]> git.proxmox.com Git - pve-common.git/blame - src/PVE/CLIHandler.pm
cli: refactor comand name helper
[pve-common.git] / src / PVE / CLIHandler.pm
CommitLineData
e143e9d8
DM
1package PVE::CLIHandler;
2
3use strict;
4use warnings;
5
93ddd7bc 6use PVE::SafeSyslog;
e143e9d8
DM
7use PVE::Exception qw(raise raise_param_exc);
8use PVE::RESTHandler;
881eb755 9use PVE::INotify;
e143e9d8
DM
10
11use base qw(PVE::RESTHandler);
12
13my $cmddef;
14my $exename;
891b798d 15my $cli_handler_class;
e143e9d8 16
d204696c
TL
17my $assert_initialized = sub {
18 my @caller = caller;
19 die "$caller[0]:$caller[2] - not initialized\n"
20 if !($cmddef && $exename && $cli_handler_class);
21};
22
e143e9d8
DM
23my $expand_command_name = sub {
24 my ($def, $cmd) = @_;
25
26 if (!$def->{$cmd}) {
7bac844e
TL
27 my @expanded = grep { /^\Q$cmd\E/ } keys %$def;
28 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
e143e9d8
DM
29 }
30 return $cmd;
31};
32
edf3d572 33my $complete_command_names = sub {
7bac844e 34 return [ sort keys %$cmddef ];
edf3d572
DM
35};
36
e143e9d8 37__PACKAGE__->register_method ({
3ef20687 38 name => 'help',
e143e9d8
DM
39 path => 'help',
40 method => 'GET',
41 description => "Get help about specified command.",
42 parameters => {
3ef20687 43 additionalProperties => 0,
e143e9d8
DM
44 properties => {
45 cmd => {
46 description => "Command name",
47 type => 'string',
48 optional => 1,
edf3d572 49 completion => $complete_command_names,
e143e9d8
DM
50 },
51 verbose => {
52 description => "Verbose output format.",
53 type => 'boolean',
54 optional => 1,
55 },
56 },
57 },
58 returns => { type => 'null' },
3ef20687 59
e143e9d8
DM
60 code => sub {
61 my ($param) = @_;
62
d204696c 63 $assert_initialized->();
e143e9d8
DM
64
65 my $cmd = $param->{cmd};
66
67 my $verbose = defined($cmd) && $cmd;
68 $verbose = $param->{verbose} if defined($param->{verbose});
69
70 if (!$cmd) {
71 if ($verbose) {
72 print_usage_verbose();
3ef20687 73 } else {
e143e9d8
DM
74 print_usage_short(\*STDOUT);
75 }
76 return undef;
77 }
78
79 $cmd = &$expand_command_name($cmddef, $cmd);
80
81 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd} || []};
82
83 raise_param_exc({ cmd => "no such command '$cmd'"}) if !$class;
84
891b798d 85 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 86 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
e143e9d8 87
891b798d 88 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param,
4845032a
FG
89 $verbose ? 'full' : 'short', $pwcallback,
90 $stringfilemap);
e143e9d8
DM
91 if ($verbose) {
92 print "$str\n";
93 } else {
94 print "USAGE: $str\n";
95 }
96
97 return undef;
98
99 }});
100
0a5a1eee 101sub print_simple_asciidoc_synopsis {
fe3f1fde
DM
102 my ($class, $name, $arg_param, $uri_param) = @_;
103
d204696c 104 $assert_initialized->();
fe3f1fde
DM
105
106 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 107 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
fe3f1fde
DM
108
109 my $synopsis = "*${name}* `help`\n\n";
110
4845032a
FG
111 $synopsis .= $class->usage_str($name, $name, $arg_param, $uri_param,
112 'asciidoc', $pwcallback, $stringfilemap);
fe3f1fde
DM
113
114 return $synopsis;
115}
116
0a5a1eee 117sub print_asciidoc_synopsis {
fe3f1fde 118
d204696c 119 $assert_initialized->();
fe3f1fde
DM
120
121 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 122 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
fe3f1fde
DM
123
124 my $synopsis = "";
125
126 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
127
128 my $oldclass;
129 foreach my $cmd (sort keys %$cmddef) {
130 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
131 my $str = $class->usage_str($name, "$exename $cmd", $arg_param,
4845032a
FG
132 $uri_param, 'asciidoc', $pwcallback,
133 $stringfilemap);
fe3f1fde
DM
134 $synopsis .= "\n" if $oldclass && $oldclass ne $class;
135
136 $synopsis .= "$str\n\n";
137 $oldclass = $class;
138 }
139
140 $synopsis .= "\n";
141
142 return $synopsis;
143}
144
e143e9d8
DM
145sub print_usage_verbose {
146
d204696c 147 $assert_initialized->();
891b798d
DM
148
149 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 150 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
e143e9d8
DM
151
152 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
153
154 foreach my $cmd (sort keys %$cmddef) {
155 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
891b798d 156 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param,
4845032a 157 'full', $pwcallback, $stringfilemap);
e143e9d8
DM
158 print "$str\n\n";
159 }
160}
161
162sub sorted_commands {
163 return sort { ($cmddef->{$a}->[0] cmp $cmddef->{$b}->[0]) || ($a cmp $b)} keys %$cmddef;
164}
165
166sub print_usage_short {
167 my ($fd, $msg) = @_;
168
d204696c 169 $assert_initialized->();
891b798d
DM
170
171 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 172 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
e143e9d8
DM
173
174 print $fd "ERROR: $msg\n" if $msg;
175 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
176
177 my $oldclass;
178 foreach my $cmd (sorted_commands()) {
179 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
4845032a 180 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param, 'short', $pwcallback, $stringfilemap);
e143e9d8
DM
181 print $fd "\n" if $oldclass && $oldclass ne $class;
182 print $fd " $str";
183 $oldclass = $class;
184 }
185}
186
d8053c08 187my $print_bash_completion = sub {
57e67ea3 188 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
d8053c08
DM
189
190 my $debug = 0;
191
192 return if !(defined($cur) && defined($prev) && defined($bash_command));
193 return if !defined($ENV{COMP_LINE});
194 return if !defined($ENV{COMP_POINT});
195
196 my $cmdline = substr($ENV{COMP_LINE}, 0, $ENV{COMP_POINT});
197 print STDERR "\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
198
58d9e664
DM
199 my $args = PVE::Tools::split_args($cmdline);
200 my $pos = scalar(@$args) - 2;
d8053c08
DM
201 $pos += 1 if $cmdline =~ m/\s+$/;
202
203 print STDERR "CMDLINE:$pos:$cmdline\n" if $debug;
204
205 return if $pos < 0;
206
207 my $print_result = sub {
208 foreach my $p (@_) {
209 print "$p\n" if $p =~ m/^$cur/;
210 }
211 };
212
213 my $cmd;
214 if ($simple_cmd) {
215 $cmd = $simple_cmd;
216 } else {
217 if ($pos == 0) {
218 &$print_result(keys %$cmddef);
219 return;
220 }
58d9e664 221 $cmd = $args->[1];
d8053c08
DM
222 }
223
224 my $def = $cmddef->{$cmd};
225 return if !$def;
226
227 print STDERR "CMDLINE1:$pos:$cmdline\n" if $debug;
228
229 my $skip_param = {};
230
231 my ($class, $name, $arg_param, $uri_param) = @$def;
232 $arg_param //= [];
233 $uri_param //= {};
234
d90a2fd0
DM
235 $arg_param = [ $arg_param ] if !ref($arg_param);
236
d8053c08
DM
237 map { $skip_param->{$_} = 1; } @$arg_param;
238 map { $skip_param->{$_} = 1; } keys %$uri_param;
239
240 my $fpcount = scalar(@$arg_param);
241
242 my $info = $class->map_method_by_name($name);
243
244 my $schema = $info->{parameters};
245 my $prop = $schema->{properties};
246
247 my $print_parameter_completion = sub {
248 my ($pname) = @_;
249 my $d = $prop->{$pname};
250 if ($d->{completion}) {
251 my $vt = ref($d->{completion});
252 if ($vt eq 'CODE') {
58d9e664 253 my $res = $d->{completion}->($cmd, $pname, $cur, $args);
d8053c08
DM
254 &$print_result(@$res);
255 }
256 } elsif ($d->{type} eq 'boolean') {
257 &$print_result('0', '1');
258 } elsif ($d->{enum}) {
259 &$print_result(@{$d->{enum}});
260 }
261 };
262
263 # positional arguments
264 $pos += 1 if $simple_cmd;
265 if ($fpcount && $pos <= $fpcount) {
266 my $pname = $arg_param->[$pos -1];
267 &$print_parameter_completion($pname);
268 return;
269 }
270
271 my @option_list = ();
272 foreach my $key (keys %$prop) {
273 next if $skip_param->{$key};
274 push @option_list, "--$key";
275 }
276
277 if ($cur =~ m/^-/) {
278 &$print_result(@option_list);
279 return;
280 }
281
282 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
283 my $pname = $1;
284 &$print_parameter_completion($pname);
285 return;
286 }
287
288 &$print_result(@option_list);
289};
290
1f130ba6
DM
291sub verify_api {
292 my ($class) = @_;
293
294 # simply verify all registered methods
295 PVE::RESTHandler::validate_method_schemas();
296}
297
8f3712f8
DM
298my $get_exe_name = sub {
299 my ($class) = @_;
3ef20687 300
8f3712f8
DM
301 my $name = $class;
302 $name =~ s/^.*:://;
303 $name =~ s/_/-/g;
304
305 return $name;
306};
307
c45707a0
DM
308sub generate_bash_completions {
309 my ($class) = @_;
310
311 # generate bash completion config
312
8f3712f8 313 $exename = &$get_exe_name($class);
c45707a0
DM
314
315 print <<__EOD__;
316# $exename bash completion
317
318# see http://tiswww.case.edu/php/chet/bash/FAQ
319# and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
320# this modifies global var, but I found no better way
321COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
322
e4a1d8e2 323complete -o default -C '$exename bashcomplete' $exename
c45707a0
DM
324__EOD__
325}
326
fe3f1fde
DM
327sub generate_asciidoc_synopsys {
328 my ($class) = @_;
0a5a1eee
FG
329 $class->generate_asciidoc_synopsis();
330};
331
332sub generate_asciidoc_synopsis {
333 my ($class) = @_;
fe3f1fde
DM
334
335 $cli_handler_class = $class;
336
337 $exename = &$get_exe_name($class);
338
339 no strict 'refs';
340 my $def = ${"${class}::cmddef"};
57e67ea3 341 $cmddef = $def;
fe3f1fde
DM
342
343 if (ref($def) eq 'ARRAY') {
0a5a1eee 344 print_simple_asciidoc_synopsis(@$def);
fe3f1fde 345 } else {
fe3f1fde
DM
346 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
347
0a5a1eee 348 print_asciidoc_synopsis();
fe3f1fde
DM
349 }
350}
351
7b7f99c9
DM
352# overwrite this if you want to run/setup things early
353sub setup_environment {
354 my ($class) = @_;
355
356 # do nothing by default
357}
358
891b798d 359my $handle_cmd = sub {
57e67ea3 360 my ($args, $pwcallback, $preparefunc, $stringfilemap) = @_;
e143e9d8
DM
361
362 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
363
7b7f99c9
DM
364 # call verifyapi before setup_environment(), because we do not want to
365 # execute any real code in this case
366
57e67ea3 367 my $cmd = shift @$args;
7b7f99c9 368 if (!$cmd) {
e143e9d8
DM
369 print_usage_short (\*STDERR, "no command specified");
370 exit (-1);
371 } elsif ($cmd eq 'verifyapi') {
372 PVE::RESTHandler::validate_method_schemas();
373 return;
7b7f99c9
DM
374 }
375
376 $cli_handler_class->setup_environment();
377
378 if ($cmd eq 'bashcomplete') {
57e67ea3 379 &$print_bash_completion(undef, @$args);
d8053c08 380 return;
e143e9d8
DM
381 }
382
8e3e9929
WB
383 &$preparefunc() if $preparefunc;
384
e143e9d8
DM
385 $cmd = &$expand_command_name($cmddef, $cmd);
386
387 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef->{$cmd} || []};
388
389 if (!$class) {
390 print_usage_short (\*STDERR, "unknown command '$cmd'");
391 exit (-1);
392 }
393
394 my $prefix = "$exename $cmd";
408976c6 395 my $res = $class->cli_handler($prefix, $name, \@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
2026f4b5
DM
396
397 &$outsub($res) if $outsub;
891b798d 398};
2026f4b5 399
891b798d 400my $handle_simple_cmd = sub {
57e67ea3 401 my ($args, $pwcallback, $preparefunc, $stringfilemap) = @_;
2026f4b5 402
57e67ea3 403 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
2026f4b5
DM
404 die "no class specified" if !$class;
405
d8053c08 406 if (scalar(@$args) >= 1) {
2026f4b5
DM
407 if ($args->[0] eq 'help') {
408 my $str = "USAGE: $name help\n";
4845032a 409 $str .= $class->usage_str($name, $name, $arg_param, $uri_param, 'long', $pwcallback, $stringfilemap);
2026f4b5
DM
410 print STDERR "$str\n\n";
411 return;
412 } elsif ($args->[0] eq 'verifyapi') {
413 PVE::RESTHandler::validate_method_schemas();
414 return;
2026f4b5 415 }
e143e9d8 416 }
2026f4b5 417
7b7f99c9
DM
418 $cli_handler_class->setup_environment();
419
420 if (scalar(@$args) >= 1) {
421 if ($args->[0] eq 'bashcomplete') {
422 shift @$args;
57e67ea3 423 &$print_bash_completion($name, @$args);
7b7f99c9
DM
424 return;
425 }
426 }
427
7fe1f565
DM
428 &$preparefunc() if $preparefunc;
429
408976c6 430 my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
2026f4b5
DM
431
432 &$outsub($res) if $outsub;
891b798d
DM
433};
434
891b798d
DM
435sub run_cli_handler {
436 my ($class, %params) = @_;
437
438 $cli_handler_class = $class;
439
440 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
441
aa9b9af5 442 foreach my $key (keys %params) {
5ae87c41 443 next if $key eq 'prepare';
1042b82c
DM
444 next if $key eq 'no_init'; # not used anymore
445 next if $key eq 'no_rpcenv'; # not used anymore
aa9b9af5
DM
446 die "unknown parameter '$key'";
447 }
448
5ae87c41 449 my $preparefunc = $params{prepare};
891b798d
DM
450
451 my $pwcallback = $class->can('read_password');
408976c6 452 my $stringfilemap = $class->can('string_param_file_mapping');
891b798d
DM
453
454 $exename = &$get_exe_name($class);
455
456 initlog($exename);
457
891b798d 458 no strict 'refs';
57e67ea3 459 $cmddef = ${"${class}::cmddef"};
891b798d 460
57e67ea3
TL
461 if (ref($cmddef) eq 'ARRAY') {
462 &$handle_simple_cmd(\@ARGV, $pwcallback, $preparefunc, $stringfilemap);
891b798d 463 } else {
57e67ea3 464 &$handle_cmd(\@ARGV, $pwcallback, $preparefunc, $stringfilemap);
891b798d
DM
465 }
466
467 exit 0;
e143e9d8
DM
468}
469
4701;