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 {
56 my @expanded = grep { /^\Q$cmd\E/ } keys %$def;
57 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
62 my $get_commands = sub {
63 my $def = shift // die "no command definition passed!";
64 return [ grep { !(ref($def->{$_}) eq 'HASH' && defined($def->{$_}->{alias
})) } sort keys %$def ];
67 my $complete_command_names = sub { $get_commands->($cmddef) };
69 # traverses the command definition using the $argv array, resolving one level
71 # Returns the matching (sub) command and its definition, and argument array for
72 # this (sub) command and a hash where we marked which (sub) commands got
73 # expanded (e.g. st => status) while traversing
75 my ($argv, $is_alias) = @_;
77 my ($def, $cmd) = ($cmddef, $argv);
78 my $cmdstr = $exename;
80 if (ref($argv) eq 'ARRAY') {
82 my $last_arg_id = scalar(@$argv) - 1;
84 for my $i (0..$last_arg_id) {
85 $cmd = $expand_command_name->($def, $argv->[$i]);
87 $expanded->{$argv->[$i]} = $cmd if $cmd ne $argv->[$i];
88 last if !defined($def->{$cmd});
91 if (ref($def) eq 'ARRAY') {
92 # could expand to a real command, rest of $argv are its arguments
93 my $cmd_args = [ @$argv[$i+1..$last_arg_id] ];
94 return ($cmd, $def, $cmd_args, $expanded, $cmdstr);
97 if (defined($def->{alias
})) {
98 die "alias loop detected for '$cmd'" if $is_alias; # avoids cycles
99 # replace aliased (sub)command with the expanded aliased command
100 splice @$argv, $i, 1, split(/ +/, $def->{alias
});
101 return resolve_cmd
($argv, 1);
104 # got either a special command (bashcomplete, verifyapi) or an unknown
105 # cmd, just return first entry as cmd and the rest of $argv as cmd_arg
106 my $cmd_args = [ @$argv[1..$last_arg_id] ];
107 return ($argv->[0], $def, $cmd_args, $expanded, $cmdstr);
109 return ($cmd, $def, undef, undef, $cmdstr);
112 sub generate_usage_str
{
113 my ($format, $cmd, $indent, $separator, $sortfunc) = @_;
115 $assert_initialized->();
116 die 'format required' if !$format;
118 $sortfunc //= sub { sort keys %{$_[0]} };
122 my $read_password_func = $cli_handler_class->can('read_password');
123 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
124 $cli_handler_class->can('string_param_file_mapping');
126 my ($subcmd, $def, undef, undef, $cmdstr) = resolve_cmd
($cmd);
130 my ($indent, $separator, $def, $prefix) = @_;
133 if (ref($def) eq 'HASH') {
134 my $oldclass = undef;
135 foreach my $cmd (&$sortfunc($def)) {
137 if (ref($def->{$cmd}) eq 'ARRAY') {
138 my ($class, $name, $arg_param, $fixed_param) = @{$def->{$cmd}};
140 $str .= $separator if $oldclass && $oldclass ne $class;
142 $str .= $class->usage_str($name, "$prefix $cmd", $arg_param,
143 $fixed_param, $format,
144 $read_password_func, $param_mapping_func);
147 } elsif (defined($def->{$cmd}->{alias
}) && ($format eq 'asciidoc')) {
149 $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n";
152 next if $def->{$cmd}->{alias
};
154 my $substr = $generate->($indent, $separator, $def->{$cmd}, "$prefix $cmd");
156 $substr .= $separator if $substr !~ /\Q$separator\E{2}/;
163 my ($class, $name, $arg_param, $fixed_param) = @$def;
164 $abort->("unknown command '$cmd'") if !$class;
167 $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format,
168 $read_password_func, $param_mapping_func);
173 return $generate->($indent, $separator, $def, $cmdstr);
176 __PACKAGE__-
>register_method ({
180 description
=> "Get help about specified command.",
182 additionalProperties
=> 0,
184 'extra-args' => PVE
::JSONSchema
::get_standard_option
('extra-args', {
185 description
=> 'Shows help for a specific command',
186 completion
=> $complete_command_names,
189 description
=> "Verbose output format.",
195 returns
=> { type
=> 'null' },
200 $assert_initialized->();
202 my $cmd = $param->{'extra-args'};
204 my $verbose = defined($cmd) && $cmd;
205 $verbose = $param->{verbose
} if defined($param->{verbose
});
209 print_usage_verbose
();
211 print_usage_short
(\
*STDOUT
);
218 $str = generate_usage_str
('full', $cmd, '');
220 $str = generate_usage_str
('short', $cmd, ' ' x
7);
227 print "USAGE: $str\n";
234 sub print_simple_asciidoc_synopsis
{
235 $assert_initialized->();
237 my $synopsis = "*${exename}* `help`\n\n";
238 $synopsis .= generate_usage_str
('asciidoc');
243 sub print_asciidoc_synopsis
{
244 $assert_initialized->();
248 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
250 $synopsis .= generate_usage_str
('asciidoc');
257 sub print_usage_verbose
{
258 $assert_initialized->();
260 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
262 my $str = generate_usage_str
('full');
267 sub print_usage_short
{
268 my ($fd, $msg, $cmd) = @_;
270 $assert_initialized->();
272 print $fd "ERROR: $msg\n" if $msg;
273 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
275 print {$fd} generate_usage_str
('short', $cmd, ' ' x
7, "\n", sub {
278 if (ref($h->{$a}) eq 'ARRAY' && ref($h->{$b}) eq 'ARRAY') {
279 # $a and $b are both real commands order them by their class
280 return $h->{$a}->[0] cmp $h->{$b}->[0] || $a cmp $b;
281 } elsif (ref($h->{$a}) eq 'ARRAY' xor ref($h->{$b}) eq 'ARRAY') {
282 # real command and subcommand mixed, put sub commands first
283 return ref($h->{$b}) eq 'ARRAY' ?
-1 : 1;
285 # both are either from the same class or subcommands
292 my $print_bash_completion = sub {
293 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
297 return if !(defined($cur) && defined($prev) && defined($bash_command));
298 return if !defined($ENV{COMP_LINE
});
299 return if !defined($ENV{COMP_POINT
});
301 my $cmdline = substr($ENV{COMP_LINE
}, 0, $ENV{COMP_POINT
});
302 print STDERR
"\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
304 my $args = PVE
::Tools
::split_args
($cmdline);
305 shift @$args; # no need for program name
306 my $print_result = sub {
308 print "$p\n" if $p =~ m/^$cur/;
312 my ($cmd, $def) = ($simple_cmd, $cmddef);
314 ($cmd, $def, $args, my $expaned) = resolve_cmd
($args);
316 if (ref($def) eq 'HASH') {
317 &$print_result(@{$get_commands->($def)});
320 if (my $expanded_cmd = $expaned->{$cur}) {
321 print "$expanded_cmd\n";
327 my $pos = scalar(@$args) - 1;
328 $pos += 1 if $cmdline =~ m/\s+$/;
329 print STDERR
"pos: $pos\n" if $debug;
334 my ($class, $name, $arg_param, $uri_param) = @$def;
338 $arg_param = [ $arg_param ] if !ref($arg_param);
340 map { $skip_param->{$_} = 1; } @$arg_param;
341 map { $skip_param->{$_} = 1; } keys %$uri_param;
343 my $info = $class->map_method_by_name($name);
345 my $prop = $info->{parameters
}->{properties
};
347 my $print_parameter_completion = sub {
349 my $d = $prop->{$pname};
350 if ($d->{completion
}) {
351 my $vt = ref($d->{completion
});
353 my $res = $d->{completion
}->($cmd, $pname, $cur, $args);
354 &$print_result(@$res);
356 } elsif ($d->{type
} eq 'boolean') {
357 &$print_result('0', '1');
358 } elsif ($d->{enum
}) {
359 &$print_result(@{$d->{enum
}});
363 # positional arguments
364 $pos++ if $simple_cmd;
365 if ($pos < scalar(@$arg_param)) {
366 my $pname = $arg_param->[$pos];
367 &$print_parameter_completion($pname);
371 my @option_list = ();
372 foreach my $key (keys %$prop) {
373 next if $skip_param->{$key};
374 push @option_list, "--$key";
378 &$print_result(@option_list);
382 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
384 &$print_parameter_completion($pname);
388 &$print_result(@option_list);
394 # simply verify all registered methods
395 PVE
::RESTHandler
::validate_method_schemas
();
398 my $get_exe_name = sub {
408 sub generate_bash_completions
{
411 # generate bash completion config
413 $exename = &$get_exe_name($class);
416 # $exename bash completion
418 # see http://tiswww.case.edu/php/chet/bash/FAQ
419 # and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
420 # this modifies global var, but I found no better way
421 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
423 complete -o default -C '$exename bashcomplete' $exename
427 sub generate_asciidoc_synopsys
{
429 $class->generate_asciidoc_synopsis();
432 sub generate_asciidoc_synopsis
{
435 $cli_handler_class = $class;
437 $exename = &$get_exe_name($class);
440 my $def = ${"${class}::cmddef"};
443 if (ref($def) eq 'ARRAY') {
444 print_simple_asciidoc_synopsis
();
446 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['cmd'] ];
448 print_asciidoc_synopsis
();
452 # overwrite this if you want to run/setup things early
453 sub setup_environment
{
456 # do nothing by default
459 my $handle_cmd = sub {
460 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
462 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['extra-args'] ];
464 my ($cmd, $def, $cmd_args, undef, $cmd_str) = resolve_cmd
($args);
466 $abort->("no command specified") if !$cmd;
468 # call verifyapi before setup_environment(), don't execute any real code in
470 if ($cmd eq 'verifyapi') {
471 PVE
::RESTHandler
::validate_method_schemas
();
475 $cli_handler_class->setup_environment();
477 if ($cmd eq 'bashcomplete') {
478 &$print_bash_completion(undef, @$cmd_args);
482 # checked special commands, if def is still a hash we got an incomplete sub command
483 $abort->("incomplete command '$cmd_str'") if ref($def) eq 'HASH';
485 &$preparefunc() if $preparefunc;
487 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def || []};
488 $abort->("unknown command '$cmd_str'") if !$class;
490 my $res = $class->cli_handler($cmd_str, $name, $cmd_args, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
492 &$outsub($res) if $outsub;
495 my $handle_simple_cmd = sub {
496 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
498 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
499 die "no class specified" if !$class;
501 if (scalar(@$args) >= 1) {
502 if ($args->[0] eq 'help') {
503 my $str = "USAGE: $name help\n";
504 $str .= generate_usage_str
('long');
505 print STDERR
"$str\n\n";
507 } elsif ($args->[0] eq 'verifyapi') {
508 PVE
::RESTHandler
::validate_method_schemas
();
513 $cli_handler_class->setup_environment();
515 if (scalar(@$args) >= 1) {
516 if ($args->[0] eq 'bashcomplete') {
518 &$print_bash_completion($name, @$args);
523 &$preparefunc() if $preparefunc;
525 my $res = $class->cli_handler($name, $name, \
@ARGV, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
527 &$outsub($res) if $outsub;
530 sub run_cli_handler
{
531 my ($class, %params) = @_;
533 $cli_handler_class = $class;
535 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
537 foreach my $key (keys %params) {
538 next if $key eq 'prepare';
539 next if $key eq 'no_init'; # not used anymore
540 next if $key eq 'no_rpcenv'; # not used anymore
541 die "unknown parameter '$key'";
544 my $preparefunc = $params{prepare
};
546 my $read_password_func = $class->can('read_password');
547 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
548 $class->can('string_param_file_mapping');
550 $exename = &$get_exe_name($class);
555 $cmddef = ${"${class}::cmddef"};
557 if (ref($cmddef) eq 'ARRAY') {
558 &$handle_simple_cmd(\
@ARGV, $read_password_func, $preparefunc, $param_mapping_func);
560 &$handle_cmd(\
@ARGV, $read_password_func, $preparefunc, $param_mapping_func);