]> git.proxmox.com Git - pve-common.git/blame - src/PVE/CLIHandler.pm
cli: allow specifying sub commands through $cmddef
[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
DM
160 properties => {
161 cmd => {
162 description => "Command name",
163 type => 'string',
164 optional => 1,
edf3d572 165 completion => $complete_command_names,
e143e9d8
DM
166 },
167 verbose => {
168 description => "Verbose output format.",
169 type => 'boolean',
170 optional => 1,
171 },
172 },
173 },
174 returns => { type => 'null' },
3ef20687 175
e143e9d8
DM
176 code => sub {
177 my ($param) = @_;
178
d204696c 179 $assert_initialized->();
e143e9d8
DM
180
181 my $cmd = $param->{cmd};
182
183 my $verbose = defined($cmd) && $cmd;
184 $verbose = $param->{verbose} if defined($param->{verbose});
185
186 if (!$cmd) {
187 if ($verbose) {
188 print_usage_verbose();
3ef20687 189 } else {
e143e9d8
DM
190 print_usage_short(\*STDOUT);
191 }
192 return undef;
193 }
194
4c802a57
TL
195 my $str;
196 if ($verbose) {
197 $str = generate_usage_str('full', $cmd, '');
198 } else {
199 $str = generate_usage_str('short', $cmd, ' ' x 7);
200 }
201 $str =~ s/^\s+//;
e143e9d8 202
e143e9d8
DM
203 if ($verbose) {
204 print "$str\n";
205 } else {
206 print "USAGE: $str\n";
207 }
208
209 return undef;
210
211 }});
212
0a5a1eee 213sub print_simple_asciidoc_synopsis {
d204696c 214 $assert_initialized->();
fe3f1fde 215
4c802a57
TL
216 my $synopsis = "*${exename}* `help`\n\n";
217 $synopsis .= generate_usage_str('asciidoc');
fe3f1fde
DM
218
219 return $synopsis;
220}
221
0a5a1eee 222sub print_asciidoc_synopsis {
d204696c 223 $assert_initialized->();
fe3f1fde 224
fe3f1fde
DM
225 my $synopsis = "";
226
227 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
228
4c802a57 229 $synopsis .= generate_usage_str('asciidoc');
fe3f1fde
DM
230
231 $synopsis .= "\n";
232
233 return $synopsis;
234}
235
e143e9d8 236sub print_usage_verbose {
d204696c 237 $assert_initialized->();
891b798d 238
e143e9d8
DM
239 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
240
4c802a57 241 my $str = generate_usage_str('full');
e143e9d8 242
4c802a57 243 print "$str\n";
e143e9d8
DM
244}
245
246sub print_usage_short {
50b89b88 247 my ($fd, $msg, $cmd) = @_;
e143e9d8 248
d204696c 249 $assert_initialized->();
891b798d 250
e143e9d8
DM
251 print $fd "ERROR: $msg\n" if $msg;
252 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
253
50b89b88 254 print {$fd} generate_usage_str('short', $cmd, ' ' x 7, "\n", sub {
4c802a57
TL
255 my ($h) = @_;
256 return sort {
257 if (ref($h->{$a}) eq 'ARRAY' && ref($h->{$b}) eq 'ARRAY') {
258 # $a and $b are both real commands order them by their class
259 return $h->{$a}->[0] cmp $h->{$b}->[0] || $a cmp $b;
50b89b88
TL
260 } elsif (ref($h->{$a}) eq 'ARRAY' xor ref($h->{$b}) eq 'ARRAY') {
261 # real command and subcommand mixed, put sub commands first
262 return ref($h->{$b}) eq 'ARRAY' ? -1 : 1;
4c802a57 263 } else {
50b89b88 264 # both are either from the same class or subcommands
4c802a57
TL
265 return $a cmp $b;
266 }
267 } keys %$h;
268 });
e143e9d8
DM
269}
270
d8053c08 271my $print_bash_completion = sub {
57e67ea3 272 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
d8053c08
DM
273
274 my $debug = 0;
275
276 return if !(defined($cur) && defined($prev) && defined($bash_command));
277 return if !defined($ENV{COMP_LINE});
278 return if !defined($ENV{COMP_POINT});
279
280 my $cmdline = substr($ENV{COMP_LINE}, 0, $ENV{COMP_POINT});
281 print STDERR "\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
282
58d9e664 283 my $args = PVE::Tools::split_args($cmdline);
5fa768fc 284 shift @$args; # no need for program name
d8053c08
DM
285 my $print_result = sub {
286 foreach my $p (@_) {
287 print "$p\n" if $p =~ m/^$cur/;
288 }
289 };
290
5fa768fc
TL
291 my ($cmd, $def) = ($simple_cmd, $cmddef);
292 if (!$simple_cmd) {
50b89b88
TL
293 ($cmd, $def, $args, my $expaned) = resolve_cmd($args);
294
295 if (ref($def) eq 'HASH') {
296 &$print_result(@{$get_commands->($def)});
297 return;
298 }
299 if (my $expanded_cmd = $expaned->{$cur}) {
300 print "$expanded_cmd\n";
d8053c08
DM
301 return;
302 }
d8053c08 303 }
d8053c08
DM
304 return if !$def;
305
5fa768fc
TL
306 my $pos = scalar(@$args) - 1;
307 $pos += 1 if $cmdline =~ m/\s+$/;
308 print STDERR "pos: $pos\n" if $debug;
309 return if $pos < 0;
d8053c08
DM
310
311 my $skip_param = {};
312
313 my ($class, $name, $arg_param, $uri_param) = @$def;
314 $arg_param //= [];
315 $uri_param //= {};
316
d90a2fd0
DM
317 $arg_param = [ $arg_param ] if !ref($arg_param);
318
d8053c08
DM
319 map { $skip_param->{$_} = 1; } @$arg_param;
320 map { $skip_param->{$_} = 1; } keys %$uri_param;
321
d8053c08
DM
322 my $info = $class->map_method_by_name($name);
323
5fa768fc 324 my $prop = $info->{parameters}->{properties};
d8053c08
DM
325
326 my $print_parameter_completion = sub {
327 my ($pname) = @_;
328 my $d = $prop->{$pname};
329 if ($d->{completion}) {
330 my $vt = ref($d->{completion});
331 if ($vt eq 'CODE') {
58d9e664 332 my $res = $d->{completion}->($cmd, $pname, $cur, $args);
d8053c08
DM
333 &$print_result(@$res);
334 }
335 } elsif ($d->{type} eq 'boolean') {
336 &$print_result('0', '1');
337 } elsif ($d->{enum}) {
338 &$print_result(@{$d->{enum}});
339 }
340 };
341
342 # positional arguments
5fa768fc
TL
343 $pos++ if $simple_cmd;
344 if ($pos < scalar(@$arg_param)) {
345 my $pname = $arg_param->[$pos];
d8053c08
DM
346 &$print_parameter_completion($pname);
347 return;
348 }
349
350 my @option_list = ();
351 foreach my $key (keys %$prop) {
352 next if $skip_param->{$key};
353 push @option_list, "--$key";
354 }
355
356 if ($cur =~ m/^-/) {
357 &$print_result(@option_list);
358 return;
359 }
360
361 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
362 my $pname = $1;
363 &$print_parameter_completion($pname);
364 return;
365 }
366
367 &$print_result(@option_list);
368};
369
1f130ba6
DM
370sub verify_api {
371 my ($class) = @_;
372
373 # simply verify all registered methods
374 PVE::RESTHandler::validate_method_schemas();
375}
376
8f3712f8
DM
377my $get_exe_name = sub {
378 my ($class) = @_;
3ef20687 379
8f3712f8
DM
380 my $name = $class;
381 $name =~ s/^.*:://;
382 $name =~ s/_/-/g;
383
384 return $name;
385};
386
c45707a0
DM
387sub generate_bash_completions {
388 my ($class) = @_;
389
390 # generate bash completion config
391
8f3712f8 392 $exename = &$get_exe_name($class);
c45707a0
DM
393
394 print <<__EOD__;
395# $exename bash completion
396
397# see http://tiswww.case.edu/php/chet/bash/FAQ
398# and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
399# this modifies global var, but I found no better way
400COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
401
e4a1d8e2 402complete -o default -C '$exename bashcomplete' $exename
c45707a0
DM
403__EOD__
404}
405
fe3f1fde
DM
406sub generate_asciidoc_synopsys {
407 my ($class) = @_;
0a5a1eee
FG
408 $class->generate_asciidoc_synopsis();
409};
410
411sub generate_asciidoc_synopsis {
412 my ($class) = @_;
fe3f1fde
DM
413
414 $cli_handler_class = $class;
415
416 $exename = &$get_exe_name($class);
417
418 no strict 'refs';
419 my $def = ${"${class}::cmddef"};
57e67ea3 420 $cmddef = $def;
fe3f1fde
DM
421
422 if (ref($def) eq 'ARRAY') {
4c802a57 423 print_simple_asciidoc_synopsis();
fe3f1fde 424 } else {
fe3f1fde
DM
425 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
426
0a5a1eee 427 print_asciidoc_synopsis();
fe3f1fde
DM
428 }
429}
430
7b7f99c9
DM
431# overwrite this if you want to run/setup things early
432sub setup_environment {
433 my ($class) = @_;
434
435 # do nothing by default
436}
437
891b798d 438my $handle_cmd = sub {
57e67ea3 439 my ($args, $pwcallback, $preparefunc, $stringfilemap) = @_;
e143e9d8
DM
440
441 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
442
50b89b88
TL
443 my $cmd_str = join(' ', @$args);
444 my ($cmd, $def, $cmd_args) = resolve_cmd($args);
7b7f99c9 445
918140af
TL
446 $abort->("no command specified") if !$cmd;
447
448 # call verifyapi before setup_environment(), don't execute any real code in
449 # this case
450 if ($cmd eq 'verifyapi') {
e143e9d8
DM
451 PVE::RESTHandler::validate_method_schemas();
452 return;
7b7f99c9
DM
453 }
454
455 $cli_handler_class->setup_environment();
456
457 if ($cmd eq 'bashcomplete') {
50b89b88 458 &$print_bash_completion(undef, @$cmd_args);
d8053c08 459 return;
e143e9d8
DM
460 }
461
50b89b88
TL
462 # checked special commands, if def is still a hash we got an incomplete sub command
463 $abort->("incomplete command '$exename $cmd_str'") if ref($def) eq 'HASH';
8e3e9929 464
50b89b88 465 &$preparefunc() if $preparefunc;
e143e9d8
DM
466
467 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef->{$cmd} || []};
50b89b88 468 $abort->("unknown command '$cmd_str'") if !$class;
e143e9d8 469
50b89b88
TL
470 my $prefix = "$exename $cmd_str";
471 my $res = $class->cli_handler($prefix, $name, $cmd_args, $arg_param, $uri_param, $pwcallback, $stringfilemap);
2026f4b5
DM
472
473 &$outsub($res) if $outsub;
891b798d 474};
2026f4b5 475
891b798d 476my $handle_simple_cmd = sub {
57e67ea3 477 my ($args, $pwcallback, $preparefunc, $stringfilemap) = @_;
2026f4b5 478
57e67ea3 479 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
2026f4b5
DM
480 die "no class specified" if !$class;
481
d8053c08 482 if (scalar(@$args) >= 1) {
2026f4b5
DM
483 if ($args->[0] eq 'help') {
484 my $str = "USAGE: $name help\n";
4c802a57 485 $str .= generate_usage_str('long');
2026f4b5
DM
486 print STDERR "$str\n\n";
487 return;
488 } elsif ($args->[0] eq 'verifyapi') {
489 PVE::RESTHandler::validate_method_schemas();
490 return;
2026f4b5 491 }
e143e9d8 492 }
2026f4b5 493
7b7f99c9
DM
494 $cli_handler_class->setup_environment();
495
496 if (scalar(@$args) >= 1) {
497 if ($args->[0] eq 'bashcomplete') {
498 shift @$args;
57e67ea3 499 &$print_bash_completion($name, @$args);
7b7f99c9
DM
500 return;
501 }
502 }
503
7fe1f565
DM
504 &$preparefunc() if $preparefunc;
505
408976c6 506 my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
2026f4b5
DM
507
508 &$outsub($res) if $outsub;
891b798d
DM
509};
510
891b798d
DM
511sub run_cli_handler {
512 my ($class, %params) = @_;
513
514 $cli_handler_class = $class;
515
516 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
517
aa9b9af5 518 foreach my $key (keys %params) {
5ae87c41 519 next if $key eq 'prepare';
1042b82c
DM
520 next if $key eq 'no_init'; # not used anymore
521 next if $key eq 'no_rpcenv'; # not used anymore
aa9b9af5
DM
522 die "unknown parameter '$key'";
523 }
524
5ae87c41 525 my $preparefunc = $params{prepare};
891b798d
DM
526
527 my $pwcallback = $class->can('read_password');
408976c6 528 my $stringfilemap = $class->can('string_param_file_mapping');
891b798d
DM
529
530 $exename = &$get_exe_name($class);
531
532 initlog($exename);
533
891b798d 534 no strict 'refs';
57e67ea3 535 $cmddef = ${"${class}::cmddef"};
891b798d 536
57e67ea3
TL
537 if (ref($cmddef) eq 'ARRAY') {
538 &$handle_simple_cmd(\@ARGV, $pwcallback, $preparefunc, $stringfilemap);
891b798d 539 } else {
57e67ea3 540 &$handle_cmd(\@ARGV, $pwcallback, $preparefunc, $stringfilemap);
891b798d
DM
541 }
542
543 exit 0;
e143e9d8
DM
544}
545
5461;