1 package PVE
::CLIHandler
;
7 use PVE
::Exception
qw(raise raise_param_exc);
10 use base
qw(PVE::RESTHandler);
12 # $cmddef defines which (sub)commands are available in a specific CLI class.
13 # A real command is always an array consisting of its class, name, array of
14 # position fixed (required) parameters and hash of predefined parameters when
15 # mapping a CLI command t o an API call. Optionally an output method can be
16 # passed at the end, e.g., for formatting or transformation purpose.
18 # [class, name, fixed_params, API_pre-set params, output_sub ]
20 # In case of so called 'simple commands', the $cmddef can be also just an
25 # command => [ 'PVE::API2::Class', 'command', [ 'arg1', 'arg2' ], { node => $nodename } ],
27 # this => [ 'PVE::API2::OtherClass', 'method', [ 'arg1' ], undef, sub {
31 # that => [ 'PVE::API2::OtherClass', 'subroutine' [] ],
33 # dothat => { alias => 'do that' },
37 my $cli_handler_class;
39 my $assert_initialized = sub {
41 die "$caller[0]:$caller[2] - not initialized\n"
42 if !($cmddef && $exename && $cli_handler_class);
46 my ($reason, $cmd) = @_;
47 print_usage_short
(\
*STDERR
, $reason, $cmd);
51 my $expand_command_name = sub {
55 my @expanded = grep { /^\Q$cmd\E/ } keys %$def;
56 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
61 my $get_commands = sub {
62 my $def = shift // die "no command definition passed!";
63 return [ grep { !(ref($def->{$_}) eq 'HASH' && defined($def->{$_}->{alias
})) } sort keys %$def ];
66 my $complete_command_names = sub { $get_commands->($cmddef) };
68 # traverses the command definition using the $argv array, resolving one level
70 # Returns the matching (sub) command and its definition, and argument array for
71 # this (sub) command and a hash where we marked which (sub) commands got
72 # expanded (e.g. st => status) while traversing
74 my ($argv, $is_alias) = @_;
76 my ($def, $cmd) = ($cmddef, $argv);
77 my $cmdstr = $exename;
79 if (ref($argv) eq 'ARRAY') {
81 my $last_arg_id = scalar(@$argv) - 1;
83 for my $i (0..$last_arg_id) {
84 $cmd = $expand_command_name->($def, $argv->[$i]);
86 $expanded->{$argv->[$i]} = $cmd if $cmd ne $argv->[$i];
87 last if !defined($def->{$cmd});
90 if (ref($def) eq 'ARRAY') {
91 # could expand to a real command, rest of $argv are its arguments
92 my $cmd_args = [ @$argv[$i+1..$last_arg_id] ];
93 return ($cmd, $def, $cmd_args, $expanded, $cmdstr);
96 if (defined($def->{alias
})) {
97 die "alias loop detected for '$cmd'" if $is_alias; # avoids cycles
98 # replace aliased (sub)command with the expanded aliased command
99 splice @$argv, $i, 1, split(/ +/, $def->{alias
});
100 return resolve_cmd
($argv, 1);
103 # got either a special command (bashcomplete, verifyapi) or an unknown
104 # cmd, just return first entry as cmd and the rest of $argv as cmd_arg
105 my $cmd_args = [ @$argv[1..$last_arg_id] ];
106 return ($argv->[0], $def, $cmd_args, $expanded, $cmdstr);
108 return ($cmd, $def, undef, undef, $cmdstr);
111 sub generate_usage_str
{
112 my ($format, $cmd, $indent, $separator, $sortfunc) = @_;
114 $assert_initialized->();
115 die 'format required' if !$format;
117 $sortfunc //= sub { sort keys %{$_[0]} };
121 my $read_password_func = $cli_handler_class->can('read_password');
122 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
123 $cli_handler_class->can('string_param_file_mapping');
125 my ($subcmd, $def, undef, undef, $cmdstr) = resolve_cmd
($cmd);
129 my ($indent, $separator, $def, $prefix) = @_;
132 if (ref($def) eq 'HASH') {
133 my $oldclass = undef;
134 foreach my $cmd (&$sortfunc($def)) {
136 if (ref($def->{$cmd}) eq 'ARRAY') {
137 my ($class, $name, $arg_param, $fixed_param) = @{$def->{$cmd}};
139 $str .= $separator if $oldclass && $oldclass ne $class;
141 $str .= $class->usage_str($name, "$prefix $cmd", $arg_param,
142 $fixed_param, $format,
143 $read_password_func, $param_mapping_func);
146 } elsif (defined($def->{$cmd}->{alias
}) && ($format eq 'asciidoc')) {
148 $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n";
151 next if $def->{$cmd}->{alias
};
153 my $substr = $generate->($indent, $separator, $def->{$cmd}, "$prefix $cmd");
155 $substr .= $separator if $substr !~ /\Q$separator\E{2}/;
162 my ($class, $name, $arg_param, $fixed_param) = @$def;
163 $abort->("unknown command '$cmd'") if !$class;
166 $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format,
167 $read_password_func, $param_mapping_func);
172 return $generate->($indent, $separator, $def, $cmdstr);
175 __PACKAGE__-
>register_method ({
179 description
=> "Get help about specified command.",
181 additionalProperties
=> 0,
183 'extra-args' => PVE
::JSONSchema
::get_standard_option
('extra-args', {
184 description
=> 'Shows help for a specific command',
185 completion
=> $complete_command_names,
188 description
=> "Verbose output format.",
194 returns
=> { type
=> 'null' },
199 $assert_initialized->();
201 my $cmd = $param->{'extra-args'};
203 my $verbose = defined($cmd) && $cmd;
204 $verbose = $param->{verbose
} if defined($param->{verbose
});
208 print_usage_verbose
();
210 print_usage_short
(\
*STDOUT
);
217 $str = generate_usage_str
('full', $cmd, '');
219 $str = generate_usage_str
('short', $cmd, ' ' x
7);
226 print "USAGE: $str\n";
233 sub print_simple_asciidoc_synopsis
{
234 $assert_initialized->();
236 my $synopsis = "*${exename}* `help`\n\n";
237 $synopsis .= generate_usage_str
('asciidoc');
242 sub print_asciidoc_synopsis
{
243 $assert_initialized->();
247 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
249 $synopsis .= generate_usage_str
('asciidoc');
256 sub print_usage_verbose
{
257 $assert_initialized->();
259 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
261 my $str = generate_usage_str
('full');
266 sub print_usage_short
{
267 my ($fd, $msg, $cmd) = @_;
269 $assert_initialized->();
271 print $fd "ERROR: $msg\n" if $msg;
272 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
274 print {$fd} generate_usage_str
('short', $cmd, ' ' x
7, "\n", sub {
277 if (ref($h->{$a}) eq 'ARRAY' && ref($h->{$b}) eq 'ARRAY') {
278 # $a and $b are both real commands order them by their class
279 return $h->{$a}->[0] cmp $h->{$b}->[0] || $a cmp $b;
280 } elsif (ref($h->{$a}) eq 'ARRAY' xor ref($h->{$b}) eq 'ARRAY') {
281 # real command and subcommand mixed, put sub commands first
282 return ref($h->{$b}) eq 'ARRAY' ?
-1 : 1;
284 # both are either from the same class or subcommands
291 my $print_bash_completion = sub {
292 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
296 return if !(defined($cur) && defined($prev) && defined($bash_command));
297 return if !defined($ENV{COMP_LINE
});
298 return if !defined($ENV{COMP_POINT
});
300 my $cmdline = substr($ENV{COMP_LINE
}, 0, $ENV{COMP_POINT
});
301 print STDERR
"\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
303 my $args = PVE
::Tools
::split_args
($cmdline);
304 shift @$args; # no need for program name
305 my $print_result = sub {
307 print "$p\n" if $p =~ m/^$cur/;
311 my ($cmd, $def) = ($simple_cmd, $cmddef);
313 ($cmd, $def, $args, my $expaned) = resolve_cmd
($args);
315 if (ref($def) eq 'HASH') {
316 &$print_result(@{$get_commands->($def)});
319 if (my $expanded_cmd = $expaned->{$cur}) {
320 print "$expanded_cmd\n";
326 my $pos = scalar(@$args) - 1;
327 $pos += 1 if $cmdline =~ m/\s+$/;
328 print STDERR
"pos: $pos\n" if $debug;
333 my ($class, $name, $arg_param, $uri_param) = @$def;
337 $arg_param = [ $arg_param ] if !ref($arg_param);
339 map { $skip_param->{$_} = 1; } @$arg_param;
340 map { $skip_param->{$_} = 1; } keys %$uri_param;
342 my $info = $class->map_method_by_name($name);
344 my $prop = $info->{parameters
}->{properties
};
346 my $print_parameter_completion = sub {
348 my $d = $prop->{$pname};
349 if ($d->{completion
}) {
350 my $vt = ref($d->{completion
});
352 my $res = $d->{completion
}->($cmd, $pname, $cur, $args);
353 &$print_result(@$res);
355 } elsif ($d->{type
} eq 'boolean') {
356 &$print_result('0', '1');
357 } elsif ($d->{enum
}) {
358 &$print_result(@{$d->{enum
}});
362 # positional arguments
363 $pos++ if $simple_cmd;
364 if ($pos < scalar(@$arg_param)) {
365 my $pname = $arg_param->[$pos];
366 &$print_parameter_completion($pname);
370 my @option_list = ();
371 foreach my $key (keys %$prop) {
372 next if $skip_param->{$key};
373 push @option_list, "--$key";
377 &$print_result(@option_list);
381 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
383 &$print_parameter_completion($pname);
387 &$print_result(@option_list);
393 # simply verify all registered methods
394 PVE
::RESTHandler
::validate_method_schemas
();
397 my $get_exe_name = sub {
407 sub generate_bash_completions
{
410 # generate bash completion config
412 $exename = &$get_exe_name($class);
415 # $exename bash completion
417 # see http://tiswww.case.edu/php/chet/bash/FAQ
418 # and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
419 # this modifies global var, but I found no better way
420 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
422 complete -o default -C '$exename bashcomplete' $exename
426 sub generate_asciidoc_synopsys
{
428 $class->generate_asciidoc_synopsis();
431 sub generate_asciidoc_synopsis
{
434 $cli_handler_class = $class;
436 $exename = &$get_exe_name($class);
439 my $def = ${"${class}::cmddef"};
442 if (ref($def) eq 'ARRAY') {
443 print_simple_asciidoc_synopsis
();
445 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['cmd'] ];
447 print_asciidoc_synopsis
();
451 # overwrite this if you want to run/setup things early
452 sub setup_environment
{
455 # do nothing by default
458 my $handle_cmd = sub {
459 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
461 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['extra-args'] ];
463 my ($cmd, $def, $cmd_args, undef, $cmd_str) = resolve_cmd
($args);
465 $abort->("no command specified") if !$cmd;
467 # call verifyapi before setup_environment(), don't execute any real code in
469 if ($cmd eq 'verifyapi') {
470 PVE
::RESTHandler
::validate_method_schemas
();
474 $cli_handler_class->setup_environment();
476 if ($cmd eq 'bashcomplete') {
477 &$print_bash_completion(undef, @$cmd_args);
481 # checked special commands, if def is still a hash we got an incomplete sub command
482 $abort->("incomplete command '$cmd_str'") if ref($def) eq 'HASH';
484 &$preparefunc() if $preparefunc;
486 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def || []};
487 $abort->("unknown command '$cmd_str'") if !$class;
489 my $res = $class->cli_handler($cmd_str, $name, $cmd_args, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
491 &$outsub($res) if $outsub;
494 my $handle_simple_cmd = sub {
495 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
497 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
498 die "no class specified" if !$class;
500 if (scalar(@$args) >= 1) {
501 if ($args->[0] eq 'help') {
502 my $str = "USAGE: $name help\n";
503 $str .= generate_usage_str
('long');
504 print STDERR
"$str\n\n";
506 } elsif ($args->[0] eq 'verifyapi') {
507 PVE
::RESTHandler
::validate_method_schemas
();
512 $cli_handler_class->setup_environment();
514 if (scalar(@$args) >= 1) {
515 if ($args->[0] eq 'bashcomplete') {
517 &$print_bash_completion($name, @$args);
522 &$preparefunc() if $preparefunc;
524 my $res = $class->cli_handler($name, $name, \
@ARGV, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
526 &$outsub($res) if $outsub;
529 sub run_cli_handler
{
530 my ($class, %params) = @_;
532 $cli_handler_class = $class;
534 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
536 foreach my $key (keys %params) {
537 next if $key eq 'prepare';
538 next if $key eq 'no_init'; # not used anymore
539 next if $key eq 'no_rpcenv'; # not used anymore
540 die "unknown parameter '$key'";
543 my $preparefunc = $params{prepare
};
545 my $read_password_func = $class->can('read_password');
546 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
547 $class->can('string_param_file_mapping');
549 $exename = &$get_exe_name($class);
554 $cmddef = ${"${class}::cmddef"};
556 if (ref($cmddef) eq 'ARRAY') {
557 &$handle_simple_cmd(\
@ARGV, $read_password_func, $preparefunc, $param_mapping_func);
559 &$handle_cmd(\
@ARGV, $read_password_func, $preparefunc, $param_mapping_func);