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 my $standard_mappings = { };
74 sub get_standard_mapping
{
75 my ($name, $base) = @_;
77 my $std = $standard_mappings->{$name};
78 die "no such standard mapping '$name'\n" if !$std;
80 my $res = $base || {};
82 foreach my $opt (keys %$std) {
83 next if defined($res->{$opt});
84 $res->{$opt} = $std->{$opt};
90 # traverses the command definition using the $argv array, resolving one level
92 # Returns the matching (sub) command and its definition, and argument array for
93 # this (sub) command and a hash where we marked which (sub) commands got
94 # expanded (e.g. st => status) while traversing
96 my ($argv, $is_alias) = @_;
98 my ($def, $cmd) = ($cmddef, $argv);
99 my $cmdstr = $exename;
101 if (ref($argv) eq 'ARRAY') {
102 my $expanded_last_arg;
103 my $last_arg_id = scalar(@$argv) - 1;
105 for my $i (0..$last_arg_id) {
106 $cmd = $expand_command_name->($def, $argv->[$i]);
108 # If the argument was expanded (or was already complete) and it
109 # is the final argument, tell our caller about it:
110 $expanded_last_arg = $cmd if $i == $last_arg_id;
112 # Otherwise continue with the unexpanded version of it.
117 last if !defined($def);
119 if (ref($def) eq 'ARRAY') {
120 # could expand to a real command, rest of $argv are its arguments
121 my $cmd_args = [ @$argv[$i+1..$last_arg_id] ];
122 return ($cmd, $def, $cmd_args, $expanded_last_arg, $cmdstr);
125 if (defined($def->{alias
})) {
126 die "alias loop detected for '$cmd'" if $is_alias; # avoids cycles
127 # replace aliased (sub)command with the expanded aliased command
128 splice @$argv, $i, 1, split(/ +/, $def->{alias
});
129 return resolve_cmd
($argv, 1);
132 # got either a special command (bashcomplete, verifyapi) or an unknown
133 # cmd, just return first entry as cmd and the rest of $argv as cmd_arg
134 my $cmd_args = [ @$argv[1..$last_arg_id] ];
135 return ($argv->[0], $def, $cmd_args, $expanded_last_arg, $cmdstr);
137 return ($cmd, $def, undef, undef, $cmdstr);
140 sub generate_usage_str
{
141 my ($format, $cmd, $indent, $separator, $sortfunc) = @_;
143 $assert_initialized->();
144 die 'format required' if !$format;
146 $sortfunc //= sub { sort keys %{$_[0]} };
150 my $read_password_func = $cli_handler_class->can('read_password');
151 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
152 $cli_handler_class->can('string_param_file_mapping');
154 my ($subcmd, $def, undef, undef, $cmdstr) = resolve_cmd
($cmd);
155 $abort->("unknown command '$cmdstr'") if !defined($def) && ref($cmd) eq 'ARRAY';
159 my ($indent, $separator, $def, $prefix) = @_;
162 if (ref($def) eq 'HASH') {
163 my $oldclass = undef;
164 foreach my $cmd (&$sortfunc($def)) {
166 if (ref($def->{$cmd}) eq 'ARRAY') {
167 my ($class, $name, $arg_param, $fixed_param) = @{$def->{$cmd}};
169 $str .= $separator if $oldclass && $oldclass ne $class;
171 $str .= $class->usage_str($name, "$prefix $cmd", $arg_param,
172 $fixed_param, $format,
173 $read_password_func, $param_mapping_func);
176 } elsif (defined($def->{$cmd}->{alias
}) && ($format eq 'asciidoc')) {
178 $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n";
181 next if $def->{$cmd}->{alias
};
183 my $substr = $generate->($indent, $separator, $def->{$cmd}, "$prefix $cmd");
185 $substr .= $separator if $substr !~ /\Q$separator\E{2}/;
192 my ($class, $name, $arg_param, $fixed_param) = @$def;
193 $abort->("unknown command '$cmd'") if !$class;
196 $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format,
197 $read_password_func, $param_mapping_func);
202 return $generate->($indent, $separator, $def, $cmdstr);
205 __PACKAGE__-
>register_method ({
209 description
=> "Get help about specified command.",
211 additionalProperties
=> 0,
213 'extra-args' => PVE
::JSONSchema
::get_standard_option
('extra-args', {
214 description
=> 'Shows help for a specific command',
215 completion
=> $complete_command_names,
218 description
=> "Verbose output format.",
224 returns
=> { type
=> 'null' },
229 $assert_initialized->();
231 my $cmd = $param->{'extra-args'};
233 my $verbose = defined($cmd) && $cmd;
234 $verbose = $param->{verbose
} if defined($param->{verbose
});
238 print_usage_verbose
();
240 print_usage_short
(\
*STDOUT
);
247 $str = generate_usage_str
('full', $cmd, '');
249 $str = generate_usage_str
('short', $cmd, ' ' x
7);
256 print "USAGE: $str\n";
263 sub print_simple_asciidoc_synopsis
{
264 $assert_initialized->();
266 my $synopsis = "*${exename}* `help`\n\n";
267 $synopsis .= generate_usage_str
('asciidoc');
272 sub print_asciidoc_synopsis
{
273 $assert_initialized->();
277 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
279 $synopsis .= generate_usage_str
('asciidoc');
286 sub print_usage_verbose
{
287 $assert_initialized->();
289 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
291 my $str = generate_usage_str
('full');
296 sub print_usage_short
{
297 my ($fd, $msg, $cmd) = @_;
299 $assert_initialized->();
301 print $fd "ERROR: $msg\n" if $msg;
302 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
304 print {$fd} generate_usage_str
('short', $cmd, ' ' x
7, "\n", sub {
307 if (ref($h->{$a}) eq 'ARRAY' && ref($h->{$b}) eq 'ARRAY') {
308 # $a and $b are both real commands order them by their class
309 return $h->{$a}->[0] cmp $h->{$b}->[0] || $a cmp $b;
310 } elsif (ref($h->{$a}) eq 'ARRAY' xor ref($h->{$b}) eq 'ARRAY') {
311 # real command and subcommand mixed, put sub commands first
312 return ref($h->{$b}) eq 'ARRAY' ?
-1 : 1;
314 # both are either from the same class or subcommands
321 my $print_bash_completion = sub {
322 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
326 return if !(defined($cur) && defined($prev) && defined($bash_command));
327 return if !defined($ENV{COMP_LINE
});
328 return if !defined($ENV{COMP_POINT
});
330 my $cmdline = substr($ENV{COMP_LINE
}, 0, $ENV{COMP_POINT
});
331 print STDERR
"\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
333 my $args = PVE
::Tools
::split_args
($cmdline);
334 shift @$args; # no need for program name
335 my $print_result = sub {
337 print "$p\n" if $p =~ m/^\Q$cur\E/;
341 my ($cmd, $def) = ($simple_cmd, $cmddef);
343 ($cmd, $def, $args, my $expanded) = resolve_cmd
($args);
345 if (defined($expanded) && $prev ne $expanded) {
350 if (ref($def) eq 'HASH') {
351 &$print_result(@{$get_commands->($def)});
357 my $pos = scalar(@$args) - 1;
358 $pos += 1 if $cmdline =~ m/\s+$/;
359 print STDERR
"pos: $pos\n" if $debug;
364 my ($class, $name, $arg_param, $uri_param) = @$def;
368 $arg_param = [ $arg_param ] if !ref($arg_param);
370 map { $skip_param->{$_} = 1; } @$arg_param;
371 map { $skip_param->{$_} = 1; } keys %$uri_param;
373 my $info = $class->map_method_by_name($name);
375 my $prop = $info->{parameters
}->{properties
};
377 my $print_parameter_completion = sub {
379 my $d = $prop->{$pname};
380 if ($d->{completion
}) {
381 my $vt = ref($d->{completion
});
383 my $res = $d->{completion
}->($cmd, $pname, $cur, $args);
384 &$print_result(@$res);
386 } elsif ($d->{type
} eq 'boolean') {
387 &$print_result('0', '1');
388 } elsif ($d->{enum
}) {
389 &$print_result(@{$d->{enum
}});
393 # positional arguments
394 if ($pos < scalar(@$arg_param)) {
395 my $pname = $arg_param->[$pos];
396 &$print_parameter_completion($pname);
400 my @option_list = ();
401 foreach my $key (keys %$prop) {
402 next if $skip_param->{$key};
403 push @option_list, "--$key";
407 &$print_result(@option_list);
411 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
413 &$print_parameter_completion($pname);
417 &$print_result(@option_list);
420 # prints a formatted table with a title row.
421 # $formatopts is an array of hashes, with the following keys:
422 # 'key' - key of $data element to print
423 # 'title' - column title, defaults to 'key' - won't get cutoff
424 # 'cutoff' - maximal (print) length of this column values, if set
425 # the last column will never be cutoff
426 # 'default' - optional default value for the column
427 # formatopts element order defines column order (left to right)
428 sub print_text_table
{
429 my ($formatopts, $data) = @_;
431 my ($formatstring, @keys, @titles, %cutoffs, %defaults);
432 my $last_col = $formatopts->[$#{$formatopts}];
434 foreach my $col ( @$formatopts ) {
435 my ($key, $title, $cutoff, $default) = @$col{qw(key title cutoff default)};
439 push @titles, $title;
440 $defaults{$key} = $default;
442 # calculate maximal print width and cutoff
443 my $titlelen = length($title);
445 my $longest = $titlelen;
446 foreach my $entry (@$data) {
447 my $len = length($entry->{$key}) // 0;
448 $longest = $len if $len > $longest;
451 $cutoff = (defined($cutoff) && $cutoff < $longest) ?
$cutoff : $longest;
452 $cutoffs{$key} = $cutoff;
454 my $printalign = $cutoff > $titlelen ?
'-' : '';
455 if ($col == $last_col) {
456 $formatstring .= "%${printalign}${titlelen}s\n";
458 $formatstring .= "%${printalign}${cutoff}s ";
462 printf $formatstring, @titles;
464 foreach my $entry (sort { $a->{$keys[0]} cmp $b->{$keys[0]} } @$data) {
465 printf $formatstring, map { substr(($entry->{$_} // $defaults{$_}), 0 , $cutoffs{$_}) } @keys;
472 #TODO: handle objects/hashes as well
473 foreach my $item (sort keys %$entry) {
474 if (ref($entry->{$item}) eq 'ARRAY') {
475 printf "%s: [ %s ]\n", $item, join(", ", @{$entry->{$item}});
477 printf "%s: %s\n", $item, $entry->{$item};
482 # prints the result of an API GET call returning an array
483 # and to have the results key of the API call defined.
485 my ($props_to_print, $data, $returninfo) = @_;
487 die "can only print array result" if $returninfo->{type
} ne 'array';
489 my $returnprops = $returninfo->{items
}->{properties
};
492 foreach my $prop ( @$props_to_print ) {
493 my $propinfo = $returnprops->{$prop};
496 title
=> $propinfo->{title
},
497 default => $propinfo->{default},
498 cutoff
=> $propinfo->{print_width
} // $propinfo->{maxLength
},
500 push @$formatopts, $colopts;
503 print_text_table
($formatopts, $data);
509 # simply verify all registered methods
510 PVE
::RESTHandler
::validate_method_schemas
();
513 my $get_exe_name = sub {
523 sub generate_bash_completions
{
526 # generate bash completion config
528 $exename = &$get_exe_name($class);
531 # $exename bash completion
533 # see http://tiswww.case.edu/php/chet/bash/FAQ
534 # and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
535 # this modifies global var, but I found no better way
536 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
538 complete -o default -C '$exename bashcomplete' $exename
542 sub generate_asciidoc_synopsys
{
544 $class->generate_asciidoc_synopsis();
547 sub generate_asciidoc_synopsis
{
550 $cli_handler_class = $class;
552 $exename = &$get_exe_name($class);
555 my $def = ${"${class}::cmddef"};
558 if (ref($def) eq 'ARRAY') {
559 print_simple_asciidoc_synopsis
();
561 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['cmd'] ];
563 print_asciidoc_synopsis
();
567 # overwrite this if you want to run/setup things early
568 sub setup_environment
{
571 # do nothing by default
574 my $handle_cmd = sub {
575 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
577 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['extra-args'] ];
579 my ($cmd, $def, $cmd_args, undef, $cmd_str) = resolve_cmd
($args);
581 $abort->("no command specified") if !$cmd;
583 # call verifyapi before setup_environment(), don't execute any real code in
585 if ($cmd eq 'verifyapi') {
586 PVE
::RESTHandler
::validate_method_schemas
();
590 $cli_handler_class->setup_environment();
592 if ($cmd eq 'bashcomplete') {
593 &$print_bash_completion(undef, @$cmd_args);
597 # checked special commands, if def is still a hash we got an incomplete sub command
598 $abort->("incomplete command '$cmd_str'", $args) if ref($def) eq 'HASH';
600 &$preparefunc() if $preparefunc;
602 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def || []};
603 $abort->("unknown command '$cmd_str'") if !$class;
605 my $res = $class->cli_handler($cmd_str, $name, $cmd_args, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
607 if (defined $outsub) {
608 my $returninfo = $class->map_method_by_name($name)->{returns
};
609 $outsub->($res, $returninfo);
613 my $handle_simple_cmd = sub {
614 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
616 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
617 die "no class specified" if !$class;
619 if (scalar(@$args) >= 1) {
620 if ($args->[0] eq 'help') {
621 my $str = "USAGE: $name help\n";
622 $str .= generate_usage_str
('long');
623 print STDERR
"$str\n\n";
625 } elsif ($args->[0] eq 'verifyapi') {
626 PVE
::RESTHandler
::validate_method_schemas
();
631 $cli_handler_class->setup_environment();
633 if (scalar(@$args) >= 1) {
634 if ($args->[0] eq 'bashcomplete') {
636 &$print_bash_completion($name, @$args);
641 &$preparefunc() if $preparefunc;
643 my $res = $class->cli_handler($name, $name, \
@ARGV, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
645 if (defined $outsub) {
646 my $returninfo = $class->map_method_by_name($name)->{returns
};
647 $outsub->($res, $returninfo);
651 sub run_cli_handler
{
652 my ($class, %params) = @_;
654 $cli_handler_class = $class;
656 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
658 foreach my $key (keys %params) {
659 next if $key eq 'prepare';
660 next if $key eq 'no_init'; # not used anymore
661 next if $key eq 'no_rpcenv'; # not used anymore
662 die "unknown parameter '$key'";
665 my $preparefunc = $params{prepare
};
667 my $read_password_func = $class->can('read_password');
668 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
669 $class->can('string_param_file_mapping');
671 $exename = &$get_exe_name($class);
676 $cmddef = ${"${class}::cmddef"};
678 if (ref($cmddef) eq 'ARRAY') {
679 &$handle_simple_cmd(\
@ARGV, $read_password_func, $preparefunc, $param_mapping_func);
681 &$handle_cmd(\
@ARGV, $read_password_func, $preparefunc, $param_mapping_func);