1 package PVE
::CLIHandler
;
7 use Scalar
::Util
qw(weaken);
10 use PVE
::Exception
qw(raise raise_param_exc);
14 use PVE
::CLIFormatter
;
16 use base
qw(PVE::RESTHandler);
18 # $cmddef defines which (sub)commands are available in a specific CLI class.
19 # A real command is always an array consisting of its class, name, array of
20 # position fixed (required) parameters and hash of predefined parameters when
21 # mapping a CLI command t o an API call. Optionally an output method can be
22 # passed at the end, e.g., for formatting or transformation purpose, and
23 # a schema of additional properties/arguments which are added to
24 # the method schema and gets passed to the formatter.
26 # [class, name, fixed_params, API_pre-set params, output_sub ]
28 # In case of so called 'simple commands', the $cmddef can be also just an
33 # command => [ 'PVE::API2::Class', 'command', [ 'arg1', 'arg2' ], { node => $nodename } ],
35 # this => [ 'PVE::API2::OtherClass', 'method', [ 'arg1' ], undef, sub {
39 # that => [ 'PVE::API2::OtherClass', 'subroutine' [] ],
41 # dothat => { alias => 'do that' },
45 my $cli_handler_class;
47 my $standard_mappings = {
54 return $value if $value;
55 return PVE
::PTY
::get_confirmed_password
();
59 sub get_standard_mapping
{
60 my ($name, $base) = @_;
62 my $std = $standard_mappings->{$name};
63 die "no such standard mapping '$name'\n" if !$std;
65 my $res = $base || {};
67 foreach my $opt (keys %$std) {
68 next if defined($res->{$opt});
69 $res->{$opt} = $std->{$opt};
75 my $gen_param_mapping_func = sub {
76 my ($cli_handler_class) = @_;
78 my $param_mapping = $cli_handler_class->can('param_mapping');
80 if (!$param_mapping) {
81 my $read_password = $cli_handler_class->can('read_password');
82 my $string_param_mapping = $cli_handler_class->can('string_param_file_mapping');
84 return $string_param_mapping if !$read_password;
86 $param_mapping = sub {
89 my $password_map = get_standard_mapping
('pve-password', {
90 func
=> $read_password
92 my $map = $string_param_mapping ?
$string_param_mapping->($name) : [];
93 return [@$map, $password_map];
97 return $param_mapping;
100 my $assert_initialized = sub {
102 die "$caller[0]:$caller[2] - not initialized\n"
103 if !($cmddef && $exename && $cli_handler_class);
107 my ($reason, $cmd) = @_;
108 print_usage_short
(\
*STDERR
, $reason, $cmd);
112 my $expand_command_name = sub {
113 my ($def, $cmd, $enforce_exact) = @_;
115 return $cmd if exists $def->{$cmd}; # command is already complete
117 my $is_alias = sub { ref($_[0]) eq 'HASH' && exists($_[0]->{alias
}) };
118 my @expanded = grep { /^\Q$cmd\E/ && !$is_alias->($def->{$_}) } keys %$def;
120 return @expanded if !$enforce_exact;
122 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
127 my $get_commands = sub {
128 my $def = shift // die "no command definition passed!";
129 return [ grep { !(ref($def->{$_}) eq 'HASH' && defined($def->{$_}->{alias
})) } sort keys %$def ];
132 my $complete_command_names = sub { $get_commands->($cmddef) };
134 # traverses the command definition using the $argv array, resolving one level
136 # Returns the matching (sub) command and its definition, and argument array for
137 # this (sub) command and a hash where we marked which (sub) commands got
138 # expanded (e.g. st => status) while traversing
140 my ($argv, $is_alias) = @_;
142 my ($def, $cmd) = ($cmddef, $argv);
143 my $cmdstr = $exename;
145 if (ref($argv) eq 'ARRAY') {
146 my $expanded_last_arg;
147 my $last_arg_id = scalar(@$argv) - 1;
149 for my $i (0..$last_arg_id) {
150 $cmd = $expand_command_name->($def, $argv->[$i], 1);
152 # If the argument was expanded (or was already complete) and it
153 # is the final argument, tell our caller about it:
154 $expanded_last_arg = $cmd if $i == $last_arg_id;
156 # Otherwise continue with the unexpanded version of it.
160 if (!defined($def->{$cmd})) {
161 # $cmd still could be a valid prefix for bash_completion
162 # in that case keep $def as it is, else set it to undef
163 $def = undef if !$expand_command_name->($def, $cmd);
168 if (ref($def) eq 'ARRAY') {
169 # could expand to a real command, rest of $argv are its arguments
170 my $cmd_args = [ @$argv[$i+1..$last_arg_id] ];
171 return ($cmd, $def, $cmd_args, $expanded_last_arg, $cmdstr);
174 if (defined($def->{alias
})) {
175 die "alias loop detected for '$cmd'" if $is_alias; # avoids cycles
176 # replace aliased (sub)command with the expanded aliased command
177 splice @$argv, $i, 1, split(/ +/, $def->{alias
});
178 return resolve_cmd
($argv, 1);
181 # got either a special command (bashcomplete, verifyapi) or an unknown
182 # cmd, just return first entry as cmd and the rest of $argv as cmd_arg
183 my $cmd_args = [ @$argv[1..$last_arg_id] ];
184 return ($argv->[0], $def, $cmd_args, $expanded_last_arg, $cmdstr);
186 return ($cmd, $def, undef, undef, $cmdstr);
189 sub generate_usage_str
{
190 my ($format, $cmd, $indent, $separator, $sortfunc) = @_;
192 $assert_initialized->();
193 die 'format required' if !$format;
195 $sortfunc //= sub { sort keys %{$_[0]} };
199 my $param_cb = $gen_param_mapping_func->($cli_handler_class);
201 my ($subcmd, $def, undef, undef, $cmdstr) = resolve_cmd
($cmd);
204 $generate_weak = sub {
205 my ($indent, $separator, $def, $prefix) = @_;
208 if (ref($def) eq 'HASH') {
209 my $oldclass = undef;
210 foreach my $cmd (&$sortfunc($def)) {
212 if (ref($def->{$cmd}) eq 'ARRAY') {
213 my ($class, $name, $arg_param, $fixed_param, undef, $formatter_properties) = @{$def->{$cmd}};
215 $str .= $separator if $oldclass && $oldclass ne $class;
217 $str .= $class->usage_str($name, "$prefix $cmd", $arg_param,
218 $fixed_param, $format, $param_cb, $formatter_properties);
221 } elsif (defined($def->{$cmd}->{alias
}) && ($format eq 'asciidoc')) {
223 $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n";
226 next if $def->{$cmd}->{alias
};
228 my $substr = $generate_weak->($indent, '', $def->{$cmd}, "$prefix $cmd");
230 $substr .= $separator if $substr !~ /\Q$separator\E{2}/;
237 my ($class, $name, $arg_param, $fixed_param, undef, $formatter_properties) = @$def;
238 $abort->("unknown command '$cmd'") if !$class;
241 $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties);
245 my $generate = $generate_weak;
246 weaken
($generate_weak);
248 return $generate->($indent, $separator, $def, $cmdstr);
251 __PACKAGE__-
>register_method ({
255 description
=> "Get help about specified command.",
257 additionalProperties
=> 0,
259 'extra-args' => PVE
::JSONSchema
::get_standard_option
('extra-args', {
260 description
=> 'Shows help for a specific command',
261 completion
=> $complete_command_names,
264 description
=> "Verbose output format.",
270 returns
=> { type
=> 'null' },
275 $assert_initialized->();
277 my $cmd = $param->{'extra-args'};
279 my $verbose = defined($cmd) && $cmd;
280 $verbose = $param->{verbose
} if defined($param->{verbose
});
284 print_usage_verbose
();
286 print_usage_short
(\
*STDOUT
);
293 $str = generate_usage_str
('full', $cmd, '');
295 $str = generate_usage_str
('short', $cmd, ' ' x
7);
302 print "USAGE: $str\n";
309 sub print_simple_asciidoc_synopsis
{
310 $assert_initialized->();
312 my $synopsis = "*${exename}* `help`\n\n";
313 $synopsis .= generate_usage_str
('asciidoc');
318 sub print_asciidoc_synopsis
{
319 $assert_initialized->();
323 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
325 $synopsis .= generate_usage_str
('asciidoc');
332 sub print_usage_verbose
{
333 $assert_initialized->();
335 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
337 my $str = generate_usage_str
('full');
342 sub print_usage_short
{
343 my ($fd, $msg, $cmd) = @_;
345 $assert_initialized->();
347 print $fd "ERROR: $msg\n" if $msg;
348 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
350 print {$fd} generate_usage_str
('short', $cmd, ' ' x
7, $cmd ?
'' : "\n", sub {
353 if (ref($h->{$a}) eq 'ARRAY' && ref($h->{$b}) eq 'ARRAY') {
354 # $a and $b are both real commands order them by their class
355 return $h->{$a}->[0] cmp $h->{$b}->[0] || $a cmp $b;
356 } elsif (ref($h->{$a}) eq 'ARRAY' xor ref($h->{$b}) eq 'ARRAY') {
357 # real command and subcommand mixed, put sub commands first
358 return ref($h->{$b}) eq 'ARRAY' ?
-1 : 1;
360 # both are either from the same class or subcommands
367 my $print_bash_completion = sub {
368 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
372 return if !(defined($cur) && defined($prev) && defined($bash_command));
373 return if !defined($ENV{COMP_LINE
});
374 return if !defined($ENV{COMP_POINT
});
376 my $cmdline = substr($ENV{COMP_LINE
}, 0, $ENV{COMP_POINT
});
377 print STDERR
"\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
379 my $args = PVE
::Tools
::split_args
($cmdline);
380 shift @$args; # no need for program name
381 my $print_result = sub {
383 print "$p\n" if $p =~ m/^\Q$cur\E/;
387 my ($cmd, $def) = ($simple_cmd, $cmddef);
389 ($cmd, $def, $args, my $expanded) = resolve_cmd
($args);
391 if (defined($expanded) && $prev ne $expanded) {
396 if (ref($def) eq 'HASH') {
397 &$print_result(@{$get_commands->($def)});
403 my $pos = scalar(@$args) - 1;
404 $pos += 1 if $cmdline =~ m/\s+$/;
405 print STDERR
"pos: $pos\n" if $debug;
410 my ($class, $name, $arg_param, $uri_param, undef, $formatter_properties) = @$def;
414 $arg_param = [ $arg_param ] if !ref($arg_param);
416 map { $skip_param->{$_} = 1; } @$arg_param;
417 map { $skip_param->{$_} = 1; } keys %$uri_param;
419 my $info = $class->map_method_by_name($name);
421 my $prop = { %{$info->{parameters
}->{properties
}} }; # copy
422 $prop = { %$prop, %$formatter_properties } if $formatter_properties;
424 my $print_parameter_completion = sub {
426 my $d = $prop->{$pname};
427 if ($d->{completion
}) {
428 my $vt = ref($d->{completion
});
430 my $res = $d->{completion
}->($cmd, $pname, $cur, $args);
431 &$print_result(@$res);
433 } elsif ($d->{type
} eq 'boolean') {
434 &$print_result('0', '1');
435 } elsif ($d->{enum
}) {
436 &$print_result(@{$d->{enum
}});
440 # positional arguments
441 if ($pos < scalar(@$arg_param)) {
442 my $pname = $arg_param->[$pos];
443 &$print_parameter_completion($pname);
447 my @option_list = ();
448 foreach my $key (keys %$prop) {
449 next if $skip_param->{$key};
450 push @option_list, "--$key";
454 &$print_result(@option_list);
458 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
460 &$print_parameter_completion($pname);
464 &$print_result(@option_list);
470 # simply verify all registered methods
471 PVE
::RESTHandler
::validate_method_schemas
();
474 my $get_exe_name = sub {
484 sub generate_bash_completions
{
487 # generate bash completion config
489 $exename = &$get_exe_name($class);
492 # $exename bash completion
494 # see http://tiswww.case.edu/php/chet/bash/FAQ
495 # and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
496 # this modifies global var, but I found no better way
497 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
499 complete -o default -C '$exename bashcomplete' $exename
503 sub generate_zsh_completions
{
506 # generate zsh completion config
508 $exename = &$get_exe_name($class);
511 #compdef _$exename $exename
513 function _$exename() {
514 local cwords line point cmd curr prev
519 curr=\${words[cwords]}
520 prev=\${words[cwords-1]}
521 compadd \$(COMP_CWORD="\$cwords" COMP_LINE="\$line" COMP_POINT="\$point" \\
522 $exename bashcomplete "\$cmd" "\$curr" "\$prev")
527 sub generate_asciidoc_synopsys
{
529 $class->generate_asciidoc_synopsis();
532 sub generate_asciidoc_synopsis
{
535 $cli_handler_class = $class;
537 $exename = &$get_exe_name($class);
540 my $def = ${"${class}::cmddef"};
543 if (ref($def) eq 'ARRAY') {
544 print_simple_asciidoc_synopsis
();
546 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['cmd'] ];
548 print_asciidoc_synopsis
();
552 # overwrite this if you want to run/setup things early
553 sub setup_environment
{
556 # do nothing by default
559 my $handle_cmd = sub {
560 my ($args, $preparefunc, $param_cb) = @_;
562 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['extra-args'] ];
564 my ($cmd, $def, $cmd_args, undef, $cmd_str) = resolve_cmd
($args);
566 $abort->("no command specified") if !$cmd;
568 # call verifyapi before setup_environment(), don't execute any real code in
570 if ($cmd eq 'verifyapi') {
571 PVE
::RESTHandler
::validate_method_schemas
();
575 $cli_handler_class->setup_environment();
577 if ($cmd eq 'bashcomplete') {
578 &$print_bash_completion(undef, @$cmd_args);
582 # checked special commands, if def is still a hash we got an incomplete sub command
583 $abort->("incomplete command '$cmd_str'", $args) if ref($def) eq 'HASH';
585 &$preparefunc() if $preparefunc;
587 my ($class, $name, $arg_param, $uri_param, $outsub, $formatter_properties) = @{$def || []};
588 $abort->("unknown command '$cmd_str'") if !$class;
590 my ($res, $formatter_params) = $class->cli_handler(
591 $cmd_str, $name, $cmd_args, $arg_param, $uri_param, $param_cb, $formatter_properties);
593 if (defined $outsub) {
594 my $result_schema = $class->map_method_by_name($name)->{returns
};
595 $outsub->($res, $result_schema, $formatter_params);
599 my $handle_simple_cmd = sub {
600 my ($args, $preparefunc, $param_cb) = @_;
602 my ($class, $name, $arg_param, $uri_param, $outsub, $formatter_properties) = @{$cmddef};
603 die "no class specified" if !$class;
605 if (scalar(@$args) >= 1) {
606 if ($args->[0] eq 'help') {
607 my $str = "USAGE: $name help\n";
608 $str .= generate_usage_str
('long');
609 print STDERR
"$str\n\n";
611 } elsif ($args->[0] eq 'verifyapi') {
612 PVE
::RESTHandler
::validate_method_schemas
();
617 $cli_handler_class->setup_environment();
619 if (scalar(@$args) >= 1) {
620 if ($args->[0] eq 'bashcomplete') {
622 &$print_bash_completion($name, @$args);
627 &$preparefunc() if $preparefunc;
629 my ($res, $formatter_params) = $class->cli_handler(
630 $name, $name, \
@ARGV, $arg_param, $uri_param, $param_cb, $formatter_properties);
632 if (defined $outsub) {
633 my $result_schema = $class->map_method_by_name($name)->{returns
};
634 $outsub->($res, $result_schema, $formatter_params);
638 sub run_cli_handler
{
639 my ($class, %params) = @_;
641 $cli_handler_class = $class;
643 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
645 foreach my $key (keys %params) {
646 next if $key eq 'prepare';
647 next if $key eq 'no_init'; # not used anymore
648 next if $key eq 'no_rpcenv'; # not used anymore
649 die "unknown parameter '$key'";
652 my $preparefunc = $params{prepare
};
654 my $param_cb = $gen_param_mapping_func->($cli_handler_class);
656 $exename = &$get_exe_name($class);
658 my $logid = $ENV{PVE_LOG_ID
} || $exename;
662 $cmddef = ${"${class}::cmddef"};
664 if (ref($cmddef) eq 'ARRAY') {
665 $handle_simple_cmd->(\
@ARGV, $preparefunc, $param_cb);
667 $handle_cmd->(\
@ARGV, $preparefunc, $param_cb);