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 $read_password_func = $cli_handler_class->can('read_password');
121 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
122 $cli_handler_class->can('string_param_file_mapping');
124 my ($subcmd, $def) = resolve_cmd
($cmd);
128 my ($indent, $separator, $def, $prefix) = @_;
131 if (ref($def) eq 'HASH') {
132 my $oldclass = undef;
133 foreach my $cmd (&$sortfunc($def)) {
135 if (ref($def->{$cmd}) eq 'ARRAY') {
136 my ($class, $name, $arg_param, $fixed_param) = @{$def->{$cmd}};
138 $str .= $separator if $oldclass && $oldclass ne $class;
140 $str .= $class->usage_str($name, "$prefix $cmd", $arg_param,
141 $fixed_param, $format,
142 $read_password_func, $param_mapping_func);
145 } elsif (defined($def->{$cmd}->{alias
}) && ($format eq 'asciidoc')) {
147 $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n";
150 next if $def->{$cmd}->{alias
};
152 my $substr = $generate->($indent, $separator, $def->{$cmd}, "$prefix $cmd");
154 $substr .= $separator if $substr !~ /\Q$separator\E{2}/;
161 my ($class, $name, $arg_param, $fixed_param) = @$def;
162 $abort->("unknown command '$cmd'") if !$class;
165 $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format,
166 $read_password_func, $param_mapping_func);
171 my $cmdstr = $exename;
172 $cmdstr .= ' ' . join(' ', @$cmd) if defined($cmd);
174 return $generate->($indent, $separator, $def, $cmdstr);
177 __PACKAGE__-
>register_method ({
181 description
=> "Get help about specified command.",
183 additionalProperties
=> 0,
185 'extra-args' => PVE
::JSONSchema
::get_standard_option
('extra-args', {
186 description
=> 'Shows help for a specific command',
187 completion
=> $complete_command_names,
190 description
=> "Verbose output format.",
196 returns
=> { type
=> 'null' },
201 $assert_initialized->();
203 my $cmd = $param->{'extra-args'};
205 my $verbose = defined($cmd) && $cmd;
206 $verbose = $param->{verbose
} if defined($param->{verbose
});
210 print_usage_verbose
();
212 print_usage_short
(\
*STDOUT
);
219 $str = generate_usage_str
('full', $cmd, '');
221 $str = generate_usage_str
('short', $cmd, ' ' x
7);
228 print "USAGE: $str\n";
235 sub print_simple_asciidoc_synopsis
{
236 $assert_initialized->();
238 my $synopsis = "*${exename}* `help`\n\n";
239 $synopsis .= generate_usage_str
('asciidoc');
244 sub print_asciidoc_synopsis
{
245 $assert_initialized->();
249 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
251 $synopsis .= generate_usage_str
('asciidoc');
258 sub print_usage_verbose
{
259 $assert_initialized->();
261 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
263 my $str = generate_usage_str
('full');
268 sub print_usage_short
{
269 my ($fd, $msg, $cmd) = @_;
271 $assert_initialized->();
273 print $fd "ERROR: $msg\n" if $msg;
274 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
276 print {$fd} generate_usage_str
('short', $cmd, ' ' x
7, "\n", sub {
279 if (ref($h->{$a}) eq 'ARRAY' && ref($h->{$b}) eq 'ARRAY') {
280 # $a and $b are both real commands order them by their class
281 return $h->{$a}->[0] cmp $h->{$b}->[0] || $a cmp $b;
282 } elsif (ref($h->{$a}) eq 'ARRAY' xor ref($h->{$b}) eq 'ARRAY') {
283 # real command and subcommand mixed, put sub commands first
284 return ref($h->{$b}) eq 'ARRAY' ?
-1 : 1;
286 # both are either from the same class or subcommands
293 my $print_bash_completion = sub {
294 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
298 return if !(defined($cur) && defined($prev) && defined($bash_command));
299 return if !defined($ENV{COMP_LINE
});
300 return if !defined($ENV{COMP_POINT
});
302 my $cmdline = substr($ENV{COMP_LINE
}, 0, $ENV{COMP_POINT
});
303 print STDERR
"\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
305 my $args = PVE
::Tools
::split_args
($cmdline);
306 shift @$args; # no need for program name
307 my $print_result = sub {
309 print "$p\n" if $p =~ m/^$cur/;
313 my ($cmd, $def) = ($simple_cmd, $cmddef);
315 ($cmd, $def, $args, my $expaned) = resolve_cmd
($args);
317 if (ref($def) eq 'HASH') {
318 &$print_result(@{$get_commands->($def)});
321 if (my $expanded_cmd = $expaned->{$cur}) {
322 print "$expanded_cmd\n";
328 my $pos = scalar(@$args) - 1;
329 $pos += 1 if $cmdline =~ m/\s+$/;
330 print STDERR
"pos: $pos\n" if $debug;
335 my ($class, $name, $arg_param, $uri_param) = @$def;
339 $arg_param = [ $arg_param ] if !ref($arg_param);
341 map { $skip_param->{$_} = 1; } @$arg_param;
342 map { $skip_param->{$_} = 1; } keys %$uri_param;
344 my $info = $class->map_method_by_name($name);
346 my $prop = $info->{parameters
}->{properties
};
348 my $print_parameter_completion = sub {
350 my $d = $prop->{$pname};
351 if ($d->{completion
}) {
352 my $vt = ref($d->{completion
});
354 my $res = $d->{completion
}->($cmd, $pname, $cur, $args);
355 &$print_result(@$res);
357 } elsif ($d->{type
} eq 'boolean') {
358 &$print_result('0', '1');
359 } elsif ($d->{enum
}) {
360 &$print_result(@{$d->{enum
}});
364 # positional arguments
365 $pos++ if $simple_cmd;
366 if ($pos < scalar(@$arg_param)) {
367 my $pname = $arg_param->[$pos];
368 &$print_parameter_completion($pname);
372 my @option_list = ();
373 foreach my $key (keys %$prop) {
374 next if $skip_param->{$key};
375 push @option_list, "--$key";
379 &$print_result(@option_list);
383 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
385 &$print_parameter_completion($pname);
389 &$print_result(@option_list);
395 # simply verify all registered methods
396 PVE
::RESTHandler
::validate_method_schemas
();
399 my $get_exe_name = sub {
409 sub generate_bash_completions
{
412 # generate bash completion config
414 $exename = &$get_exe_name($class);
417 # $exename bash completion
419 # see http://tiswww.case.edu/php/chet/bash/FAQ
420 # and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
421 # this modifies global var, but I found no better way
422 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
424 complete -o default -C '$exename bashcomplete' $exename
428 sub generate_asciidoc_synopsys
{
430 $class->generate_asciidoc_synopsis();
433 sub generate_asciidoc_synopsis
{
436 $cli_handler_class = $class;
438 $exename = &$get_exe_name($class);
441 my $def = ${"${class}::cmddef"};
444 if (ref($def) eq 'ARRAY') {
445 print_simple_asciidoc_synopsis
();
447 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['cmd'] ];
449 print_asciidoc_synopsis
();
453 # overwrite this if you want to run/setup things early
454 sub setup_environment
{
457 # do nothing by default
460 my $handle_cmd = sub {
461 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
463 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['extra-args'] ];
465 my $cmd_str = join(' ', @$args);
466 my ($cmd, $def, $cmd_args) = resolve_cmd
($args);
468 $abort->("no command specified") if !$cmd;
470 # call verifyapi before setup_environment(), don't execute any real code in
472 if ($cmd eq 'verifyapi') {
473 PVE
::RESTHandler
::validate_method_schemas
();
477 $cli_handler_class->setup_environment();
479 if ($cmd eq 'bashcomplete') {
480 &$print_bash_completion(undef, @$cmd_args);
484 # checked special commands, if def is still a hash we got an incomplete sub command
485 $abort->("incomplete command '$exename $cmd_str'") if ref($def) eq 'HASH';
487 &$preparefunc() if $preparefunc;
489 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def || []};
490 $abort->("unknown command '$cmd_str'") if !$class;
492 my $prefix = "$exename $cmd_str";
493 my $res = $class->cli_handler($prefix, $name, $cmd_args, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
495 &$outsub($res) if $outsub;
498 my $handle_simple_cmd = sub {
499 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
501 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
502 die "no class specified" if !$class;
504 if (scalar(@$args) >= 1) {
505 if ($args->[0] eq 'help') {
506 my $str = "USAGE: $name help\n";
507 $str .= generate_usage_str
('long');
508 print STDERR
"$str\n\n";
510 } elsif ($args->[0] eq 'verifyapi') {
511 PVE
::RESTHandler
::validate_method_schemas
();
516 $cli_handler_class->setup_environment();
518 if (scalar(@$args) >= 1) {
519 if ($args->[0] eq 'bashcomplete') {
521 &$print_bash_completion($name, @$args);
526 &$preparefunc() if $preparefunc;
528 my $res = $class->cli_handler($name, $name, \
@ARGV, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
530 &$outsub($res) if $outsub;
533 sub run_cli_handler
{
534 my ($class, %params) = @_;
536 $cli_handler_class = $class;
538 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
540 foreach my $key (keys %params) {
541 next if $key eq 'prepare';
542 next if $key eq 'no_init'; # not used anymore
543 next if $key eq 'no_rpcenv'; # not used anymore
544 die "unknown parameter '$key'";
547 my $preparefunc = $params{prepare
};
549 my $read_password_func = $class->can('read_password');
550 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
551 $class->can('string_param_file_mapping');
553 $exename = &$get_exe_name($class);
558 $cmddef = ${"${class}::cmddef"};
560 if (ref($cmddef) eq 'ARRAY') {
561 &$handle_simple_cmd(\
@ARGV, $read_password_func, $preparefunc, $param_mapping_func);
563 &$handle_cmd(\
@ARGV, $read_password_func, $preparefunc, $param_mapping_func);