1 package PVE
::CLIHandler
;
7 use PVE
::Exception
qw(raise raise_param_exc);
11 use base
qw(PVE::RESTHandler);
15 my $cli_handler_class;
17 my $assert_initialized = sub {
19 die "$caller[0]:$caller[2] - not initialized\n"
20 if !($cmddef && $exename && $cli_handler_class);
24 my ($reason, $cmd) = @_;
25 print_usage_short
(\
*STDERR
, $reason, $cmd);
29 my $expand_command_name = sub {
33 my @expanded = grep { /^\Q$cmd\E/ } keys %$def;
34 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
39 my $get_commands = sub {
40 my $def = shift // die "no command definition passed!";
41 return [ grep { !(ref($def->{$_}) eq 'HASH' && defined($def->{$_}->{alias
})) } sort keys %$def ];
44 my $complete_command_names = sub { $get_commands->($cmddef) };
46 # traverses the command definition using the $argv array, resolving one level
48 # Returns the matching (sub) command and its definition, and argument array for
49 # this (sub) command and a hash where we marked which (sub) commands got
50 # expanded (e.g. st => status) while traversing
52 my ($argv, $is_alias) = @_;
54 my ($def, $cmd) = ($cmddef, $argv);
56 if (ref($argv) eq 'ARRAY') {
58 my $last_arg_id = scalar(@$argv) - 1;
60 for my $i (0..$last_arg_id) {
61 $cmd = $expand_command_name->($def, $argv->[$i]);
62 $expanded->{$argv->[$i]} = $cmd if $cmd ne $argv->[$i];
63 last if !defined($def->{$cmd});
66 if (ref($def) eq 'ARRAY') {
67 # could expand to a real command, rest of $argv are its arguments
68 my $cmd_args = [ @$argv[$i+1..$last_arg_id] ];
69 return ($cmd, $def, $cmd_args, $expanded);
72 if (defined($def->{alias
})) {
73 die "alias loop detected for '$cmd'" if $is_alias; # avoids cycles
74 # replace aliased (sub)command with the expanded aliased command
75 splice @$argv, $i, 1, split(/ +/, $def->{alias
});
76 return resolve_cmd
($argv, 1);
79 # got either a special command (bashcomplete, verifyapi) or an unknown
80 # cmd, just return first entry as cmd and the rest of $argv as cmd_arg
81 my $cmd_args = [ @$argv[1..$last_arg_id] ];
82 return ($argv->[0], $def, $cmd_args, $expanded);
87 sub generate_usage_str
{
88 my ($format, $cmd, $indent, $separator, $sortfunc) = @_;
90 $assert_initialized->();
91 die 'format required' if !$format;
93 $sortfunc //= sub { sort keys %{$_[0]} };
97 my $can_read_pass = $cli_handler_class->can('read_password');
98 my $can_str_param_fmap = $cli_handler_class->can('string_param_file_mapping');
100 my ($subcmd, $def) = resolve_cmd
($cmd);
104 my ($indent, $separator, $def, $prefix) = @_;
107 if (ref($def) eq 'HASH') {
108 my $oldclass = undef;
109 foreach my $cmd (&$sortfunc($def)) {
111 if (ref($def->{$cmd}) eq 'ARRAY') {
112 my ($class, $name, $arg_param, $fixed_param) = @{$def->{$cmd}};
114 $str .= $separator if $oldclass && $oldclass ne $class;
116 $str .= $class->usage_str($name, "$prefix $cmd", $arg_param,
117 $fixed_param, $format,
118 $can_read_pass, $can_str_param_fmap);
121 } elsif (defined($def->{$cmd}->{alias
}) && ($format eq 'asciidoc')) {
123 $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n";
126 next if $def->{$cmd}->{alias
};
128 my $substr = $generate->($indent, $separator, $def->{$cmd}, "$prefix $cmd");
130 $substr .= $separator if $substr !~ /\Q$separator\E{2}/;
137 my ($class, $name, $arg_param, $fixed_param) = @$def;
138 $abort->("unknown command '$cmd'") if !$class;
141 $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format,
142 $can_read_pass, $can_str_param_fmap);
147 my $cmdstr = $exename;
148 $cmdstr .= ' ' . join(' ', @$cmd) if defined($cmd);
150 return $generate->($indent, $separator, $def, $cmdstr);
153 __PACKAGE__-
>register_method ({
157 description
=> "Get help about specified command.",
159 additionalProperties
=> 0,
161 'extra-args' => PVE
::JSONSchema
::get_standard_option
('extra-args', {
162 description
=> 'Shows help for a specific command',
163 completion
=> $complete_command_names,
166 description
=> "Verbose output format.",
172 returns
=> { type
=> 'null' },
177 $assert_initialized->();
179 my $cmd = $param->{'extra-args'};
181 my $verbose = defined($cmd) && $cmd;
182 $verbose = $param->{verbose
} if defined($param->{verbose
});
186 print_usage_verbose
();
188 print_usage_short
(\
*STDOUT
);
195 $str = generate_usage_str
('full', $cmd, '');
197 $str = generate_usage_str
('short', $cmd, ' ' x
7);
204 print "USAGE: $str\n";
211 sub print_simple_asciidoc_synopsis
{
212 $assert_initialized->();
214 my $synopsis = "*${exename}* `help`\n\n";
215 $synopsis .= generate_usage_str
('asciidoc');
220 sub print_asciidoc_synopsis
{
221 $assert_initialized->();
225 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
227 $synopsis .= generate_usage_str
('asciidoc');
234 sub print_usage_verbose
{
235 $assert_initialized->();
237 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
239 my $str = generate_usage_str
('full');
244 sub print_usage_short
{
245 my ($fd, $msg, $cmd) = @_;
247 $assert_initialized->();
249 print $fd "ERROR: $msg\n" if $msg;
250 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
252 print {$fd} generate_usage_str
('short', $cmd, ' ' x
7, "\n", sub {
255 if (ref($h->{$a}) eq 'ARRAY' && ref($h->{$b}) eq 'ARRAY') {
256 # $a and $b are both real commands order them by their class
257 return $h->{$a}->[0] cmp $h->{$b}->[0] || $a cmp $b;
258 } elsif (ref($h->{$a}) eq 'ARRAY' xor ref($h->{$b}) eq 'ARRAY') {
259 # real command and subcommand mixed, put sub commands first
260 return ref($h->{$b}) eq 'ARRAY' ?
-1 : 1;
262 # both are either from the same class or subcommands
269 my $print_bash_completion = sub {
270 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
274 return if !(defined($cur) && defined($prev) && defined($bash_command));
275 return if !defined($ENV{COMP_LINE
});
276 return if !defined($ENV{COMP_POINT
});
278 my $cmdline = substr($ENV{COMP_LINE
}, 0, $ENV{COMP_POINT
});
279 print STDERR
"\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
281 my $args = PVE
::Tools
::split_args
($cmdline);
282 shift @$args; # no need for program name
283 my $print_result = sub {
285 print "$p\n" if $p =~ m/^$cur/;
289 my ($cmd, $def) = ($simple_cmd, $cmddef);
291 ($cmd, $def, $args, my $expaned) = resolve_cmd
($args);
293 if (ref($def) eq 'HASH') {
294 &$print_result(@{$get_commands->($def)});
297 if (my $expanded_cmd = $expaned->{$cur}) {
298 print "$expanded_cmd\n";
304 my $pos = scalar(@$args) - 1;
305 $pos += 1 if $cmdline =~ m/\s+$/;
306 print STDERR
"pos: $pos\n" if $debug;
311 my ($class, $name, $arg_param, $uri_param) = @$def;
315 $arg_param = [ $arg_param ] if !ref($arg_param);
317 map { $skip_param->{$_} = 1; } @$arg_param;
318 map { $skip_param->{$_} = 1; } keys %$uri_param;
320 my $info = $class->map_method_by_name($name);
322 my $prop = $info->{parameters
}->{properties
};
324 my $print_parameter_completion = sub {
326 my $d = $prop->{$pname};
327 if ($d->{completion
}) {
328 my $vt = ref($d->{completion
});
330 my $res = $d->{completion
}->($cmd, $pname, $cur, $args);
331 &$print_result(@$res);
333 } elsif ($d->{type
} eq 'boolean') {
334 &$print_result('0', '1');
335 } elsif ($d->{enum
}) {
336 &$print_result(@{$d->{enum
}});
340 # positional arguments
341 $pos++ if $simple_cmd;
342 if ($pos < scalar(@$arg_param)) {
343 my $pname = $arg_param->[$pos];
344 &$print_parameter_completion($pname);
348 my @option_list = ();
349 foreach my $key (keys %$prop) {
350 next if $skip_param->{$key};
351 push @option_list, "--$key";
355 &$print_result(@option_list);
359 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
361 &$print_parameter_completion($pname);
365 &$print_result(@option_list);
371 # simply verify all registered methods
372 PVE
::RESTHandler
::validate_method_schemas
();
375 my $get_exe_name = sub {
385 sub generate_bash_completions
{
388 # generate bash completion config
390 $exename = &$get_exe_name($class);
393 # $exename bash completion
395 # see http://tiswww.case.edu/php/chet/bash/FAQ
396 # and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
397 # this modifies global var, but I found no better way
398 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
400 complete -o default -C '$exename bashcomplete' $exename
404 sub generate_asciidoc_synopsys
{
406 $class->generate_asciidoc_synopsis();
409 sub generate_asciidoc_synopsis
{
412 $cli_handler_class = $class;
414 $exename = &$get_exe_name($class);
417 my $def = ${"${class}::cmddef"};
420 if (ref($def) eq 'ARRAY') {
421 print_simple_asciidoc_synopsis
();
423 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['cmd'] ];
425 print_asciidoc_synopsis
();
429 # overwrite this if you want to run/setup things early
430 sub setup_environment
{
433 # do nothing by default
436 my $handle_cmd = sub {
437 my ($args, $pwcallback, $preparefunc, $stringfilemap) = @_;
439 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['extra-args'] ];
441 my $cmd_str = join(' ', @$args);
442 my ($cmd, $def, $cmd_args) = resolve_cmd
($args);
444 $abort->("no command specified") if !$cmd;
446 # call verifyapi before setup_environment(), don't execute any real code in
448 if ($cmd eq 'verifyapi') {
449 PVE
::RESTHandler
::validate_method_schemas
();
453 $cli_handler_class->setup_environment();
455 if ($cmd eq 'bashcomplete') {
456 &$print_bash_completion(undef, @$cmd_args);
460 # checked special commands, if def is still a hash we got an incomplete sub command
461 $abort->("incomplete command '$exename $cmd_str'") if ref($def) eq 'HASH';
463 &$preparefunc() if $preparefunc;
465 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef->{$cmd} || []};
466 $abort->("unknown command '$cmd_str'") if !$class;
468 my $prefix = "$exename $cmd_str";
469 my $res = $class->cli_handler($prefix, $name, $cmd_args, $arg_param, $uri_param, $pwcallback, $stringfilemap);
471 &$outsub($res) if $outsub;
474 my $handle_simple_cmd = sub {
475 my ($args, $pwcallback, $preparefunc, $stringfilemap) = @_;
477 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
478 die "no class specified" if !$class;
480 if (scalar(@$args) >= 1) {
481 if ($args->[0] eq 'help') {
482 my $str = "USAGE: $name help\n";
483 $str .= generate_usage_str
('long');
484 print STDERR
"$str\n\n";
486 } elsif ($args->[0] eq 'verifyapi') {
487 PVE
::RESTHandler
::validate_method_schemas
();
492 $cli_handler_class->setup_environment();
494 if (scalar(@$args) >= 1) {
495 if ($args->[0] eq 'bashcomplete') {
497 &$print_bash_completion($name, @$args);
502 &$preparefunc() if $preparefunc;
504 my $res = $class->cli_handler($name, $name, \
@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
506 &$outsub($res) if $outsub;
509 sub run_cli_handler
{
510 my ($class, %params) = @_;
512 $cli_handler_class = $class;
514 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
516 foreach my $key (keys %params) {
517 next if $key eq 'prepare';
518 next if $key eq 'no_init'; # not used anymore
519 next if $key eq 'no_rpcenv'; # not used anymore
520 die "unknown parameter '$key'";
523 my $preparefunc = $params{prepare
};
525 my $pwcallback = $class->can('read_password');
526 my $stringfilemap = $class->can('string_param_file_mapping');
528 $exename = &$get_exe_name($class);
533 $cmddef = ${"${class}::cmddef"};
535 if (ref($cmddef) eq 'ARRAY') {
536 &$handle_simple_cmd(\
@ARGV, $pwcallback, $preparefunc, $stringfilemap);
538 &$handle_cmd(\
@ARGV, $pwcallback, $preparefunc, $stringfilemap);