1 package PVE
::CLIHandler
;
7 use PVE
::Exception
qw(raise raise_param_exc);
11 use base
qw(PVE::RESTHandler);
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.
19 # [class, name, fixed_params, API_pre-set params, output_sub ]
21 # In case of so called 'simple commands', the $cmddef can be also just an
26 # command => [ 'PVE::API2::Class', 'command', [ 'arg1', 'arg2' ], { node => $nodename } ],
28 # this => [ 'PVE::API2::OtherClass', 'method', [ 'arg1' ], undef, sub {
32 # that => [ 'PVE::API2::OtherClass', 'subroutine' [] ],
34 # dothat => { alias => 'do that' },
38 my $cli_handler_class;
40 my $assert_initialized = sub {
42 die "$caller[0]:$caller[2] - not initialized\n"
43 if !($cmddef && $exename && $cli_handler_class);
47 my ($reason, $cmd) = @_;
48 print_usage_short
(\
*STDERR
, $reason, $cmd);
52 my $expand_command_name = sub {
55 return $cmd if exists $def->{$cmd}; # command is already complete
57 my $is_alias = sub { ref($_[0]) eq 'HASH' && exists($_[0]->{alias
}) };
58 my @expanded = grep { /^\Q$cmd\E/ && !$is_alias->($def->{$_}) } keys %$def;
60 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
65 my $get_commands = sub {
66 my $def = shift // die "no command definition passed!";
67 return [ grep { !(ref($def->{$_}) eq 'HASH' && defined($def->{$_}->{alias
})) } sort keys %$def ];
70 my $complete_command_names = sub { $get_commands->($cmddef) };
72 # traverses the command definition using the $argv array, resolving one level
74 # Returns the matching (sub) command and its definition, and argument array for
75 # this (sub) command and a hash where we marked which (sub) commands got
76 # expanded (e.g. st => status) while traversing
78 my ($argv, $is_alias) = @_;
80 my ($def, $cmd) = ($cmddef, $argv);
81 my $cmdstr = $exename;
83 if (ref($argv) eq 'ARRAY') {
84 my $expanded_last_arg;
85 my $last_arg_id = scalar(@$argv) - 1;
87 for my $i (0..$last_arg_id) {
88 $cmd = $expand_command_name->($def, $argv->[$i]);
90 # If the argument was expanded (or was already complete) and it
91 # is the final argument, tell our caller about it:
92 $expanded_last_arg = $cmd if $i == $last_arg_id;
94 # Otherwise continue with the unexpanded version of it.
99 last if !defined($def);
101 if (ref($def) eq 'ARRAY') {
102 # could expand to a real command, rest of $argv are its arguments
103 my $cmd_args = [ @$argv[$i+1..$last_arg_id] ];
104 return ($cmd, $def, $cmd_args, $expanded_last_arg, $cmdstr);
107 if (defined($def->{alias
})) {
108 die "alias loop detected for '$cmd'" if $is_alias; # avoids cycles
109 # replace aliased (sub)command with the expanded aliased command
110 splice @$argv, $i, 1, split(/ +/, $def->{alias
});
111 return resolve_cmd
($argv, 1);
114 # got either a special command (bashcomplete, verifyapi) or an unknown
115 # cmd, just return first entry as cmd and the rest of $argv as cmd_arg
116 my $cmd_args = [ @$argv[1..$last_arg_id] ];
117 return ($argv->[0], $def, $cmd_args, $expanded_last_arg, $cmdstr);
119 return ($cmd, $def, undef, undef, $cmdstr);
122 sub generate_usage_str
{
123 my ($format, $cmd, $indent, $separator, $sortfunc) = @_;
125 $assert_initialized->();
126 die 'format required' if !$format;
128 $sortfunc //= sub { sort keys %{$_[0]} };
132 my $read_password_func = $cli_handler_class->can('read_password');
133 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
134 $cli_handler_class->can('string_param_file_mapping');
136 my ($subcmd, $def, undef, undef, $cmdstr) = resolve_cmd
($cmd);
137 $abort->("unknown command '$cmdstr'") if !defined($def) && ref($cmd) eq 'ARRAY';
141 my ($indent, $separator, $def, $prefix) = @_;
144 if (ref($def) eq 'HASH') {
145 my $oldclass = undef;
146 foreach my $cmd (&$sortfunc($def)) {
148 if (ref($def->{$cmd}) eq 'ARRAY') {
149 my ($class, $name, $arg_param, $fixed_param) = @{$def->{$cmd}};
151 $str .= $separator if $oldclass && $oldclass ne $class;
153 $str .= $class->usage_str($name, "$prefix $cmd", $arg_param,
154 $fixed_param, $format,
155 $read_password_func, $param_mapping_func);
158 } elsif (defined($def->{$cmd}->{alias
}) && ($format eq 'asciidoc')) {
160 $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n";
163 next if $def->{$cmd}->{alias
};
165 my $substr = $generate->($indent, $separator, $def->{$cmd}, "$prefix $cmd");
167 $substr .= $separator if $substr !~ /\Q$separator\E{2}/;
174 my ($class, $name, $arg_param, $fixed_param) = @$def;
175 $abort->("unknown command '$cmd'") if !$class;
178 $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format,
179 $read_password_func, $param_mapping_func);
184 return $generate->($indent, $separator, $def, $cmdstr);
187 __PACKAGE__-
>register_method ({
191 description
=> "Get help about specified command.",
193 additionalProperties
=> 0,
195 'extra-args' => PVE
::JSONSchema
::get_standard_option
('extra-args', {
196 description
=> 'Shows help for a specific command',
197 completion
=> $complete_command_names,
200 description
=> "Verbose output format.",
206 returns
=> { type
=> 'null' },
211 $assert_initialized->();
213 my $cmd = $param->{'extra-args'};
215 my $verbose = defined($cmd) && $cmd;
216 $verbose = $param->{verbose
} if defined($param->{verbose
});
220 print_usage_verbose
();
222 print_usage_short
(\
*STDOUT
);
229 $str = generate_usage_str
('full', $cmd, '');
231 $str = generate_usage_str
('short', $cmd, ' ' x
7);
238 print "USAGE: $str\n";
245 sub print_simple_asciidoc_synopsis
{
246 $assert_initialized->();
248 my $synopsis = "*${exename}* `help`\n\n";
249 $synopsis .= generate_usage_str
('asciidoc');
254 sub print_asciidoc_synopsis
{
255 $assert_initialized->();
259 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
261 $synopsis .= generate_usage_str
('asciidoc');
268 sub print_usage_verbose
{
269 $assert_initialized->();
271 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
273 my $str = generate_usage_str
('full');
278 sub print_usage_short
{
279 my ($fd, $msg, $cmd) = @_;
281 $assert_initialized->();
283 print $fd "ERROR: $msg\n" if $msg;
284 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
286 print {$fd} generate_usage_str
('short', $cmd, ' ' x
7, "\n", sub {
289 if (ref($h->{$a}) eq 'ARRAY' && ref($h->{$b}) eq 'ARRAY') {
290 # $a and $b are both real commands order them by their class
291 return $h->{$a}->[0] cmp $h->{$b}->[0] || $a cmp $b;
292 } elsif (ref($h->{$a}) eq 'ARRAY' xor ref($h->{$b}) eq 'ARRAY') {
293 # real command and subcommand mixed, put sub commands first
294 return ref($h->{$b}) eq 'ARRAY' ?
-1 : 1;
296 # both are either from the same class or subcommands
303 my $print_bash_completion = sub {
304 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
308 return if !(defined($cur) && defined($prev) && defined($bash_command));
309 return if !defined($ENV{COMP_LINE
});
310 return if !defined($ENV{COMP_POINT
});
312 my $cmdline = substr($ENV{COMP_LINE
}, 0, $ENV{COMP_POINT
});
313 print STDERR
"\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
315 my $args = PVE
::Tools
::split_args
($cmdline);
316 shift @$args; # no need for program name
317 my $print_result = sub {
319 print "$p\n" if $p =~ m/^\Q$cur\E/;
323 my ($cmd, $def) = ($simple_cmd, $cmddef);
325 ($cmd, $def, $args, my $expanded) = resolve_cmd
($args);
327 if (defined($expanded) && $prev ne $expanded) {
332 if (ref($def) eq 'HASH') {
333 &$print_result(@{$get_commands->($def)});
339 my $pos = scalar(@$args) - 1;
340 $pos += 1 if $cmdline =~ m/\s+$/;
341 print STDERR
"pos: $pos\n" if $debug;
346 my ($class, $name, $arg_param, $uri_param) = @$def;
350 $arg_param = [ $arg_param ] if !ref($arg_param);
352 map { $skip_param->{$_} = 1; } @$arg_param;
353 map { $skip_param->{$_} = 1; } keys %$uri_param;
355 my $info = $class->map_method_by_name($name);
357 my $prop = $info->{parameters
}->{properties
};
359 my $print_parameter_completion = sub {
361 my $d = $prop->{$pname};
362 if ($d->{completion
}) {
363 my $vt = ref($d->{completion
});
365 my $res = $d->{completion
}->($cmd, $pname, $cur, $args);
366 &$print_result(@$res);
368 } elsif ($d->{type
} eq 'boolean') {
369 &$print_result('0', '1');
370 } elsif ($d->{enum
}) {
371 &$print_result(@{$d->{enum
}});
375 # positional arguments
376 if ($pos < scalar(@$arg_param)) {
377 my $pname = $arg_param->[$pos];
378 &$print_parameter_completion($pname);
382 my @option_list = ();
383 foreach my $key (keys %$prop) {
384 next if $skip_param->{$key};
385 push @option_list, "--$key";
389 &$print_result(@option_list);
393 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
395 &$print_parameter_completion($pname);
399 &$print_result(@option_list);
402 # prints a formatted table with a title row.
403 # $formatopts is an array of hashes, with the following keys:
404 # 'key' - the key in the data-objects to use for this column
405 # 'title' - the title to print above the column, defaults to 'key' - always gets printed in full
406 # 'cutoff' - the maximal length of the data, overlong values will be truncated
407 # 'default' - an optional default value for the column
408 # the last column always gets printed in full
409 sub print_text_table
{
410 my ($formatopts, $data) = @_;
411 my ($formatstring, @keys, @titles, %cutoffs, %defaults, $last_col);
413 $last_col = $formatopts->[$#{$formatopts}];
414 foreach my $col ( @$formatopts ) {
415 my ($key, $title, $cutoff, $default) = @$col{ qw(key title cutoff default)};
419 push @titles, $title;
420 $defaults{$key} = $default;
422 #calculate maximal print width and cutoff
423 my $titlelen = length($title);
425 my $longest = $titlelen;
426 foreach my $entry (@$data) {
427 my $len = length($entry->{$key}) // 0;
428 $longest = $len if $len > $longest;
431 $cutoff = (defined($cutoff) && $cutoff < $longest) ?
$cutoff : $longest;
432 $cutoffs{$key} = $cutoff;
434 my $printalign = $cutoff > $titlelen ?
'-' : '';
435 if ($col == $last_col) {
436 $formatstring .= "%${printalign}${titlelen}s\n";
438 $formatstring .= "%${printalign}${cutoff}s ";
442 printf $formatstring, @titles;
444 foreach my $entry (sort { $a->{$keys[0]} cmp $b->{$keys[0]} } @$data){
445 printf $formatstring, map { substr(($entry->{$_} // $defaults{$_}), 0 , $cutoffs{$_}) } @keys;
451 #TODO: handle objects/hashes as well
452 foreach my $item (sort keys %$entry) {
453 if (ref($entry->{$item}) eq 'ARRAY'){
454 printf "%s: [ %s ]\n", $item, join(", ", @{$entry->{$item}});
456 printf "%s: %s\n", $item, $entry->{$item};
461 # used to print the result of an API-listing - expects the API to return an array
462 # and to have the results key of the API call defined.
464 my ($props_to_print, $data, $returninfo) = @_;
466 my $returnprops = $returninfo->{items
}->{properties
};
467 foreach my $prop ( @$props_to_print ) {
468 my $propinfo = $returnprops->{$prop};
471 title
=> $propinfo->{title
},
472 default => $propinfo->{default},
473 cutoff
=> $propinfo->{print_width
} // $propinfo->{maxLength
},
475 push @$formatopts, $colopts;
478 print_text_table
($formatopts, $data);
484 # simply verify all registered methods
485 PVE
::RESTHandler
::validate_method_schemas
();
488 my $get_exe_name = sub {
498 sub generate_bash_completions
{
501 # generate bash completion config
503 $exename = &$get_exe_name($class);
506 # $exename bash completion
508 # see http://tiswww.case.edu/php/chet/bash/FAQ
509 # and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
510 # this modifies global var, but I found no better way
511 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
513 complete -o default -C '$exename bashcomplete' $exename
517 sub generate_asciidoc_synopsys
{
519 $class->generate_asciidoc_synopsis();
522 sub generate_asciidoc_synopsis
{
525 $cli_handler_class = $class;
527 $exename = &$get_exe_name($class);
530 my $def = ${"${class}::cmddef"};
533 if (ref($def) eq 'ARRAY') {
534 print_simple_asciidoc_synopsis
();
536 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['cmd'] ];
538 print_asciidoc_synopsis
();
542 # overwrite this if you want to run/setup things early
543 sub setup_environment
{
546 # do nothing by default
549 my $handle_cmd = sub {
550 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
552 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['extra-args'] ];
554 my ($cmd, $def, $cmd_args, undef, $cmd_str) = resolve_cmd
($args);
556 $abort->("no command specified") if !$cmd;
558 # call verifyapi before setup_environment(), don't execute any real code in
560 if ($cmd eq 'verifyapi') {
561 PVE
::RESTHandler
::validate_method_schemas
();
565 $cli_handler_class->setup_environment();
567 if ($cmd eq 'bashcomplete') {
568 &$print_bash_completion(undef, @$cmd_args);
572 # checked special commands, if def is still a hash we got an incomplete sub command
573 $abort->("incomplete command '$cmd_str'", $args) if ref($def) eq 'HASH';
575 &$preparefunc() if $preparefunc;
577 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def || []};
578 $abort->("unknown command '$cmd_str'") if !$class;
580 my $res = $class->cli_handler($cmd_str, $name, $cmd_args, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
582 if (defined $outsub) {
583 my $returninfo = $class->map_method_by_name($name)->{returns
};
584 $outsub->($res, $returninfo);
588 my $handle_simple_cmd = sub {
589 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
591 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
592 die "no class specified" if !$class;
594 if (scalar(@$args) >= 1) {
595 if ($args->[0] eq 'help') {
596 my $str = "USAGE: $name help\n";
597 $str .= generate_usage_str
('long');
598 print STDERR
"$str\n\n";
600 } elsif ($args->[0] eq 'verifyapi') {
601 PVE
::RESTHandler
::validate_method_schemas
();
606 $cli_handler_class->setup_environment();
608 if (scalar(@$args) >= 1) {
609 if ($args->[0] eq 'bashcomplete') {
611 &$print_bash_completion($name, @$args);
616 &$preparefunc() if $preparefunc;
618 my $res = $class->cli_handler($name, $name, \
@ARGV, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
620 if (defined $outsub) {
621 my $returninfo = $class->map_method_by_name($name)->{returns
};
622 $outsub->($res, $returninfo);
626 sub run_cli_handler
{
627 my ($class, %params) = @_;
629 $cli_handler_class = $class;
631 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
633 foreach my $key (keys %params) {
634 next if $key eq 'prepare';
635 next if $key eq 'no_init'; # not used anymore
636 next if $key eq 'no_rpcenv'; # not used anymore
637 die "unknown parameter '$key'";
640 my $preparefunc = $params{prepare
};
642 my $read_password_func = $class->can('read_password');
643 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
644 $class->can('string_param_file_mapping');
646 $exename = &$get_exe_name($class);
651 $cmddef = ${"${class}::cmddef"};
653 if (ref($cmddef) eq 'ARRAY') {
654 &$handle_simple_cmd(\
@ARGV, $read_password_func, $preparefunc, $param_mapping_func);
656 &$handle_cmd(\
@ARGV, $read_password_func, $preparefunc, $param_mapping_func);