1 package PVE
::CLIHandler
;
8 use PVE
::Exception
qw(raise raise_param_exc);
12 use PVE
::CLIFormatter
;
14 use base
qw(PVE::RESTHandler);
16 # $cmddef defines which (sub)commands are available in a specific CLI class.
17 # A real command is always an array consisting of its class, name, array of
18 # position fixed (required) parameters and hash of predefined parameters when
19 # mapping a CLI command t o an API call. Optionally an output method can be
20 # passed at the end, e.g., for formatting or transformation purpose, and
21 # a schema of additional properties/arguments which are added to
22 # the method schema and gets passed to the formatter.
24 # [class, name, fixed_params, API_pre-set params, output_sub ]
26 # In case of so called 'simple commands', the $cmddef can be also just an
31 # command => [ 'PVE::API2::Class', 'command', [ 'arg1', 'arg2' ], { node => $nodename } ],
33 # this => [ 'PVE::API2::OtherClass', 'method', [ 'arg1' ], undef, sub {
37 # that => [ 'PVE::API2::OtherClass', 'subroutine' [] ],
39 # dothat => { alias => 'do that' },
43 my $cli_handler_class;
45 my $standard_mappings = {
52 return $value if $value;
53 return PVE
::PTY
::get_confirmed_password
();
57 sub get_standard_mapping
{
58 my ($name, $base) = @_;
60 my $std = $standard_mappings->{$name};
61 die "no such standard mapping '$name'\n" if !$std;
63 my $res = $base || {};
65 foreach my $opt (keys %$std) {
66 next if defined($res->{$opt});
67 $res->{$opt} = $std->{$opt};
73 my $gen_param_mapping_func = sub {
74 my ($cli_handler_class) = @_;
76 my $param_mapping = $cli_handler_class->can('param_mapping');
78 if (!$param_mapping) {
79 my $read_password = $cli_handler_class->can('read_password');
80 my $string_param_mapping = $cli_handler_class->can('string_param_file_mapping');
82 return $string_param_mapping if !$read_password;
84 $param_mapping = sub {
87 my $password_map = get_standard_mapping
('pve-password', {
88 func
=> $read_password
90 my $map = $string_param_mapping ?
$string_param_mapping->($name) : [];
91 return [@$map, $password_map];
95 return $param_mapping;
98 my $assert_initialized = sub {
100 die "$caller[0]:$caller[2] - not initialized\n"
101 if !($cmddef && $exename && $cli_handler_class);
105 my ($reason, $cmd) = @_;
106 print_usage_short
(\
*STDERR
, $reason, $cmd);
110 my $expand_command_name = sub {
111 my ($def, $cmd) = @_;
113 return $cmd if exists $def->{$cmd}; # command is already complete
115 my $is_alias = sub { ref($_[0]) eq 'HASH' && exists($_[0]->{alias
}) };
116 my @expanded = grep { /^\Q$cmd\E/ && !$is_alias->($def->{$_}) } keys %$def;
118 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
123 my $get_commands = sub {
124 my $def = shift // die "no command definition passed!";
125 return [ grep { !(ref($def->{$_}) eq 'HASH' && defined($def->{$_}->{alias
})) } sort keys %$def ];
128 my $complete_command_names = sub { $get_commands->($cmddef) };
130 # traverses the command definition using the $argv array, resolving one level
132 # Returns the matching (sub) command and its definition, and argument array for
133 # this (sub) command and a hash where we marked which (sub) commands got
134 # expanded (e.g. st => status) while traversing
136 my ($argv, $is_alias) = @_;
138 my ($def, $cmd) = ($cmddef, $argv);
139 my $cmdstr = $exename;
141 if (ref($argv) eq 'ARRAY') {
142 my $expanded_last_arg;
143 my $last_arg_id = scalar(@$argv) - 1;
145 for my $i (0..$last_arg_id) {
146 $cmd = $expand_command_name->($def, $argv->[$i]);
148 # If the argument was expanded (or was already complete) and it
149 # is the final argument, tell our caller about it:
150 $expanded_last_arg = $cmd if $i == $last_arg_id;
152 # Otherwise continue with the unexpanded version of it.
157 last if !defined($def);
159 if (ref($def) eq 'ARRAY') {
160 # could expand to a real command, rest of $argv are its arguments
161 my $cmd_args = [ @$argv[$i+1..$last_arg_id] ];
162 return ($cmd, $def, $cmd_args, $expanded_last_arg, $cmdstr);
165 if (defined($def->{alias
})) {
166 die "alias loop detected for '$cmd'" if $is_alias; # avoids cycles
167 # replace aliased (sub)command with the expanded aliased command
168 splice @$argv, $i, 1, split(/ +/, $def->{alias
});
169 return resolve_cmd
($argv, 1);
172 # got either a special command (bashcomplete, verifyapi) or an unknown
173 # cmd, just return first entry as cmd and the rest of $argv as cmd_arg
174 my $cmd_args = [ @$argv[1..$last_arg_id] ];
175 return ($argv->[0], $def, $cmd_args, $expanded_last_arg, $cmdstr);
177 return ($cmd, $def, undef, undef, $cmdstr);
180 sub generate_usage_str
{
181 my ($format, $cmd, $indent, $separator, $sortfunc) = @_;
183 $assert_initialized->();
184 die 'format required' if !$format;
186 $sortfunc //= sub { sort keys %{$_[0]} };
190 my $param_cb = $gen_param_mapping_func->($cli_handler_class);
192 my ($subcmd, $def, undef, undef, $cmdstr) = resolve_cmd
($cmd);
196 my ($indent, $separator, $def, $prefix) = @_;
199 if (ref($def) eq 'HASH') {
200 my $oldclass = undef;
201 foreach my $cmd (&$sortfunc($def)) {
203 if (ref($def->{$cmd}) eq 'ARRAY') {
204 my ($class, $name, $arg_param, $fixed_param, undef, $formatter_properties) = @{$def->{$cmd}};
206 $str .= $separator if $oldclass && $oldclass ne $class;
208 $str .= $class->usage_str($name, "$prefix $cmd", $arg_param,
209 $fixed_param, $format, $param_cb, $formatter_properties);
212 } elsif (defined($def->{$cmd}->{alias
}) && ($format eq 'asciidoc')) {
214 $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n";
217 next if $def->{$cmd}->{alias
};
219 my $substr = $generate->($indent, '', $def->{$cmd}, "$prefix $cmd");
221 $substr .= $separator if $substr !~ /\Q$separator\E{2}/;
228 my ($class, $name, $arg_param, $fixed_param, undef, $formatter_properties) = @$def;
229 $abort->("unknown command '$cmd'") if !$class;
232 $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties);
237 return $generate->($indent, $separator, $def, $cmdstr);
240 __PACKAGE__-
>register_method ({
244 description
=> "Get help about specified command.",
246 additionalProperties
=> 0,
248 'extra-args' => PVE
::JSONSchema
::get_standard_option
('extra-args', {
249 description
=> 'Shows help for a specific command',
250 completion
=> $complete_command_names,
253 description
=> "Verbose output format.",
259 returns
=> { type
=> 'null' },
264 $assert_initialized->();
266 my $cmd = $param->{'extra-args'};
268 my $verbose = defined($cmd) && $cmd;
269 $verbose = $param->{verbose
} if defined($param->{verbose
});
273 print_usage_verbose
();
275 print_usage_short
(\
*STDOUT
);
282 $str = generate_usage_str
('full', $cmd, '');
284 $str = generate_usage_str
('short', $cmd, ' ' x
7);
291 print "USAGE: $str\n";
298 sub print_simple_asciidoc_synopsis
{
299 $assert_initialized->();
301 my $synopsis = "*${exename}* `help`\n\n";
302 $synopsis .= generate_usage_str
('asciidoc');
307 sub print_asciidoc_synopsis
{
308 $assert_initialized->();
312 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
314 $synopsis .= generate_usage_str
('asciidoc');
321 sub print_usage_verbose
{
322 $assert_initialized->();
324 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
326 my $str = generate_usage_str
('full');
331 sub print_usage_short
{
332 my ($fd, $msg, $cmd) = @_;
334 $assert_initialized->();
336 print $fd "ERROR: $msg\n" if $msg;
337 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
339 print {$fd} generate_usage_str
('short', $cmd, ' ' x
7, $cmd ?
'' : "\n", sub {
342 if (ref($h->{$a}) eq 'ARRAY' && ref($h->{$b}) eq 'ARRAY') {
343 # $a and $b are both real commands order them by their class
344 return $h->{$a}->[0] cmp $h->{$b}->[0] || $a cmp $b;
345 } elsif (ref($h->{$a}) eq 'ARRAY' xor ref($h->{$b}) eq 'ARRAY') {
346 # real command and subcommand mixed, put sub commands first
347 return ref($h->{$b}) eq 'ARRAY' ?
-1 : 1;
349 # both are either from the same class or subcommands
356 my $print_bash_completion = sub {
357 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
361 return if !(defined($cur) && defined($prev) && defined($bash_command));
362 return if !defined($ENV{COMP_LINE
});
363 return if !defined($ENV{COMP_POINT
});
365 my $cmdline = substr($ENV{COMP_LINE
}, 0, $ENV{COMP_POINT
});
366 print STDERR
"\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
368 my $args = PVE
::Tools
::split_args
($cmdline);
369 shift @$args; # no need for program name
370 my $print_result = sub {
372 print "$p\n" if $p =~ m/^\Q$cur\E/;
376 my ($cmd, $def) = ($simple_cmd, $cmddef);
378 ($cmd, $def, $args, my $expanded) = resolve_cmd
($args);
380 if (defined($expanded) && $prev ne $expanded) {
385 if (ref($def) eq 'HASH') {
386 &$print_result(@{$get_commands->($def)});
392 my $pos = scalar(@$args) - 1;
393 $pos += 1 if $cmdline =~ m/\s+$/;
394 print STDERR
"pos: $pos\n" if $debug;
399 my ($class, $name, $arg_param, $uri_param, undef, $formatter_properties) = @$def;
403 $arg_param = [ $arg_param ] if !ref($arg_param);
405 map { $skip_param->{$_} = 1; } @$arg_param;
406 map { $skip_param->{$_} = 1; } keys %$uri_param;
408 my $info = $class->map_method_by_name($name);
410 my $prop = { %{$info->{parameters
}->{properties
}} }; # copy
411 $prop = { %$prop, %$formatter_properties } if $formatter_properties;
413 my $print_parameter_completion = sub {
415 my $d = $prop->{$pname};
416 if ($d->{completion
}) {
417 my $vt = ref($d->{completion
});
419 my $res = $d->{completion
}->($cmd, $pname, $cur, $args);
420 &$print_result(@$res);
422 } elsif ($d->{type
} eq 'boolean') {
423 &$print_result('0', '1');
424 } elsif ($d->{enum
}) {
425 &$print_result(@{$d->{enum
}});
429 # positional arguments
430 if ($pos < scalar(@$arg_param)) {
431 my $pname = $arg_param->[$pos];
432 &$print_parameter_completion($pname);
436 my @option_list = ();
437 foreach my $key (keys %$prop) {
438 next if $skip_param->{$key};
439 push @option_list, "--$key";
443 &$print_result(@option_list);
447 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
449 &$print_parameter_completion($pname);
453 &$print_result(@option_list);
459 # simply verify all registered methods
460 PVE
::RESTHandler
::validate_method_schemas
();
463 my $get_exe_name = sub {
473 sub generate_bash_completions
{
476 # generate bash completion config
478 $exename = &$get_exe_name($class);
481 # $exename bash completion
483 # see http://tiswww.case.edu/php/chet/bash/FAQ
484 # and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
485 # this modifies global var, but I found no better way
486 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
488 complete -o default -C '$exename bashcomplete' $exename
492 sub generate_zsh_completions
{
495 # generate zsh completion config
497 $exename = &$get_exe_name($class);
500 #compdef _$exename $exename
502 function _$exename() {
503 local cwords line point cmd curr prev
508 curr=\${words[cwords]}
509 prev=\${words[cwords-1]}
510 compadd \$(COMP_CWORD="\$cwords" COMP_LINE="\$line" COMP_POINT="\$point" \\
511 $exename bashcomplete "\$cmd" "\$curr" "\$prev")
516 sub generate_asciidoc_synopsys
{
518 $class->generate_asciidoc_synopsis();
521 sub generate_asciidoc_synopsis
{
524 $cli_handler_class = $class;
526 $exename = &$get_exe_name($class);
529 my $def = ${"${class}::cmddef"};
532 if (ref($def) eq 'ARRAY') {
533 print_simple_asciidoc_synopsis
();
535 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['cmd'] ];
537 print_asciidoc_synopsis
();
541 # overwrite this if you want to run/setup things early
542 sub setup_environment
{
545 # do nothing by default
548 my $handle_cmd = sub {
549 my ($args, $preparefunc, $param_cb) = @_;
551 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['extra-args'] ];
553 my ($cmd, $def, $cmd_args, undef, $cmd_str) = resolve_cmd
($args);
555 $abort->("no command specified") if !$cmd;
557 # call verifyapi before setup_environment(), don't execute any real code in
559 if ($cmd eq 'verifyapi') {
560 PVE
::RESTHandler
::validate_method_schemas
();
564 $cli_handler_class->setup_environment();
566 if ($cmd eq 'bashcomplete') {
567 &$print_bash_completion(undef, @$cmd_args);
571 # checked special commands, if def is still a hash we got an incomplete sub command
572 $abort->("incomplete command '$cmd_str'", $args) if ref($def) eq 'HASH';
574 &$preparefunc() if $preparefunc;
576 my ($class, $name, $arg_param, $uri_param, $outsub, $formatter_properties) = @{$def || []};
577 $abort->("unknown command '$cmd_str'") if !$class;
579 my ($res, $formatter_params) = $class->cli_handler(
580 $cmd_str, $name, $cmd_args, $arg_param, $uri_param, $param_cb, $formatter_properties);
582 if (defined $outsub) {
583 my $result_schema = $class->map_method_by_name($name)->{returns
};
584 $outsub->($res, $result_schema, $formatter_params);
588 my $handle_simple_cmd = sub {
589 my ($args, $preparefunc, $param_cb) = @_;
591 my ($class, $name, $arg_param, $uri_param, $outsub, $formatter_properties) = @{$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, $formatter_params) = $class->cli_handler(
619 $name, $name, \
@ARGV, $arg_param, $uri_param, $param_cb, $formatter_properties);
621 if (defined $outsub) {
622 my $result_schema = $class->map_method_by_name($name)->{returns
};
623 $outsub->($res, $result_schema, $formatter_params);
627 sub run_cli_handler
{
628 my ($class, %params) = @_;
630 $cli_handler_class = $class;
632 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
634 foreach my $key (keys %params) {
635 next if $key eq 'prepare';
636 next if $key eq 'no_init'; # not used anymore
637 next if $key eq 'no_rpcenv'; # not used anymore
638 die "unknown parameter '$key'";
641 my $preparefunc = $params{prepare
};
643 my $param_cb = $gen_param_mapping_func->($cli_handler_class);
645 $exename = &$get_exe_name($class);
647 my $logid = $ENV{PVE_LOG_ID
} || $exename;
651 $cmddef = ${"${class}::cmddef"};
653 if (ref($cmddef) eq 'ARRAY') {
654 $handle_simple_cmd->(\
@ARGV, $preparefunc, $param_cb);
656 $handle_cmd->(\
@ARGV, $preparefunc, $param_cb);