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