1 package PVE
::APIClient
::CLIHandler
;
6 use PVE
::APIClient
::SafeSyslog
;
7 use PVE
::APIClient
::Exception
qw(raise raise_param_exc);
8 use PVE
::APIClient
::RESTHandler
;
9 use PVE
::APIClient
::PTY
;
12 use base
qw(PVE::APIClient::RESTHandler);
14 # $cmddef defines which (sub)commands are available in a specific CLI class.
15 # A real command is always an array consisting of its class, name, array of
16 # position fixed (required) parameters and hash of predefined parameters when
17 # mapping a CLI command t o an API call. Optionally an output method can be
18 # passed at the end, e.g., for formatting or transformation purpose.
20 # [class, name, fixed_params, API_pre-set params, output_sub ]
22 # In case of so called 'simple commands', the $cmddef can be also just an
27 # command => [ 'PVE::APIClient::API2::Class', 'command', [ 'arg1', 'arg2' ], { node => $nodename } ],
29 # this => [ 'PVE::APIClient::API2::OtherClass', 'method', [ 'arg1' ], undef, sub {
33 # that => [ 'PVE::APIClient::API2::OtherClass', 'subroutine' [] ],
35 # dothat => { alias => 'do that' },
39 my $cli_handler_class;
41 my $standard_mappings = {
48 return $value if $value;
49 return PVE
::APIClient
::PTY
::get_confirmed_password
();
53 sub get_standard_mapping
{
54 my ($name, $base) = @_;
56 my $std = $standard_mappings->{$name};
57 die "no such standard mapping '$name'\n" if !$std;
59 my $res = $base || {};
61 foreach my $opt (keys %$std) {
62 next if defined($res->{$opt});
63 $res->{$opt} = $std->{$opt};
69 my $assert_initialized = sub {
71 die "$caller[0]:$caller[2] - not initialized\n"
72 if !($cmddef && $exename && $cli_handler_class);
76 my ($reason, $cmd) = @_;
77 print_usage_short
(\
*STDERR
, $reason, $cmd);
81 my $expand_command_name = sub {
84 return $cmd if exists $def->{$cmd}; # command is already complete
86 my $is_alias = sub { ref($_[0]) eq 'HASH' && exists($_[0]->{alias
}) };
87 my @expanded = grep { /^\Q$cmd\E/ && !$is_alias->($def->{$_}) } keys %$def;
89 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
94 my $get_commands = sub {
95 my $def = shift // die "no command definition passed!";
96 return [ grep { !(ref($def->{$_}) eq 'HASH' && defined($def->{$_}->{alias
})) } sort keys %$def ];
99 my $complete_command_names = sub { $get_commands->($cmddef) };
101 # traverses the command definition using the $argv array, resolving one level
103 # Returns the matching (sub) command and its definition, and argument array for
104 # this (sub) command and a hash where we marked which (sub) commands got
105 # expanded (e.g. st => status) while traversing
107 my ($argv, $is_alias) = @_;
109 my ($def, $cmd) = ($cmddef, $argv);
110 my $cmdstr = $exename;
112 if (ref($argv) eq 'ARRAY') {
113 my $expanded_last_arg;
114 my $last_arg_id = scalar(@$argv) - 1;
116 for my $i (0..$last_arg_id) {
117 $cmd = $expand_command_name->($def, $argv->[$i]);
119 # If the argument was expanded (or was already complete) and it
120 # is the final argument, tell our caller about it:
121 $expanded_last_arg = $cmd if $i == $last_arg_id;
123 # Otherwise continue with the unexpanded version of it.
128 last if !defined($def);
130 if (ref($def) eq 'ARRAY') {
131 # could expand to a real command, rest of $argv are its arguments
132 my $cmd_args = [ @$argv[$i+1..$last_arg_id] ];
133 return ($cmd, $def, $cmd_args, $expanded_last_arg, $cmdstr);
136 if (defined($def->{alias
})) {
137 die "alias loop detected for '$cmd'" if $is_alias; # avoids cycles
138 # replace aliased (sub)command with the expanded aliased command
139 splice @$argv, $i, 1, split(/ +/, $def->{alias
});
140 return resolve_cmd
($argv, 1);
143 # got either a special command (bashcomplete, verifyapi) or an unknown
144 # cmd, just return first entry as cmd and the rest of $argv as cmd_arg
145 my $cmd_args = [ @$argv[1..$last_arg_id] ];
146 return ($argv->[0], $def, $cmd_args, $expanded_last_arg, $cmdstr);
148 return ($cmd, $def, undef, undef, $cmdstr);
151 sub generate_usage_str
{
152 my ($format, $cmd, $indent, $separator, $sortfunc) = @_;
154 $assert_initialized->();
155 die 'format required' if !$format;
157 $sortfunc //= sub { sort keys %{$_[0]} };
161 my $read_password_func = $cli_handler_class->can('read_password');
162 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
163 $cli_handler_class->can('string_param_file_mapping');
165 my ($subcmd, $def, undef, undef, $cmdstr) = resolve_cmd
($cmd);
166 $abort->("unknown command '$cmdstr'") if !defined($def) && ref($cmd) eq 'ARRAY';
170 my ($indent, $separator, $def, $prefix) = @_;
173 if (ref($def) eq 'HASH') {
174 my $oldclass = undef;
175 foreach my $cmd (&$sortfunc($def)) {
177 if (ref($def->{$cmd}) eq 'ARRAY') {
178 my ($class, $name, $arg_param, $fixed_param) = @{$def->{$cmd}};
180 $str .= $separator if $oldclass && $oldclass ne $class;
182 $str .= $class->usage_str($name, "$prefix $cmd", $arg_param,
183 $fixed_param, $format,
184 $read_password_func, $param_mapping_func);
187 } elsif (defined($def->{$cmd}->{alias
}) && ($format eq 'asciidoc')) {
189 $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n";
192 next if $def->{$cmd}->{alias
};
194 my $substr = $generate->($indent, $separator, $def->{$cmd}, "$prefix $cmd");
196 $substr .= $separator if $substr !~ /\Q$separator\E{2}/;
203 my ($class, $name, $arg_param, $fixed_param) = @$def;
204 $abort->("unknown command '$cmd'") if !$class;
207 $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format,
208 $read_password_func, $param_mapping_func);
213 return $generate->($indent, $separator, $def, $cmdstr);
216 __PACKAGE__-
>register_method ({
220 description
=> "Get help about specified command.",
222 additionalProperties
=> 0,
224 'extra-args' => PVE
::APIClient
::JSONSchema
::get_standard_option
('extra-args', {
225 description
=> 'Shows help for a specific command',
226 completion
=> $complete_command_names,
229 description
=> "Verbose output format.",
235 returns
=> { type
=> 'null' },
240 $assert_initialized->();
242 my $cmd = $param->{'extra-args'};
244 my $verbose = defined($cmd) && $cmd;
245 $verbose = $param->{verbose
} if defined($param->{verbose
});
249 print_usage_verbose
();
251 print_usage_short
(\
*STDOUT
);
258 $str = generate_usage_str
('full', $cmd, '');
260 $str = generate_usage_str
('short', $cmd, ' ' x
7);
267 print "USAGE: $str\n";
274 sub print_simple_asciidoc_synopsis
{
275 $assert_initialized->();
277 my $synopsis = "*${exename}* `help`\n\n";
278 $synopsis .= generate_usage_str
('asciidoc');
283 sub print_asciidoc_synopsis
{
284 $assert_initialized->();
288 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
290 $synopsis .= generate_usage_str
('asciidoc');
297 sub print_usage_verbose
{
298 $assert_initialized->();
300 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
302 my $str = generate_usage_str
('full');
307 sub print_usage_short
{
308 my ($fd, $msg, $cmd) = @_;
310 $assert_initialized->();
312 print $fd "ERROR: $msg\n" if $msg;
313 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
315 print {$fd} generate_usage_str
('short', $cmd, ' ' x
7, "\n", sub {
318 if (ref($h->{$a}) eq 'ARRAY' && ref($h->{$b}) eq 'ARRAY') {
319 # $a and $b are both real commands order them by their class
320 return $h->{$a}->[0] cmp $h->{$b}->[0] || $a cmp $b;
321 } elsif (ref($h->{$a}) eq 'ARRAY' xor ref($h->{$b}) eq 'ARRAY') {
322 # real command and subcommand mixed, put sub commands first
323 return ref($h->{$b}) eq 'ARRAY' ?
-1 : 1;
325 # both are either from the same class or subcommands
332 my $print_bash_completion = sub {
333 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
337 return if !(defined($cur) && defined($prev) && defined($bash_command));
338 return if !defined($ENV{COMP_LINE
});
339 return if !defined($ENV{COMP_POINT
});
341 my $cmdline = substr($ENV{COMP_LINE
}, 0, $ENV{COMP_POINT
});
342 print STDERR
"\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
344 my $args = PVE
::APIClient
::Tools
::split_args
($cmdline);
345 shift @$args; # no need for program name
346 my $print_result = sub {
348 print "$p\n" if $p =~ m/^\Q$cur\E/;
352 my ($cmd, $def) = ($simple_cmd, $cmddef);
354 ($cmd, $def, $args, my $expanded) = resolve_cmd
($args);
356 if (defined($expanded) && $prev ne $expanded) {
361 if (ref($def) eq 'HASH') {
362 &$print_result(@{$get_commands->($def)});
368 my $pos = scalar(@$args) - 1;
369 $pos += 1 if $cmdline =~ m/\s+$/;
370 print STDERR
"pos: $pos\n" if $debug;
375 my ($class, $name, $arg_param, $uri_param) = @$def;
379 $arg_param = [ $arg_param ] if !ref($arg_param);
381 map { $skip_param->{$_} = 1; } @$arg_param;
382 map { $skip_param->{$_} = 1; } keys %$uri_param;
384 my $info = $class->map_method_by_name($name);
386 my $prop = $info->{parameters
}->{properties
};
388 my $print_parameter_completion = sub {
390 my $d = $prop->{$pname};
391 if ($d->{completion
}) {
392 my $vt = ref($d->{completion
});
394 my $res = $d->{completion
}->($cmd, $pname, $cur, $args);
395 &$print_result(@$res);
397 } elsif ($d->{type
} eq 'boolean') {
398 &$print_result('0', '1');
399 } elsif ($d->{enum
}) {
400 &$print_result(@{$d->{enum
}});
404 # positional arguments
405 if ($pos < scalar(@$arg_param)) {
406 my $pname = $arg_param->[$pos];
407 &$print_parameter_completion($pname);
411 my @option_list = ();
412 foreach my $key (keys %$prop) {
413 next if $skip_param->{$key};
414 push @option_list, "--$key";
418 &$print_result(@option_list);
422 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
424 &$print_parameter_completion($pname);
428 &$print_result(@option_list);
431 # prints a formatted table with a title row.
432 # $formatopts is an array of hashes, with the following keys:
433 # 'key' - key of $data element to print
434 # 'title' - column title, defaults to 'key' - won't get cutoff
435 # 'cutoff' - maximal (print) length of this column values, if set
436 # the last column will never be cutoff
437 # 'default' - optional default value for the column
438 # formatopts element order defines column order (left to right)
439 sub print_text_table
{
440 my ($formatopts, $data) = @_;
442 my ($formatstring, @keys, @titles, %cutoffs, %defaults);
443 my $last_col = $formatopts->[$#{$formatopts}];
445 foreach my $col ( @$formatopts ) {
446 my ($key, $title, $cutoff, $default) = @$col{qw(key title cutoff default)};
450 push @titles, $title;
451 $defaults{$key} = $default;
453 # calculate maximal print width and cutoff
454 my $titlelen = length($title);
456 my $longest = $titlelen;
457 foreach my $entry (@$data) {
458 my $len = length($entry->{$key}) // 0;
459 $longest = $len if $len > $longest;
462 $cutoff = (defined($cutoff) && $cutoff < $longest) ?
$cutoff : $longest;
463 $cutoffs{$key} = $cutoff;
465 my $printalign = $cutoff > $titlelen ?
'-' : '';
466 if ($col == $last_col) {
467 $formatstring .= "%${printalign}${titlelen}s\n";
469 $formatstring .= "%${printalign}${cutoff}s ";
473 printf $formatstring, @titles;
475 foreach my $entry (sort { $a->{$keys[0]} cmp $b->{$keys[0]} } @$data) {
476 printf $formatstring, map { substr(($entry->{$_} // $defaults{$_}), 0 , $cutoffs{$_}) } @keys;
483 #TODO: handle objects/hashes as well
484 foreach my $item (sort keys %$entry) {
485 if (ref($entry->{$item}) eq 'ARRAY') {
486 printf "%s: [ %s ]\n", $item, join(", ", @{$entry->{$item}});
488 printf "%s: %s\n", $item, $entry->{$item};
493 # prints the result of an API GET call returning an array
494 # and to have the results key of the API call defined.
496 my ($props_to_print, $data, $returninfo) = @_;
498 die "can only print array result" if $returninfo->{type
} ne 'array';
500 my $returnprops = $returninfo->{items
}->{properties
};
503 foreach my $prop ( @$props_to_print ) {
504 my $propinfo = $returnprops->{$prop};
507 title
=> $propinfo->{title
},
508 default => $propinfo->{default},
509 cutoff
=> $propinfo->{print_width
} // $propinfo->{maxLength
},
511 push @$formatopts, $colopts;
514 print_text_table
($formatopts, $data);
520 # simply verify all registered methods
521 PVE
::APIClient
::RESTHandler
::validate_method_schemas
();
524 my $get_exe_name = sub {
534 sub generate_bash_completions
{
537 # generate bash completion config
539 $exename = &$get_exe_name($class);
542 # $exename bash completion
544 # see http://tiswww.case.edu/php/chet/bash/FAQ
545 # and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
546 # this modifies global var, but I found no better way
547 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
549 complete -o default -C '$exename bashcomplete' $exename
553 sub generate_asciidoc_synopsys
{
555 $class->generate_asciidoc_synopsis();
558 sub generate_asciidoc_synopsis
{
561 $cli_handler_class = $class;
563 $exename = &$get_exe_name($class);
566 my $def = ${"${class}::cmddef"};
569 if (ref($def) eq 'ARRAY') {
570 print_simple_asciidoc_synopsis
();
572 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['cmd'] ];
574 print_asciidoc_synopsis
();
578 # overwrite this if you want to run/setup things early
579 sub setup_environment
{
582 # do nothing by default
585 my $handle_cmd = sub {
586 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
588 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['extra-args'] ];
590 my ($cmd, $def, $cmd_args, undef, $cmd_str) = resolve_cmd
($args);
592 $abort->("no command specified") if !$cmd;
594 # call verifyapi before setup_environment(), don't execute any real code in
596 if ($cmd eq 'verifyapi') {
597 PVE
::APIClient
::RESTHandler
::validate_method_schemas
();
601 $cli_handler_class->setup_environment();
603 if ($cmd eq 'bashcomplete') {
604 &$print_bash_completion(undef, @$cmd_args);
608 # checked special commands, if def is still a hash we got an incomplete sub command
609 $abort->("incomplete command '$cmd_str'", $args) if ref($def) eq 'HASH';
611 &$preparefunc() if $preparefunc;
613 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def || []};
614 $abort->("unknown command '$cmd_str'") if !$class;
616 my $res = $class->cli_handler($cmd_str, $name, $cmd_args, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
618 if (defined $outsub) {
619 my $returninfo = $class->map_method_by_name($name)->{returns
};
620 $outsub->($res, $returninfo);
624 my $handle_simple_cmd = sub {
625 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
627 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
628 die "no class specified" if !$class;
630 if (scalar(@$args) >= 1) {
631 if ($args->[0] eq 'help') {
632 my $str = "USAGE: $name help\n";
633 $str .= generate_usage_str
('long');
634 print STDERR
"$str\n\n";
636 } elsif ($args->[0] eq 'verifyapi') {
637 PVE
::APIClient
::RESTHandler
::validate_method_schemas
();
642 $cli_handler_class->setup_environment();
644 if (scalar(@$args) >= 1) {
645 if ($args->[0] eq 'bashcomplete') {
647 &$print_bash_completion($name, @$args);
652 &$preparefunc() if $preparefunc;
654 my $res = $class->cli_handler($name, $name, \
@ARGV, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
656 if (defined $outsub) {
657 my $returninfo = $class->map_method_by_name($name)->{returns
};
658 $outsub->($res, $returninfo);
662 sub run_cli_handler
{
663 my ($class, %params) = @_;
665 $cli_handler_class = $class;
667 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
669 foreach my $key (keys %params) {
670 next if $key eq 'prepare';
671 next if $key eq 'no_init'; # not used anymore
672 next if $key eq 'no_rpcenv'; # not used anymore
673 die "unknown parameter '$key'";
676 my $preparefunc = $params{prepare
};
678 my $read_password_func = $class->can('read_password');
679 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
680 $class->can('string_param_file_mapping');
682 $exename = &$get_exe_name($class);
687 $cmddef = ${"${class}::cmddef"};
689 if (ref($cmddef) eq 'ARRAY') {
690 &$handle_simple_cmd(\
@ARGV, $read_password_func, $preparefunc, $param_mapping_func);
692 &$handle_cmd(\
@ARGV, $read_password_func, $preparefunc, $param_mapping_func);