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 {
55 return $cmd if exists $def->{$cmd}; # command is already complete
57 my @expanded = grep { /^\Q$cmd\E/ } keys %$def;
58 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
63 my $get_commands = sub {
64 my $def = shift // die "no command definition passed!";
65 return [ grep { !(ref($def->{$_}) eq 'HASH' && defined($def->{$_}->{alias
})) } sort keys %$def ];
68 my $complete_command_names = sub { $get_commands->($cmddef) };
70 # traverses the command definition using the $argv array, resolving one level
72 # Returns the matching (sub) command and its definition, and argument array for
73 # this (sub) command and a hash where we marked which (sub) commands got
74 # expanded (e.g. st => status) while traversing
76 my ($argv, $is_alias) = @_;
78 my ($def, $cmd) = ($cmddef, $argv);
79 my $cmdstr = $exename;
81 if (ref($argv) eq 'ARRAY') {
82 my $expanded_last_arg;
83 my $last_arg_id = scalar(@$argv) - 1;
85 for my $i (0..$last_arg_id) {
86 $cmd = $expand_command_name->($def, $argv->[$i]);
88 # If the argument was expanded (or was already complete) and it
89 # is the final argument, tell our caller about it:
90 $expanded_last_arg = $cmd if $i == $last_arg_id;
92 # Otherwise continue with the unexpanded version of it.
96 last if !defined($def->{$cmd});
99 if (ref($def) eq 'ARRAY') {
100 # could expand to a real command, rest of $argv are its arguments
101 my $cmd_args = [ @$argv[$i+1..$last_arg_id] ];
102 return ($cmd, $def, $cmd_args, $expanded_last_arg, $cmdstr);
105 if (defined($def->{alias
})) {
106 die "alias loop detected for '$cmd'" if $is_alias; # avoids cycles
107 # replace aliased (sub)command with the expanded aliased command
108 splice @$argv, $i, 1, split(/ +/, $def->{alias
});
109 return resolve_cmd
($argv, 1);
112 # got either a special command (bashcomplete, verifyapi) or an unknown
113 # cmd, just return first entry as cmd and the rest of $argv as cmd_arg
114 my $cmd_args = [ @$argv[1..$last_arg_id] ];
115 return ($argv->[0], $def, $cmd_args, $expanded_last_arg, $cmdstr);
117 return ($cmd, $def, undef, undef, $cmdstr);
120 sub generate_usage_str
{
121 my ($format, $cmd, $indent, $separator, $sortfunc) = @_;
123 $assert_initialized->();
124 die 'format required' if !$format;
126 $sortfunc //= sub { sort keys %{$_[0]} };
130 my $read_password_func = $cli_handler_class->can('read_password');
131 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
132 $cli_handler_class->can('string_param_file_mapping');
134 my ($subcmd, $def, undef, undef, $cmdstr) = resolve_cmd
($cmd);
138 my ($indent, $separator, $def, $prefix) = @_;
141 if (ref($def) eq 'HASH') {
142 my $oldclass = undef;
143 foreach my $cmd (&$sortfunc($def)) {
145 if (ref($def->{$cmd}) eq 'ARRAY') {
146 my ($class, $name, $arg_param, $fixed_param) = @{$def->{$cmd}};
148 $str .= $separator if $oldclass && $oldclass ne $class;
150 $str .= $class->usage_str($name, "$prefix $cmd", $arg_param,
151 $fixed_param, $format,
152 $read_password_func, $param_mapping_func);
155 } elsif (defined($def->{$cmd}->{alias
}) && ($format eq 'asciidoc')) {
157 $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n";
160 next if $def->{$cmd}->{alias
};
162 my $substr = $generate->($indent, $separator, $def->{$cmd}, "$prefix $cmd");
164 $substr .= $separator if $substr !~ /\Q$separator\E{2}/;
171 my ($class, $name, $arg_param, $fixed_param) = @$def;
172 $abort->("unknown command '$cmd'") if !$class;
175 $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format,
176 $read_password_func, $param_mapping_func);
181 return $generate->($indent, $separator, $def, $cmdstr);
184 __PACKAGE__-
>register_method ({
188 description
=> "Get help about specified command.",
190 additionalProperties
=> 0,
192 'extra-args' => PVE
::JSONSchema
::get_standard_option
('extra-args', {
193 description
=> 'Shows help for a specific command',
194 completion
=> $complete_command_names,
197 description
=> "Verbose output format.",
203 returns
=> { type
=> 'null' },
208 $assert_initialized->();
210 my $cmd = $param->{'extra-args'};
212 my $verbose = defined($cmd) && $cmd;
213 $verbose = $param->{verbose
} if defined($param->{verbose
});
217 print_usage_verbose
();
219 print_usage_short
(\
*STDOUT
);
226 $str = generate_usage_str
('full', $cmd, '');
228 $str = generate_usage_str
('short', $cmd, ' ' x
7);
235 print "USAGE: $str\n";
242 sub print_simple_asciidoc_synopsis
{
243 $assert_initialized->();
245 my $synopsis = "*${exename}* `help`\n\n";
246 $synopsis .= generate_usage_str
('asciidoc');
251 sub print_asciidoc_synopsis
{
252 $assert_initialized->();
256 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
258 $synopsis .= generate_usage_str
('asciidoc');
265 sub print_usage_verbose
{
266 $assert_initialized->();
268 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
270 my $str = generate_usage_str
('full');
275 sub print_usage_short
{
276 my ($fd, $msg, $cmd) = @_;
278 $assert_initialized->();
280 print $fd "ERROR: $msg\n" if $msg;
281 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
283 print {$fd} generate_usage_str
('short', $cmd, ' ' x
7, "\n", sub {
286 if (ref($h->{$a}) eq 'ARRAY' && ref($h->{$b}) eq 'ARRAY') {
287 # $a and $b are both real commands order them by their class
288 return $h->{$a}->[0] cmp $h->{$b}->[0] || $a cmp $b;
289 } elsif (ref($h->{$a}) eq 'ARRAY' xor ref($h->{$b}) eq 'ARRAY') {
290 # real command and subcommand mixed, put sub commands first
291 return ref($h->{$b}) eq 'ARRAY' ?
-1 : 1;
293 # both are either from the same class or subcommands
300 my $print_bash_completion = sub {
301 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
305 return if !(defined($cur) && defined($prev) && defined($bash_command));
306 return if !defined($ENV{COMP_LINE
});
307 return if !defined($ENV{COMP_POINT
});
309 my $cmdline = substr($ENV{COMP_LINE
}, 0, $ENV{COMP_POINT
});
310 print STDERR
"\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
312 my $args = PVE
::Tools
::split_args
($cmdline);
313 shift @$args; # no need for program name
314 my $print_result = sub {
316 print "$p\n" if $p =~ m/^$cur/;
320 my ($cmd, $def) = ($simple_cmd, $cmddef);
322 ($cmd, $def, $args, my $expanded) = resolve_cmd
($args);
324 if (defined($expanded) && $prev ne $expanded) {
329 if (ref($def) eq 'HASH') {
330 &$print_result(@{$get_commands->($def)});
336 my $pos = scalar(@$args) - 1;
337 $pos += 1 if $cmdline =~ m/\s+$/;
338 print STDERR
"pos: $pos\n" if $debug;
343 my ($class, $name, $arg_param, $uri_param) = @$def;
347 $arg_param = [ $arg_param ] if !ref($arg_param);
349 map { $skip_param->{$_} = 1; } @$arg_param;
350 map { $skip_param->{$_} = 1; } keys %$uri_param;
352 my $info = $class->map_method_by_name($name);
354 my $prop = $info->{parameters
}->{properties
};
356 my $print_parameter_completion = sub {
358 my $d = $prop->{$pname};
359 if ($d->{completion
}) {
360 my $vt = ref($d->{completion
});
362 my $res = $d->{completion
}->($cmd, $pname, $cur, $args);
363 &$print_result(@$res);
365 } elsif ($d->{type
} eq 'boolean') {
366 &$print_result('0', '1');
367 } elsif ($d->{enum
}) {
368 &$print_result(@{$d->{enum
}});
372 # positional arguments
373 $pos++ if $simple_cmd;
374 if ($pos < scalar(@$arg_param)) {
375 my $pname = $arg_param->[$pos];
376 &$print_parameter_completion($pname);
380 my @option_list = ();
381 foreach my $key (keys %$prop) {
382 next if $skip_param->{$key};
383 push @option_list, "--$key";
387 &$print_result(@option_list);
391 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
393 &$print_parameter_completion($pname);
397 &$print_result(@option_list);
403 # simply verify all registered methods
404 PVE
::RESTHandler
::validate_method_schemas
();
407 my $get_exe_name = sub {
417 sub generate_bash_completions
{
420 # generate bash completion config
422 $exename = &$get_exe_name($class);
425 # $exename bash completion
427 # see http://tiswww.case.edu/php/chet/bash/FAQ
428 # and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
429 # this modifies global var, but I found no better way
430 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
432 complete -o default -C '$exename bashcomplete' $exename
436 sub generate_asciidoc_synopsys
{
438 $class->generate_asciidoc_synopsis();
441 sub generate_asciidoc_synopsis
{
444 $cli_handler_class = $class;
446 $exename = &$get_exe_name($class);
449 my $def = ${"${class}::cmddef"};
452 if (ref($def) eq 'ARRAY') {
453 print_simple_asciidoc_synopsis
();
455 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['cmd'] ];
457 print_asciidoc_synopsis
();
461 # overwrite this if you want to run/setup things early
462 sub setup_environment
{
465 # do nothing by default
468 my $handle_cmd = sub {
469 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
471 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['extra-args'] ];
473 my ($cmd, $def, $cmd_args, undef, $cmd_str) = resolve_cmd
($args);
475 $abort->("no command specified") if !$cmd;
477 # call verifyapi before setup_environment(), don't execute any real code in
479 if ($cmd eq 'verifyapi') {
480 PVE
::RESTHandler
::validate_method_schemas
();
484 $cli_handler_class->setup_environment();
486 if ($cmd eq 'bashcomplete') {
487 &$print_bash_completion(undef, @$cmd_args);
491 # checked special commands, if def is still a hash we got an incomplete sub command
492 $abort->("incomplete command '$cmd_str'") if ref($def) eq 'HASH';
494 &$preparefunc() if $preparefunc;
496 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def || []};
497 $abort->("unknown command '$cmd_str'") if !$class;
499 my $res = $class->cli_handler($cmd_str, $name, $cmd_args, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
501 &$outsub($res) if $outsub;
504 my $handle_simple_cmd = sub {
505 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
507 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
508 die "no class specified" if !$class;
510 if (scalar(@$args) >= 1) {
511 if ($args->[0] eq 'help') {
512 my $str = "USAGE: $name help\n";
513 $str .= generate_usage_str
('long');
514 print STDERR
"$str\n\n";
516 } elsif ($args->[0] eq 'verifyapi') {
517 PVE
::RESTHandler
::validate_method_schemas
();
522 $cli_handler_class->setup_environment();
524 if (scalar(@$args) >= 1) {
525 if ($args->[0] eq 'bashcomplete') {
527 &$print_bash_completion($name, @$args);
532 &$preparefunc() if $preparefunc;
534 my $res = $class->cli_handler($name, $name, \
@ARGV, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
536 &$outsub($res) if $outsub;
539 sub run_cli_handler
{
540 my ($class, %params) = @_;
542 $cli_handler_class = $class;
544 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
546 foreach my $key (keys %params) {
547 next if $key eq 'prepare';
548 next if $key eq 'no_init'; # not used anymore
549 next if $key eq 'no_rpcenv'; # not used anymore
550 die "unknown parameter '$key'";
553 my $preparefunc = $params{prepare
};
555 my $read_password_func = $class->can('read_password');
556 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
557 $class->can('string_param_file_mapping');
559 $exename = &$get_exe_name($class);
564 $cmddef = ${"${class}::cmddef"};
566 if (ref($cmddef) eq 'ARRAY') {
567 &$handle_simple_cmd(\
@ARGV, $read_password_func, $preparefunc, $param_mapping_func);
569 &$handle_cmd(\
@ARGV, $read_password_func, $preparefunc, $param_mapping_func);