]> git.proxmox.com Git - pve-common.git/blame - src/PVE/CLIHandler.pm
cli: print_text_table: fix for poperties without schema
[pve-common.git] / src / PVE / CLIHandler.pm
CommitLineData
e143e9d8
DM
1package PVE::CLIHandler;
2
3use strict;
4use warnings;
340c9862 5use JSON;
e143e9d8 6
93ddd7bc 7use PVE::SafeSyslog;
e143e9d8
DM
8use PVE::Exception qw(raise raise_param_exc);
9use PVE::RESTHandler;
0da61ab3 10use PVE::PTY;
881eb755 11use PVE::INotify;
e143e9d8
DM
12
13use base qw(PVE::RESTHandler);
14
c1059f7c
TL
15# $cmddef defines which (sub)commands are available in a specific CLI class.
16# A real command is always an array consisting of its class, name, array of
17# position fixed (required) parameters and hash of predefined parameters when
18# mapping a CLI command t o an API call. Optionally an output method can be
19# passed at the end, e.g., for formatting or transformation purpose.
20#
21# [class, name, fixed_params, API_pre-set params, output_sub ]
22#
23# In case of so called 'simple commands', the $cmddef can be also just an
24# array.
25#
26# Examples:
27# $cmddef = {
28# command => [ 'PVE::API2::Class', 'command', [ 'arg1', 'arg2' ], { node => $nodename } ],
29# do => {
30# this => [ 'PVE::API2::OtherClass', 'method', [ 'arg1' ], undef, sub {
31# my ($res) = @_;
32# print "$res\n";
33# }],
34# that => [ 'PVE::API2::OtherClass', 'subroutine' [] ],
35# },
36# dothat => { alias => 'do that' },
37# }
e143e9d8
DM
38my $cmddef;
39my $exename;
891b798d 40my $cli_handler_class;
e143e9d8 41
37f010e7
TL
42my $standard_mappings = {
43 'pve-password' => {
44 name => 'password',
45 desc => '<password>',
46 interactive => 1,
47 func => sub {
48 my ($value) = @_;
49 return $value if $value;
50 return PVE::PTY::get_confirmed_password();
51 },
52 },
53};
54sub get_standard_mapping {
55 my ($name, $base) = @_;
56
57 my $std = $standard_mappings->{$name};
58 die "no such standard mapping '$name'\n" if !$std;
59
60 my $res = $base || {};
61
62 foreach my $opt (keys %$std) {
63 next if defined($res->{$opt});
64 $res->{$opt} = $std->{$opt};
65 }
66
67 return $res;
68}
69
d204696c
TL
70my $assert_initialized = sub {
71 my @caller = caller;
72 die "$caller[0]:$caller[2] - not initialized\n"
73 if !($cmddef && $exename && $cli_handler_class);
74};
75
918140af
TL
76my $abort = sub {
77 my ($reason, $cmd) = @_;
78 print_usage_short (\*STDERR, $reason, $cmd);
79 exit (-1);
80};
81
e143e9d8
DM
82my $expand_command_name = sub {
83 my ($def, $cmd) = @_;
84
5082a17b
WB
85 return $cmd if exists $def->{$cmd}; # command is already complete
86
ea5a5084 87 my $is_alias = sub { ref($_[0]) eq 'HASH' && exists($_[0]->{alias}) };
0b796806
TL
88 my @expanded = grep { /^\Q$cmd\E/ && !$is_alias->($def->{$_}) } keys %$def;
89
5082a17b
WB
90 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
91
92 return undef;
e143e9d8
DM
93};
94
50b89b88
TL
95my $get_commands = sub {
96 my $def = shift // die "no command definition passed!";
97 return [ grep { !(ref($def->{$_}) eq 'HASH' && defined($def->{$_}->{alias})) } sort keys %$def ];
edf3d572
DM
98};
99
50b89b88
TL
100my $complete_command_names = sub { $get_commands->($cmddef) };
101
102# traverses the command definition using the $argv array, resolving one level
103# of aliases.
104# Returns the matching (sub) command and its definition, and argument array for
105# this (sub) command and a hash where we marked which (sub) commands got
106# expanded (e.g. st => status) while traversing
107sub resolve_cmd {
108 my ($argv, $is_alias) = @_;
109
110 my ($def, $cmd) = ($cmddef, $argv);
f9326469 111 my $cmdstr = $exename;
50b89b88
TL
112
113 if (ref($argv) eq 'ARRAY') {
5082a17b 114 my $expanded_last_arg;
50b89b88
TL
115 my $last_arg_id = scalar(@$argv) - 1;
116
117 for my $i (0..$last_arg_id) {
118 $cmd = $expand_command_name->($def, $argv->[$i]);
5082a17b
WB
119 if (defined($cmd)) {
120 # If the argument was expanded (or was already complete) and it
121 # is the final argument, tell our caller about it:
122 $expanded_last_arg = $cmd if $i == $last_arg_id;
123 } else {
124 # Otherwise continue with the unexpanded version of it.
125 $cmd = $argv->[$i];
126 }
f9326469 127 $cmdstr .= " $cmd";
50b89b88 128 $def = $def->{$cmd};
57c0d0c6 129 last if !defined($def);
50b89b88
TL
130
131 if (ref($def) eq 'ARRAY') {
132 # could expand to a real command, rest of $argv are its arguments
133 my $cmd_args = [ @$argv[$i+1..$last_arg_id] ];
5082a17b 134 return ($cmd, $def, $cmd_args, $expanded_last_arg, $cmdstr);
50b89b88
TL
135 }
136
137 if (defined($def->{alias})) {
138 die "alias loop detected for '$cmd'" if $is_alias; # avoids cycles
139 # replace aliased (sub)command with the expanded aliased command
140 splice @$argv, $i, 1, split(/ +/, $def->{alias});
141 return resolve_cmd($argv, 1);
142 }
143 }
144 # got either a special command (bashcomplete, verifyapi) or an unknown
145 # cmd, just return first entry as cmd and the rest of $argv as cmd_arg
146 my $cmd_args = [ @$argv[1..$last_arg_id] ];
5082a17b 147 return ($argv->[0], $def, $cmd_args, $expanded_last_arg, $cmdstr);
50b89b88 148 }
f9326469 149 return ($cmd, $def, undef, undef, $cmdstr);
50b89b88
TL
150}
151
4c802a57
TL
152sub generate_usage_str {
153 my ($format, $cmd, $indent, $separator, $sortfunc) = @_;
154
155 $assert_initialized->();
156 die 'format required' if !$format;
157
158 $sortfunc //= sub { sort keys %{$_[0]} };
159 $separator //= '';
160 $indent //= '';
161
4e0214fa 162 my $read_password_func = $cli_handler_class->can('read_password');
c44ec0f6
DM
163 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
164 $cli_handler_class->can('string_param_file_mapping');
4c802a57 165
f9326469 166 my ($subcmd, $def, undef, undef, $cmdstr) = resolve_cmd($cmd);
24ccf353 167 $abort->("unknown command '$cmdstr'") if !defined($def) && ref($cmd) eq 'ARRAY';
4c802a57
TL
168
169 my $generate;
170 $generate = sub {
171 my ($indent, $separator, $def, $prefix) = @_;
172
173 my $str = '';
174 if (ref($def) eq 'HASH') {
175 my $oldclass = undef;
176 foreach my $cmd (&$sortfunc($def)) {
177
178 if (ref($def->{$cmd}) eq 'ARRAY') {
179 my ($class, $name, $arg_param, $fixed_param) = @{$def->{$cmd}};
180
181 $str .= $separator if $oldclass && $oldclass ne $class;
182 $str .= $indent;
183 $str .= $class->usage_str($name, "$prefix $cmd", $arg_param,
184 $fixed_param, $format,
4e0214fa 185 $read_password_func, $param_mapping_func);
4c802a57 186 $oldclass = $class;
50b89b88
TL
187
188 } elsif (defined($def->{$cmd}->{alias}) && ($format eq 'asciidoc')) {
189
190 $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n";
191
192 } else {
193 next if $def->{$cmd}->{alias};
194
195 my $substr = $generate->($indent, $separator, $def->{$cmd}, "$prefix $cmd");
196 if ($substr) {
197 $substr .= $separator if $substr !~ /\Q$separator\E{2}/;
198 $str .= $substr;
199 }
4c802a57
TL
200 }
201
202 }
203 } else {
204 my ($class, $name, $arg_param, $fixed_param) = @$def;
205 $abort->("unknown command '$cmd'") if !$class;
206
207 $str .= $indent;
208 $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format,
4e0214fa 209 $read_password_func, $param_mapping_func);
4c802a57
TL
210 }
211 return $str;
212 };
213
50b89b88 214 return $generate->($indent, $separator, $def, $cmdstr);
4c802a57
TL
215}
216
e143e9d8 217__PACKAGE__->register_method ({
3ef20687 218 name => 'help',
e143e9d8
DM
219 path => 'help',
220 method => 'GET',
221 description => "Get help about specified command.",
222 parameters => {
3ef20687 223 additionalProperties => 0,
e143e9d8 224 properties => {
6627ae09
TL
225 'extra-args' => PVE::JSONSchema::get_standard_option('extra-args', {
226 description => 'Shows help for a specific command',
edf3d572 227 completion => $complete_command_names,
6627ae09 228 }),
e143e9d8
DM
229 verbose => {
230 description => "Verbose output format.",
231 type => 'boolean',
232 optional => 1,
233 },
234 },
235 },
236 returns => { type => 'null' },
3ef20687 237
e143e9d8
DM
238 code => sub {
239 my ($param) = @_;
240
d204696c 241 $assert_initialized->();
e143e9d8 242
6627ae09 243 my $cmd = $param->{'extra-args'};
e143e9d8 244
6627ae09 245 my $verbose = defined($cmd) && $cmd;
e143e9d8
DM
246 $verbose = $param->{verbose} if defined($param->{verbose});
247
248 if (!$cmd) {
249 if ($verbose) {
250 print_usage_verbose();
3ef20687 251 } else {
e143e9d8
DM
252 print_usage_short(\*STDOUT);
253 }
254 return undef;
255 }
256
4c802a57
TL
257 my $str;
258 if ($verbose) {
259 $str = generate_usage_str('full', $cmd, '');
260 } else {
261 $str = generate_usage_str('short', $cmd, ' ' x 7);
262 }
263 $str =~ s/^\s+//;
e143e9d8 264
e143e9d8
DM
265 if ($verbose) {
266 print "$str\n";
267 } else {
268 print "USAGE: $str\n";
269 }
270
271 return undef;
272
273 }});
274
0a5a1eee 275sub print_simple_asciidoc_synopsis {
d204696c 276 $assert_initialized->();
fe3f1fde 277
4c802a57
TL
278 my $synopsis = "*${exename}* `help`\n\n";
279 $synopsis .= generate_usage_str('asciidoc');
fe3f1fde
DM
280
281 return $synopsis;
282}
283
0a5a1eee 284sub print_asciidoc_synopsis {
d204696c 285 $assert_initialized->();
fe3f1fde 286
fe3f1fde
DM
287 my $synopsis = "";
288
289 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
290
4c802a57 291 $synopsis .= generate_usage_str('asciidoc');
fe3f1fde
DM
292
293 $synopsis .= "\n";
294
295 return $synopsis;
296}
297
e143e9d8 298sub print_usage_verbose {
d204696c 299 $assert_initialized->();
891b798d 300
e143e9d8
DM
301 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
302
4c802a57 303 my $str = generate_usage_str('full');
e143e9d8 304
4c802a57 305 print "$str\n";
e143e9d8
DM
306}
307
308sub print_usage_short {
50b89b88 309 my ($fd, $msg, $cmd) = @_;
e143e9d8 310
d204696c 311 $assert_initialized->();
891b798d 312
e143e9d8
DM
313 print $fd "ERROR: $msg\n" if $msg;
314 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
315
50b89b88 316 print {$fd} generate_usage_str('short', $cmd, ' ' x 7, "\n", sub {
4c802a57
TL
317 my ($h) = @_;
318 return sort {
319 if (ref($h->{$a}) eq 'ARRAY' && ref($h->{$b}) eq 'ARRAY') {
320 # $a and $b are both real commands order them by their class
321 return $h->{$a}->[0] cmp $h->{$b}->[0] || $a cmp $b;
50b89b88
TL
322 } elsif (ref($h->{$a}) eq 'ARRAY' xor ref($h->{$b}) eq 'ARRAY') {
323 # real command and subcommand mixed, put sub commands first
324 return ref($h->{$b}) eq 'ARRAY' ? -1 : 1;
4c802a57 325 } else {
50b89b88 326 # both are either from the same class or subcommands
4c802a57
TL
327 return $a cmp $b;
328 }
329 } keys %$h;
330 });
e143e9d8
DM
331}
332
d8053c08 333my $print_bash_completion = sub {
57e67ea3 334 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
d8053c08
DM
335
336 my $debug = 0;
337
338 return if !(defined($cur) && defined($prev) && defined($bash_command));
339 return if !defined($ENV{COMP_LINE});
340 return if !defined($ENV{COMP_POINT});
341
342 my $cmdline = substr($ENV{COMP_LINE}, 0, $ENV{COMP_POINT});
343 print STDERR "\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
344
58d9e664 345 my $args = PVE::Tools::split_args($cmdline);
5fa768fc 346 shift @$args; # no need for program name
d8053c08
DM
347 my $print_result = sub {
348 foreach my $p (@_) {
2c48a665 349 print "$p\n" if $p =~ m/^\Q$cur\E/;
d8053c08
DM
350 }
351 };
352
5fa768fc
TL
353 my ($cmd, $def) = ($simple_cmd, $cmddef);
354 if (!$simple_cmd) {
0ed80698 355 ($cmd, $def, $args, my $expanded) = resolve_cmd($args);
50b89b88 356
5082a17b
WB
357 if (defined($expanded) && $prev ne $expanded) {
358 print "$expanded\n";
50b89b88
TL
359 return;
360 }
5082a17b
WB
361
362 if (ref($def) eq 'HASH') {
363 &$print_result(@{$get_commands->($def)});
d8053c08
DM
364 return;
365 }
d8053c08 366 }
d8053c08
DM
367 return if !$def;
368
5fa768fc
TL
369 my $pos = scalar(@$args) - 1;
370 $pos += 1 if $cmdline =~ m/\s+$/;
371 print STDERR "pos: $pos\n" if $debug;
372 return if $pos < 0;
d8053c08
DM
373
374 my $skip_param = {};
375
376 my ($class, $name, $arg_param, $uri_param) = @$def;
377 $arg_param //= [];
378 $uri_param //= {};
379
d90a2fd0
DM
380 $arg_param = [ $arg_param ] if !ref($arg_param);
381
d8053c08
DM
382 map { $skip_param->{$_} = 1; } @$arg_param;
383 map { $skip_param->{$_} = 1; } keys %$uri_param;
384
d8053c08
DM
385 my $info = $class->map_method_by_name($name);
386
5fa768fc 387 my $prop = $info->{parameters}->{properties};
d8053c08
DM
388
389 my $print_parameter_completion = sub {
390 my ($pname) = @_;
391 my $d = $prop->{$pname};
392 if ($d->{completion}) {
393 my $vt = ref($d->{completion});
394 if ($vt eq 'CODE') {
58d9e664 395 my $res = $d->{completion}->($cmd, $pname, $cur, $args);
d8053c08
DM
396 &$print_result(@$res);
397 }
398 } elsif ($d->{type} eq 'boolean') {
399 &$print_result('0', '1');
400 } elsif ($d->{enum}) {
401 &$print_result(@{$d->{enum}});
402 }
403 };
404
405 # positional arguments
5fa768fc
TL
406 if ($pos < scalar(@$arg_param)) {
407 my $pname = $arg_param->[$pos];
d8053c08
DM
408 &$print_parameter_completion($pname);
409 return;
410 }
411
412 my @option_list = ();
413 foreach my $key (keys %$prop) {
414 next if $skip_param->{$key};
415 push @option_list, "--$key";
416 }
417
418 if ($cur =~ m/^-/) {
419 &$print_result(@option_list);
420 return;
421 }
422
423 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
424 my $pname = $1;
425 &$print_parameter_completion($pname);
426 return;
427 }
428
429 &$print_result(@option_list);
430};
431
340c9862
DM
432sub data_to_text {
433 my ($data) = @_;
434
16f20332 435 return '' if !defined($data);
340c9862
DM
436
437 if (my $class = ref($data)) {
438 return to_json($data, { utf8 => 1, canonical => 1 });
439 } else {
440 return "$data";
441 }
442}
443
8042c2cc 444# prints a formatted table with a title row.
8dd3280b
DM
445# $data - the data to print (array of objects)
446# $returnprops -json schema property description
447# $props_to_print - ordered list of properties to print
9ac6416e
TL
448# $sort_key can be used to sort after a column, if it isn't set we sort
449# after the leftmost column (with no undef value in $data) this can be
450# turned off by passing 0 as $sort_key
8042c2cc 451sub print_text_table {
8dd3280b 452 my ($data, $returnprops, $props_to_print, $sort_key) = @_;
85b9def2 453
9ac6416e
TL
454 my $autosort = 1;
455 if (defined($sort_key) && $sort_key eq 0) {
456 $autosort = 0;
505786f6
DM
457 $sort_key = undef;
458 }
459
8dd3280b
DM
460 my $colopts = {};
461 my $formatstring = '';
462
463 my $column_count = scalar(@$props_to_print);
464
465 for (my $i = 0; $i < $column_count; $i++) {
466 my $prop = $props_to_print->[$i];
ffe4449c 467 my $propinfo = $returnprops->{$prop} // {};
8dd3280b 468 die "undefined property '$prop'" if !$propinfo;
8042c2cc 469
8dd3280b
DM
470 my $title = $propinfo->{title} // $prop;
471 my $cutoff = $propinfo->{print_width} // $propinfo->{maxLength};
8042c2cc 472
85b9def2 473 # calculate maximal print width and cutoff
8042c2cc
SI
474 my $titlelen = length($title);
475
476 my $longest = $titlelen;
505786f6 477 my $sortable = $autosort;
8042c2cc 478 foreach my $entry (@$data) {
8dd3280b 479 my $len = length(data_to_text($entry->{$prop})) // 0;
8042c2cc 480 $longest = $len if $len > $longest;
8dd3280b 481 $sortable = 0 if !defined($entry->{$prop});
8042c2cc 482 }
83794659 483 $cutoff = $longest if !defined($cutoff) || $cutoff > $longest;
8dd3280b 484 $sort_key //= $prop if $sortable;
8042c2cc 485
8dd3280b
DM
486 $colopts->{$prop} = {
487 title => $title,
488 default => $propinfo->{default} // '',
489 cutoff => $cutoff,
490 };
491
83794659 492 # skip alignment and cutoff on last column
8dd3280b 493 $formatstring .= ($i == ($column_count - 1)) ? "%s\n" : "%-${cutoff}s ";
8042c2cc
SI
494 }
495
8dd3280b 496 printf $formatstring, map { $colopts->{$_}->{title} } @$props_to_print;
8042c2cc 497
8dd3280b 498 if (defined($sort_key)) {
83794659
TL
499 my $type = $returnprops->{$sort_key}->{type};
500 if ($type eq 'integer' || $type eq 'number') {
8dd3280b
DM
501 @$data = sort { $a->{$sort_key} <=> $b->{$sort_key} } @$data;
502 } else {
503 @$data = sort { $a->{$sort_key} cmp $b->{$sort_key} } @$data;
504 }
e05f7cdd 505 }
8dd3280b 506
e05f7cdd 507 foreach my $entry (@$data) {
8dd3280b
DM
508 printf $formatstring, map {
509 substr(data_to_text($entry->{$_}) // $colopts->{$_}->{default},
510 0, $colopts->{$_}->{cutoff});
511 } @$props_to_print;
8042c2cc
SI
512 }
513}
514
db5b22d1
SI
515# prints the result of an API GET call returning an array as a table.
516# takes formatting information from the results property of the call
517# if $props_to_print is provided, prints only those columns. otherwise
518# takes all fields of the results property, with a fallback
519# to all fields occuring in items of $data.
a604bf22 520sub print_api_list {
505786f6 521 my ($data, $result_schema, $props_to_print, $sort_key) = @_;
85b9def2 522
2edb0abb 523 die "can only print object lists\n"
ec3cbded 524 if !($result_schema->{type} eq 'array' && $result_schema->{items}->{type} eq 'object');
305fc1e1 525
ec3cbded 526 my $returnprops = $result_schema->{items}->{properties};
85b9def2 527
eb04f1e2
DM
528 if (!defined($props_to_print)) {
529 $props_to_print = [ sort keys %$returnprops ];
530 if (!scalar(@$props_to_print)) {
9b8f2f8f
SI
531 my $all_props = {};
532 foreach my $obj (@{$data}) {
533 foreach my $key (keys %{$obj}) {
534 $all_props->{ $key } = 1;
535 }
536 }
537 $props_to_print = [ sort keys %{$all_props} ];
eb04f1e2
DM
538 }
539 die "unable to detect list properties\n" if !scalar(@$props_to_print);
540 }
541
8dd3280b 542 print_text_table($data, $returnprops, $props_to_print, $sort_key);
a604bf22
SI
543}
544
340c9862 545sub print_api_result {
505786f6 546 my ($format, $data, $result_schema, $props_to_print, $sort_key) = @_;
340c9862
DM
547
548 return if $result_schema->{type} eq 'null';
549
550 if ($format eq 'json') {
551 print to_json($data, {utf8 => 1, allow_nonref => 1, canonical => 1, pretty => 1 });
552 } elsif ($format eq 'text') {
553 my $type = $result_schema->{type};
554 if ($type eq 'object') {
fa7d20bf
TL
555 $props_to_print = [ sort keys %$data ] if !defined($props_to_print);
556 foreach my $key (@$props_to_print) {
557 print $key . ": " . data_to_text($data->{$key}) . "\n";
340c9862
DM
558 }
559 } elsif ($type eq 'array') {
560 return if !scalar(@$data);
561 my $item_type = $result_schema->{items}->{type};
562 if ($item_type eq 'object') {
505786f6 563 print_api_list($data, $result_schema, $props_to_print, $sort_key);
340c9862
DM
564 } else {
565 foreach my $entry (@$data) {
566 print data_to_text($entry) . "\n";
567 }
568 }
569 } else {
570 print "$data\n";
571 }
572 } else {
573 die "internal error: unknown output format"; # should not happen
574 }
575}
576
1f130ba6
DM
577sub verify_api {
578 my ($class) = @_;
579
580 # simply verify all registered methods
581 PVE::RESTHandler::validate_method_schemas();
582}
583
8f3712f8
DM
584my $get_exe_name = sub {
585 my ($class) = @_;
3ef20687 586
8f3712f8
DM
587 my $name = $class;
588 $name =~ s/^.*:://;
589 $name =~ s/_/-/g;
590
591 return $name;
592};
593
c45707a0
DM
594sub generate_bash_completions {
595 my ($class) = @_;
596
597 # generate bash completion config
598
8f3712f8 599 $exename = &$get_exe_name($class);
c45707a0
DM
600
601 print <<__EOD__;
602# $exename bash completion
603
604# see http://tiswww.case.edu/php/chet/bash/FAQ
605# and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
606# this modifies global var, but I found no better way
607COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
608
e4a1d8e2 609complete -o default -C '$exename bashcomplete' $exename
c45707a0
DM
610__EOD__
611}
612
fe3f1fde
DM
613sub generate_asciidoc_synopsys {
614 my ($class) = @_;
0a5a1eee
FG
615 $class->generate_asciidoc_synopsis();
616};
617
618sub generate_asciidoc_synopsis {
619 my ($class) = @_;
fe3f1fde
DM
620
621 $cli_handler_class = $class;
622
623 $exename = &$get_exe_name($class);
624
625 no strict 'refs';
626 my $def = ${"${class}::cmddef"};
57e67ea3 627 $cmddef = $def;
fe3f1fde
DM
628
629 if (ref($def) eq 'ARRAY') {
4c802a57 630 print_simple_asciidoc_synopsis();
fe3f1fde 631 } else {
fe3f1fde
DM
632 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
633
0a5a1eee 634 print_asciidoc_synopsis();
fe3f1fde
DM
635 }
636}
637
7b7f99c9
DM
638# overwrite this if you want to run/setup things early
639sub setup_environment {
640 my ($class) = @_;
641
642 # do nothing by default
643}
644
891b798d 645my $handle_cmd = sub {
8d3eb3ce 646 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
e143e9d8 647
6627ae09 648 $cmddef->{help} = [ __PACKAGE__, 'help', ['extra-args'] ];
e143e9d8 649
f9326469 650 my ($cmd, $def, $cmd_args, undef, $cmd_str) = resolve_cmd($args);
7b7f99c9 651
918140af
TL
652 $abort->("no command specified") if !$cmd;
653
654 # call verifyapi before setup_environment(), don't execute any real code in
655 # this case
656 if ($cmd eq 'verifyapi') {
e143e9d8
DM
657 PVE::RESTHandler::validate_method_schemas();
658 return;
7b7f99c9
DM
659 }
660
661 $cli_handler_class->setup_environment();
662
663 if ($cmd eq 'bashcomplete') {
50b89b88 664 &$print_bash_completion(undef, @$cmd_args);
d8053c08 665 return;
e143e9d8
DM
666 }
667
50b89b88 668 # checked special commands, if def is still a hash we got an incomplete sub command
131f316b 669 $abort->("incomplete command '$cmd_str'", $args) if ref($def) eq 'HASH';
8e3e9929 670
50b89b88 671 &$preparefunc() if $preparefunc;
e143e9d8 672
b8dc4366 673 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def || []};
50b89b88 674 $abort->("unknown command '$cmd_str'") if !$class;
e143e9d8 675
f9326469 676 my $res = $class->cli_handler($cmd_str, $name, $cmd_args, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
2026f4b5 677
a604bf22 678 if (defined $outsub) {
ec3cbded
DM
679 my $result_schema = $class->map_method_by_name($name)->{returns};
680 $outsub->($res, $result_schema);
a604bf22 681 }
891b798d 682};
2026f4b5 683
891b798d 684my $handle_simple_cmd = sub {
8d3eb3ce 685 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
2026f4b5 686
57e67ea3 687 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
2026f4b5
DM
688 die "no class specified" if !$class;
689
d8053c08 690 if (scalar(@$args) >= 1) {
2026f4b5
DM
691 if ($args->[0] eq 'help') {
692 my $str = "USAGE: $name help\n";
4c802a57 693 $str .= generate_usage_str('long');
2026f4b5
DM
694 print STDERR "$str\n\n";
695 return;
696 } elsif ($args->[0] eq 'verifyapi') {
697 PVE::RESTHandler::validate_method_schemas();
698 return;
2026f4b5 699 }
e143e9d8 700 }
2026f4b5 701
7b7f99c9
DM
702 $cli_handler_class->setup_environment();
703
704 if (scalar(@$args) >= 1) {
705 if ($args->[0] eq 'bashcomplete') {
706 shift @$args;
57e67ea3 707 &$print_bash_completion($name, @$args);
7b7f99c9
DM
708 return;
709 }
710 }
711
7fe1f565
DM
712 &$preparefunc() if $preparefunc;
713
8d3eb3ce 714 my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
2026f4b5 715
a604bf22 716 if (defined $outsub) {
ec3cbded
DM
717 my $result_schema = $class->map_method_by_name($name)->{returns};
718 $outsub->($res, $result_schema);
a604bf22 719 }
891b798d
DM
720};
721
891b798d
DM
722sub run_cli_handler {
723 my ($class, %params) = @_;
724
725 $cli_handler_class = $class;
726
727 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
728
aa9b9af5 729 foreach my $key (keys %params) {
5ae87c41 730 next if $key eq 'prepare';
1042b82c
DM
731 next if $key eq 'no_init'; # not used anymore
732 next if $key eq 'no_rpcenv'; # not used anymore
aa9b9af5
DM
733 die "unknown parameter '$key'";
734 }
735
5ae87c41 736 my $preparefunc = $params{prepare};
891b798d 737
8d3eb3ce 738 my $read_password_func = $class->can('read_password');
c44ec0f6
DM
739 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
740 $class->can('string_param_file_mapping');
891b798d
DM
741
742 $exename = &$get_exe_name($class);
743
744 initlog($exename);
745
891b798d 746 no strict 'refs';
57e67ea3 747 $cmddef = ${"${class}::cmddef"};
891b798d 748
57e67ea3 749 if (ref($cmddef) eq 'ARRAY') {
8d3eb3ce 750 &$handle_simple_cmd(\@ARGV, $read_password_func, $preparefunc, $param_mapping_func);
891b798d 751 } else {
8d3eb3ce 752 &$handle_cmd(\@ARGV, $read_password_func, $preparefunc, $param_mapping_func);
891b798d
DM
753 }
754
755 exit 0;
e143e9d8
DM
756}
757
7581;