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);
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]);
85 $expanded->{$argv->[$i]} = $cmd if $cmd ne $argv->[$i];
86 last if !defined($def->{$cmd});
89 if (ref($def) eq 'ARRAY') {
90 # could expand to a real command, rest of $argv are its arguments
91 my $cmd_args = [ @$argv[$i+1..$last_arg_id] ];
92 return ($cmd, $def, $cmd_args, $expanded);
95 if (defined($def->{alias
})) {
96 die "alias loop detected for '$cmd'" if $is_alias; # avoids cycles
97 # replace aliased (sub)command with the expanded aliased command
98 splice @$argv, $i, 1, split(/ +/, $def->{alias
});
99 return resolve_cmd
($argv, 1);
102 # got either a special command (bashcomplete, verifyapi) or an unknown
103 # cmd, just return first entry as cmd and the rest of $argv as cmd_arg
104 my $cmd_args = [ @$argv[1..$last_arg_id] ];
105 return ($argv->[0], $def, $cmd_args, $expanded);
110 sub generate_usage_str
{
111 my ($format, $cmd, $indent, $separator, $sortfunc) = @_;
113 $assert_initialized->();
114 die 'format required' if !$format;
116 $sortfunc //= sub { sort keys %{$_[0]} };
120 my $can_read_pass = $cli_handler_class->can('read_password');
121 my $can_str_param_fmap = $cli_handler_class->can('string_param_file_mapping');
123 my ($subcmd, $def) = resolve_cmd
($cmd);
127 my ($indent, $separator, $def, $prefix) = @_;
130 if (ref($def) eq 'HASH') {
131 my $oldclass = undef;
132 foreach my $cmd (&$sortfunc($def)) {
134 if (ref($def->{$cmd}) eq 'ARRAY') {
135 my ($class, $name, $arg_param, $fixed_param) = @{$def->{$cmd}};
137 $str .= $separator if $oldclass && $oldclass ne $class;
139 $str .= $class->usage_str($name, "$prefix $cmd", $arg_param,
140 $fixed_param, $format,
141 $can_read_pass, $can_str_param_fmap);
144 } elsif (defined($def->{$cmd}->{alias
}) && ($format eq 'asciidoc')) {
146 $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n";
149 next if $def->{$cmd}->{alias
};
151 my $substr = $generate->($indent, $separator, $def->{$cmd}, "$prefix $cmd");
153 $substr .= $separator if $substr !~ /\Q$separator\E{2}/;
160 my ($class, $name, $arg_param, $fixed_param) = @$def;
161 $abort->("unknown command '$cmd'") if !$class;
164 $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format,
165 $can_read_pass, $can_str_param_fmap);
170 my $cmdstr = $exename;
171 $cmdstr .= ' ' . join(' ', @$cmd) if defined($cmd);
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, $pwcallback, $preparefunc, $stringfilemap) = @_;
462 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['extra-args'] ];
464 my $cmd_str = join(' ', @$args);
465 my ($cmd, $def, $cmd_args) = resolve_cmd
($args);
467 $abort->("no command specified") if !$cmd;
469 # call verifyapi before setup_environment(), don't execute any real code in
471 if ($cmd eq 'verifyapi') {
472 PVE
::RESTHandler
::validate_method_schemas
();
476 $cli_handler_class->setup_environment();
478 if ($cmd eq 'bashcomplete') {
479 &$print_bash_completion(undef, @$cmd_args);
483 # checked special commands, if def is still a hash we got an incomplete sub command
484 $abort->("incomplete command '$exename $cmd_str'") if ref($def) eq 'HASH';
486 &$preparefunc() if $preparefunc;
488 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def || []};
489 $abort->("unknown command '$cmd_str'") if !$class;
491 my $prefix = "$exename $cmd_str";
492 my $res = $class->cli_handler($prefix, $name, $cmd_args, $arg_param, $uri_param, $pwcallback, $stringfilemap);
494 &$outsub($res) if $outsub;
497 my $handle_simple_cmd = sub {
498 my ($args, $pwcallback, $preparefunc, $stringfilemap) = @_;
500 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
501 die "no class specified" if !$class;
503 if (scalar(@$args) >= 1) {
504 if ($args->[0] eq 'help') {
505 my $str = "USAGE: $name help\n";
506 $str .= generate_usage_str
('long');
507 print STDERR
"$str\n\n";
509 } elsif ($args->[0] eq 'verifyapi') {
510 PVE
::RESTHandler
::validate_method_schemas
();
515 $cli_handler_class->setup_environment();
517 if (scalar(@$args) >= 1) {
518 if ($args->[0] eq 'bashcomplete') {
520 &$print_bash_completion($name, @$args);
525 &$preparefunc() if $preparefunc;
527 my $res = $class->cli_handler($name, $name, \
@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
529 &$outsub($res) if $outsub;
532 sub run_cli_handler
{
533 my ($class, %params) = @_;
535 $cli_handler_class = $class;
537 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
539 foreach my $key (keys %params) {
540 next if $key eq 'prepare';
541 next if $key eq 'no_init'; # not used anymore
542 next if $key eq 'no_rpcenv'; # not used anymore
543 die "unknown parameter '$key'";
546 my $preparefunc = $params{prepare
};
548 my $pwcallback = $class->can('read_password');
549 my $stringfilemap = $class->can('string_param_file_mapping');
551 $exename = &$get_exe_name($class);
556 $cmddef = ${"${class}::cmddef"};
558 if (ref($cmddef) eq 'ARRAY') {
559 &$handle_simple_cmd(\
@ARGV, $pwcallback, $preparefunc, $stringfilemap);
561 &$handle_cmd(\
@ARGV, $pwcallback, $preparefunc, $stringfilemap);