]> git.proxmox.com Git - pve-client.git/blob - PVE/CLIHandler.pm
generate_usage_str: do no generate help for unknown commands
[pve-client.git] / PVE / CLIHandler.pm
1 package PVE::CLIHandler;
2
3 use strict;
4 use warnings;
5
6 use PVE::SafeSyslog;
7 use PVE::Exception qw(raise raise_param_exc);
8 use PVE::RESTHandler;
9
10 use base qw(PVE::RESTHandler);
11
12 # $cmddef defines which (sub)commands are available in a specific CLI class.
13 # A real command is always an array consisting of its class, name, array of
14 # position fixed (required) parameters and hash of predefined parameters when
15 # mapping a CLI command t o an API call. Optionally an output method can be
16 # passed at the end, e.g., for formatting or transformation purpose.
17 #
18 # [class, name, fixed_params, API_pre-set params, output_sub ]
19 #
20 # In case of so called 'simple commands', the $cmddef can be also just an
21 # array.
22 #
23 # Examples:
24 # $cmddef = {
25 # command => [ 'PVE::API2::Class', 'command', [ 'arg1', 'arg2' ], { node => $nodename } ],
26 # do => {
27 # this => [ 'PVE::API2::OtherClass', 'method', [ 'arg1' ], undef, sub {
28 # my ($res) = @_;
29 # print "$res\n";
30 # }],
31 # that => [ 'PVE::API2::OtherClass', 'subroutine' [] ],
32 # },
33 # dothat => { alias => 'do that' },
34 # }
35 my $cmddef;
36 my $exename;
37 my $cli_handler_class;
38
39 my $assert_initialized = sub {
40 my @caller = caller;
41 die "$caller[0]:$caller[2] - not initialized\n"
42 if !($cmddef && $exename && $cli_handler_class);
43 };
44
45 my $abort = sub {
46 my ($reason, $cmd) = @_;
47 print_usage_short (\*STDERR, $reason, $cmd);
48 exit (-1);
49 };
50
51 my $expand_command_name = sub {
52 my ($def, $cmd) = @_;
53
54 return $cmd if exists $def->{$cmd}; # command is already complete
55
56 my @expanded = grep { /^\Q$cmd\E/ } keys %$def;
57 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
58
59 return undef;
60 };
61
62 my $get_commands = sub {
63 my $def = shift // die "no command definition passed!";
64 return [ grep { !(ref($def->{$_}) eq 'HASH' && defined($def->{$_}->{alias})) } sort keys %$def ];
65 };
66
67 my $complete_command_names = sub { $get_commands->($cmddef) };
68
69 # traverses the command definition using the $argv array, resolving one level
70 # of aliases.
71 # Returns the matching (sub) command and its definition, and argument array for
72 # this (sub) command and a hash where we marked which (sub) commands got
73 # expanded (e.g. st => status) while traversing
74 sub resolve_cmd {
75 my ($argv, $is_alias) = @_;
76
77 my ($def, $cmd) = ($cmddef, $argv);
78 my $cmdstr = $exename;
79
80 if (ref($argv) eq 'ARRAY') {
81 my $expanded_last_arg;
82 my $last_arg_id = scalar(@$argv) - 1;
83
84 for my $i (0..$last_arg_id) {
85 $cmd = $expand_command_name->($def, $argv->[$i]);
86 if (defined($cmd)) {
87 # If the argument was expanded (or was already complete) and it
88 # is the final argument, tell our caller about it:
89 $expanded_last_arg = $cmd if $i == $last_arg_id;
90 } else {
91 # Otherwise continue with the unexpanded version of it.
92 $cmd = $argv->[$i];
93 }
94 $cmdstr .= " $cmd";
95 $def = $def->{$cmd};
96 last if !defined($def);
97
98 if (ref($def) eq 'ARRAY') {
99 # could expand to a real command, rest of $argv are its arguments
100 my $cmd_args = [ @$argv[$i+1..$last_arg_id] ];
101 return ($cmd, $def, $cmd_args, $expanded_last_arg, $cmdstr);
102 }
103
104 if (defined($def->{alias})) {
105 die "alias loop detected for '$cmd'" if $is_alias; # avoids cycles
106 # replace aliased (sub)command with the expanded aliased command
107 splice @$argv, $i, 1, split(/ +/, $def->{alias});
108 return resolve_cmd($argv, 1);
109 }
110 }
111 # got either a special command (bashcomplete, verifyapi) or an unknown
112 # cmd, just return first entry as cmd and the rest of $argv as cmd_arg
113 my $cmd_args = [ @$argv[1..$last_arg_id] ];
114 return ($argv->[0], $def, $cmd_args, $expanded_last_arg, $cmdstr);
115 }
116 return ($cmd, $def, undef, undef, $cmdstr);
117 }
118
119 sub generate_usage_str {
120 my ($format, $cmd, $indent, $separator, $sortfunc) = @_;
121
122 $assert_initialized->();
123 die 'format required' if !$format;
124
125 $sortfunc //= sub { sort keys %{$_[0]} };
126 $separator //= '';
127 $indent //= '';
128
129 my $read_password_func = $cli_handler_class->can('read_password');
130 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
131 $cli_handler_class->can('string_param_file_mapping');
132
133 my ($subcmd, $def, undef, undef, $cmdstr) = resolve_cmd($cmd);
134 die "no such command '$cmd->[0]'\n" if !defined($def) && ref($cmd) eq 'ARRAY';
135
136 my $generate;
137 $generate = sub {
138 my ($indent, $separator, $def, $prefix) = @_;
139
140 my $str = '';
141 if (ref($def) eq 'HASH') {
142 my $oldclass = undef;
143 foreach my $cmd (&$sortfunc($def)) {
144
145 if (ref($def->{$cmd}) eq 'ARRAY') {
146 my ($class, $name, $arg_param, $fixed_param) = @{$def->{$cmd}};
147
148 $str .= $separator if $oldclass && $oldclass ne $class;
149 $str .= $indent;
150 $str .= $class->usage_str($name, "$prefix $cmd", $arg_param,
151 $fixed_param, $format,
152 $read_password_func, $param_mapping_func);
153 $oldclass = $class;
154
155 } elsif (defined($def->{$cmd}->{alias}) && ($format eq 'asciidoc')) {
156
157 $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n";
158
159 } else {
160 next if $def->{$cmd}->{alias};
161
162 my $substr = $generate->($indent, $separator, $def->{$cmd}, "$prefix $cmd");
163 if ($substr) {
164 $substr .= $separator if $substr !~ /\Q$separator\E{2}/;
165 $str .= $substr;
166 }
167 }
168
169 }
170 } else {
171 my ($class, $name, $arg_param, $fixed_param) = @$def;
172 $abort->("unknown command '$cmd'") if !$class;
173
174 $str .= $indent;
175 $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format,
176 $read_password_func, $param_mapping_func);
177 }
178 return $str;
179 };
180
181 return $generate->($indent, $separator, $def, $cmdstr);
182 }
183
184 __PACKAGE__->register_method ({
185 name => 'help',
186 path => 'help',
187 method => 'GET',
188 description => "Get help about specified command.",
189 parameters => {
190 additionalProperties => 0,
191 properties => {
192 'extra-args' => PVE::JSONSchema::get_standard_option('extra-args', {
193 description => 'Shows help for a specific command',
194 completion => $complete_command_names,
195 }),
196 verbose => {
197 description => "Verbose output format.",
198 type => 'boolean',
199 optional => 1,
200 },
201 },
202 },
203 returns => { type => 'null' },
204
205 code => sub {
206 my ($param) = @_;
207
208 $assert_initialized->();
209
210 my $cmd = $param->{'extra-args'};
211
212 my $verbose = defined($cmd) && $cmd;
213 $verbose = $param->{verbose} if defined($param->{verbose});
214
215 if (!$cmd) {
216 if ($verbose) {
217 print_usage_verbose();
218 } else {
219 print_usage_short(\*STDOUT);
220 }
221 return undef;
222 }
223
224 my $str;
225 if ($verbose) {
226 $str = generate_usage_str('full', $cmd, '');
227 } else {
228 $str = generate_usage_str('short', $cmd, ' ' x 7);
229 }
230 $str =~ s/^\s+//;
231
232 if ($verbose) {
233 print "$str\n";
234 } else {
235 print "USAGE: $str\n";
236 }
237
238 return undef;
239
240 }});
241
242 sub print_simple_asciidoc_synopsis {
243 $assert_initialized->();
244
245 my $synopsis = "*${exename}* `help`\n\n";
246 $synopsis .= generate_usage_str('asciidoc');
247
248 return $synopsis;
249 }
250
251 sub print_asciidoc_synopsis {
252 $assert_initialized->();
253
254 my $synopsis = "";
255
256 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
257
258 $synopsis .= generate_usage_str('asciidoc');
259
260 $synopsis .= "\n";
261
262 return $synopsis;
263 }
264
265 sub print_usage_verbose {
266 $assert_initialized->();
267
268 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
269
270 my $str = generate_usage_str('full');
271
272 print "$str\n";
273 }
274
275 sub print_usage_short {
276 my ($fd, $msg, $cmd) = @_;
277
278 $assert_initialized->();
279
280 print $fd "ERROR: $msg\n" if $msg;
281 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
282
283 print {$fd} generate_usage_str('short', $cmd, ' ' x 7, "\n", sub {
284 my ($h) = @_;
285 return sort {
286 if (ref($h->{$a}) eq 'ARRAY' && ref($h->{$b}) eq 'ARRAY') {
287 # $a and $b are both real commands order them by their class
288 return $h->{$a}->[0] cmp $h->{$b}->[0] || $a cmp $b;
289 } elsif (ref($h->{$a}) eq 'ARRAY' xor ref($h->{$b}) eq 'ARRAY') {
290 # real command and subcommand mixed, put sub commands first
291 return ref($h->{$b}) eq 'ARRAY' ? -1 : 1;
292 } else {
293 # both are either from the same class or subcommands
294 return $a cmp $b;
295 }
296 } keys %$h;
297 });
298 }
299
300 my $print_bash_completion = sub {
301 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
302
303 my $debug = 0;
304
305 return if !(defined($cur) && defined($prev) && defined($bash_command));
306 return if !defined($ENV{COMP_LINE});
307 return if !defined($ENV{COMP_POINT});
308
309 my $cmdline = substr($ENV{COMP_LINE}, 0, $ENV{COMP_POINT});
310 print STDERR "\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
311
312 my $args = PVE::Tools::split_args($cmdline);
313 shift @$args; # no need for program name
314 my $print_result = sub {
315 foreach my $p (@_) {
316 print "$p\n" if $p =~ m/^$cur/;
317 }
318 };
319
320 my ($cmd, $def) = ($simple_cmd, $cmddef);
321 if (!$simple_cmd) {
322 ($cmd, $def, $args, my $expanded) = resolve_cmd($args);
323
324 if (defined($expanded) && $prev ne $expanded) {
325 print "$expanded\n";
326 return;
327 }
328
329 if (ref($def) eq 'HASH') {
330 &$print_result(@{$get_commands->($def)});
331 return;
332 }
333 }
334 return if !$def;
335
336 my $pos = scalar(@$args) - 1;
337 $pos += 1 if $cmdline =~ m/\s+$/;
338 print STDERR "pos: $pos\n" if $debug;
339 return if $pos < 0;
340
341 my $skip_param = {};
342
343 my ($class, $name, $arg_param, $uri_param) = @$def;
344 $arg_param //= [];
345 $uri_param //= {};
346
347 $arg_param = [ $arg_param ] if !ref($arg_param);
348
349 map { $skip_param->{$_} = 1; } @$arg_param;
350 map { $skip_param->{$_} = 1; } keys %$uri_param;
351
352 my $info = $class->map_method_by_name($name);
353
354 my $prop = $info->{parameters}->{properties};
355
356 my $print_parameter_completion = sub {
357 my ($pname) = @_;
358 my $d = $prop->{$pname};
359 if ($d->{completion}) {
360 my $vt = ref($d->{completion});
361 if ($vt eq 'CODE') {
362 my $res = $d->{completion}->($cmd, $pname, $cur, $args);
363 &$print_result(@$res);
364 }
365 } elsif ($d->{type} eq 'boolean') {
366 &$print_result('0', '1');
367 } elsif ($d->{enum}) {
368 &$print_result(@{$d->{enum}});
369 }
370 };
371
372 # positional arguments
373 if ($pos < scalar(@$arg_param)) {
374 my $pname = $arg_param->[$pos];
375 &$print_parameter_completion($pname);
376 return;
377 }
378
379 my @option_list = ();
380 foreach my $key (keys %$prop) {
381 next if $skip_param->{$key};
382 push @option_list, "--$key";
383 }
384
385 if ($cur =~ m/^-/) {
386 &$print_result(@option_list);
387 return;
388 }
389
390 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
391 my $pname = $1;
392 &$print_parameter_completion($pname);
393 return;
394 }
395
396 &$print_result(@option_list);
397 };
398
399 sub verify_api {
400 my ($class) = @_;
401
402 # simply verify all registered methods
403 PVE::RESTHandler::validate_method_schemas();
404 }
405
406 my $get_exe_name = sub {
407 my ($class) = @_;
408
409 my $name = $class;
410 $name =~ s/^.*:://;
411 $name =~ s/_/-/g;
412
413 return $name;
414 };
415
416 sub generate_bash_completions {
417 my ($class) = @_;
418
419 # generate bash completion config
420
421 $exename = &$get_exe_name($class);
422
423 print <<__EOD__;
424 # $exename bash completion
425
426 # see http://tiswww.case.edu/php/chet/bash/FAQ
427 # and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
428 # this modifies global var, but I found no better way
429 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
430
431 complete -o default -C '$exename bashcomplete' $exename
432 __EOD__
433 }
434
435 sub generate_asciidoc_synopsys {
436 my ($class) = @_;
437 $class->generate_asciidoc_synopsis();
438 };
439
440 sub generate_asciidoc_synopsis {
441 my ($class) = @_;
442
443 $cli_handler_class = $class;
444
445 $exename = &$get_exe_name($class);
446
447 no strict 'refs';
448 my $def = ${"${class}::cmddef"};
449 $cmddef = $def;
450
451 if (ref($def) eq 'ARRAY') {
452 print_simple_asciidoc_synopsis();
453 } else {
454 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
455
456 print_asciidoc_synopsis();
457 }
458 }
459
460 # overwrite this if you want to run/setup things early
461 sub setup_environment {
462 my ($class) = @_;
463
464 # do nothing by default
465 }
466
467 my $handle_cmd = sub {
468 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
469
470 $cmddef->{help} = [ __PACKAGE__, 'help', ['extra-args'] ];
471
472 my ($cmd, $def, $cmd_args, undef, $cmd_str) = resolve_cmd($args);
473
474 $abort->("no command specified") if !$cmd;
475
476 # call verifyapi before setup_environment(), don't execute any real code in
477 # this case
478 if ($cmd eq 'verifyapi') {
479 PVE::RESTHandler::validate_method_schemas();
480 return;
481 }
482
483 $cli_handler_class->setup_environment();
484
485 if ($cmd eq 'bashcomplete') {
486 &$print_bash_completion(undef, @$cmd_args);
487 return;
488 }
489
490 # checked special commands, if def is still a hash we got an incomplete sub command
491 $abort->("incomplete command '$cmd_str'") if ref($def) eq 'HASH';
492
493 &$preparefunc() if $preparefunc;
494
495 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def || []};
496 $abort->("unknown command '$cmd_str'") if !$class;
497
498 my $res = $class->cli_handler($cmd_str, $name, $cmd_args, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
499
500 &$outsub($res) if $outsub;
501 };
502
503 my $handle_simple_cmd = sub {
504 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
505
506 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
507 die "no class specified" if !$class;
508
509 if (scalar(@$args) >= 1) {
510 if ($args->[0] eq 'help') {
511 my $str = "USAGE: $name help\n";
512 $str .= generate_usage_str('long');
513 print STDERR "$str\n\n";
514 return;
515 } elsif ($args->[0] eq 'verifyapi') {
516 PVE::RESTHandler::validate_method_schemas();
517 return;
518 }
519 }
520
521 $cli_handler_class->setup_environment();
522
523 if (scalar(@$args) >= 1) {
524 if ($args->[0] eq 'bashcomplete') {
525 shift @$args;
526 &$print_bash_completion($name, @$args);
527 return;
528 }
529 }
530
531 &$preparefunc() if $preparefunc;
532
533 my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
534
535 &$outsub($res) if $outsub;
536 };
537
538 sub run_cli_handler {
539 my ($class, %params) = @_;
540
541 $cli_handler_class = $class;
542
543 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
544
545 foreach my $key (keys %params) {
546 next if $key eq 'prepare';
547 next if $key eq 'no_init'; # not used anymore
548 next if $key eq 'no_rpcenv'; # not used anymore
549 die "unknown parameter '$key'";
550 }
551
552 my $preparefunc = $params{prepare};
553
554 my $read_password_func = $class->can('read_password');
555 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
556 $class->can('string_param_file_mapping');
557
558 $exename = &$get_exe_name($class);
559
560 initlog($exename);
561
562 no strict 'refs';
563 $cmddef = ${"${class}::cmddef"};
564
565 if (ref($cmddef) eq 'ARRAY') {
566 &$handle_simple_cmd(\@ARGV, $read_password_func, $preparefunc, $param_mapping_func);
567 } else {
568 &$handle_cmd(\@ARGV, $read_password_func, $preparefunc, $param_mapping_func);
569 }
570
571 exit 0;
572 }
573
574 1;