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