]> git.proxmox.com Git - pve-common.git/blame - src/PVE/CLIHandler.pm
cli: refactor and use $cmddef directly
[pve-common.git] / src / PVE / CLIHandler.pm
CommitLineData
e143e9d8
DM
1package PVE::CLIHandler;
2
3use strict;
4use warnings;
5
93ddd7bc 6use PVE::SafeSyslog;
e143e9d8
DM
7use PVE::Exception qw(raise raise_param_exc);
8use PVE::RESTHandler;
881eb755 9use PVE::INotify;
e143e9d8
DM
10
11use base qw(PVE::RESTHandler);
12
13my $cmddef;
14my $exename;
891b798d 15my $cli_handler_class;
e143e9d8
DM
16
17my $expand_command_name = sub {
18 my ($def, $cmd) = @_;
19
20 if (!$def->{$cmd}) {
21 my $expanded;
22 for my $k (keys(%$def)) {
23 if ($k =~ m/^$cmd/) {
24 if ($expanded) {
25 $expanded = undef; # more than one match
26 last;
27 } else {
28 $expanded = $k;
29 }
30 }
31 }
32 $cmd = $expanded if $expanded;
33 }
34 return $cmd;
35};
36
edf3d572
DM
37my $complete_command_names = sub {
38 my $res = [];
39
40 return if ref($cmddef) ne 'HASH';
41
42 foreach my $cmd (keys %$cmddef) {
43 next if $cmd eq 'help';
44 push @$res, $cmd;
45 }
46
47 return $res;
48};
49
e143e9d8 50__PACKAGE__->register_method ({
3ef20687 51 name => 'help',
e143e9d8
DM
52 path => 'help',
53 method => 'GET',
54 description => "Get help about specified command.",
55 parameters => {
3ef20687 56 additionalProperties => 0,
e143e9d8
DM
57 properties => {
58 cmd => {
59 description => "Command name",
60 type => 'string',
61 optional => 1,
edf3d572 62 completion => $complete_command_names,
e143e9d8
DM
63 },
64 verbose => {
65 description => "Verbose output format.",
66 type => 'boolean',
67 optional => 1,
68 },
69 },
70 },
71 returns => { type => 'null' },
3ef20687 72
e143e9d8
DM
73 code => sub {
74 my ($param) = @_;
75
891b798d 76 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
e143e9d8
DM
77
78 my $cmd = $param->{cmd};
79
80 my $verbose = defined($cmd) && $cmd;
81 $verbose = $param->{verbose} if defined($param->{verbose});
82
83 if (!$cmd) {
84 if ($verbose) {
85 print_usage_verbose();
3ef20687 86 } else {
e143e9d8
DM
87 print_usage_short(\*STDOUT);
88 }
89 return undef;
90 }
91
92 $cmd = &$expand_command_name($cmddef, $cmd);
93
94 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd} || []};
95
96 raise_param_exc({ cmd => "no such command '$cmd'"}) if !$class;
97
891b798d 98 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 99 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
e143e9d8 100
891b798d 101 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param,
4845032a
FG
102 $verbose ? 'full' : 'short', $pwcallback,
103 $stringfilemap);
e143e9d8
DM
104 if ($verbose) {
105 print "$str\n";
106 } else {
107 print "USAGE: $str\n";
108 }
109
110 return undef;
111
112 }});
113
0a5a1eee 114sub print_simple_asciidoc_synopsis {
fe3f1fde
DM
115 my ($class, $name, $arg_param, $uri_param) = @_;
116
117 die "not initialized" if !$cli_handler_class;
118
119 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 120 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
fe3f1fde
DM
121
122 my $synopsis = "*${name}* `help`\n\n";
123
4845032a
FG
124 $synopsis .= $class->usage_str($name, $name, $arg_param, $uri_param,
125 'asciidoc', $pwcallback, $stringfilemap);
fe3f1fde
DM
126
127 return $synopsis;
128}
129
0a5a1eee 130sub print_asciidoc_synopsis {
fe3f1fde
DM
131
132 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
133
134 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 135 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
fe3f1fde
DM
136
137 my $synopsis = "";
138
139 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
140
141 my $oldclass;
142 foreach my $cmd (sort keys %$cmddef) {
143 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
144 my $str = $class->usage_str($name, "$exename $cmd", $arg_param,
4845032a
FG
145 $uri_param, 'asciidoc', $pwcallback,
146 $stringfilemap);
fe3f1fde
DM
147 $synopsis .= "\n" if $oldclass && $oldclass ne $class;
148
149 $synopsis .= "$str\n\n";
150 $oldclass = $class;
151 }
152
153 $synopsis .= "\n";
154
155 return $synopsis;
156}
157
e143e9d8
DM
158sub print_usage_verbose {
159
891b798d
DM
160 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
161
162 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 163 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
e143e9d8
DM
164
165 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
166
167 foreach my $cmd (sort keys %$cmddef) {
168 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
891b798d 169 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param,
4845032a 170 'full', $pwcallback, $stringfilemap);
e143e9d8
DM
171 print "$str\n\n";
172 }
173}
174
175sub sorted_commands {
176 return sort { ($cmddef->{$a}->[0] cmp $cmddef->{$b}->[0]) || ($a cmp $b)} keys %$cmddef;
177}
178
179sub print_usage_short {
180 my ($fd, $msg) = @_;
181
891b798d
DM
182 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
183
184 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 185 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
e143e9d8
DM
186
187 print $fd "ERROR: $msg\n" if $msg;
188 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
189
190 my $oldclass;
191 foreach my $cmd (sorted_commands()) {
192 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
4845032a 193 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param, 'short', $pwcallback, $stringfilemap);
e143e9d8
DM
194 print $fd "\n" if $oldclass && $oldclass ne $class;
195 print $fd " $str";
196 $oldclass = $class;
197 }
198}
199
d8053c08 200my $print_bash_completion = sub {
57e67ea3 201 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
d8053c08
DM
202
203 my $debug = 0;
204
205 return if !(defined($cur) && defined($prev) && defined($bash_command));
206 return if !defined($ENV{COMP_LINE});
207 return if !defined($ENV{COMP_POINT});
208
209 my $cmdline = substr($ENV{COMP_LINE}, 0, $ENV{COMP_POINT});
210 print STDERR "\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
211
58d9e664
DM
212 my $args = PVE::Tools::split_args($cmdline);
213 my $pos = scalar(@$args) - 2;
d8053c08
DM
214 $pos += 1 if $cmdline =~ m/\s+$/;
215
216 print STDERR "CMDLINE:$pos:$cmdline\n" if $debug;
217
218 return if $pos < 0;
219
220 my $print_result = sub {
221 foreach my $p (@_) {
222 print "$p\n" if $p =~ m/^$cur/;
223 }
224 };
225
226 my $cmd;
227 if ($simple_cmd) {
228 $cmd = $simple_cmd;
229 } else {
230 if ($pos == 0) {
231 &$print_result(keys %$cmddef);
232 return;
233 }
58d9e664 234 $cmd = $args->[1];
d8053c08
DM
235 }
236
237 my $def = $cmddef->{$cmd};
238 return if !$def;
239
240 print STDERR "CMDLINE1:$pos:$cmdline\n" if $debug;
241
242 my $skip_param = {};
243
244 my ($class, $name, $arg_param, $uri_param) = @$def;
245 $arg_param //= [];
246 $uri_param //= {};
247
d90a2fd0
DM
248 $arg_param = [ $arg_param ] if !ref($arg_param);
249
d8053c08
DM
250 map { $skip_param->{$_} = 1; } @$arg_param;
251 map { $skip_param->{$_} = 1; } keys %$uri_param;
252
253 my $fpcount = scalar(@$arg_param);
254
255 my $info = $class->map_method_by_name($name);
256
257 my $schema = $info->{parameters};
258 my $prop = $schema->{properties};
259
260 my $print_parameter_completion = sub {
261 my ($pname) = @_;
262 my $d = $prop->{$pname};
263 if ($d->{completion}) {
264 my $vt = ref($d->{completion});
265 if ($vt eq 'CODE') {
58d9e664 266 my $res = $d->{completion}->($cmd, $pname, $cur, $args);
d8053c08
DM
267 &$print_result(@$res);
268 }
269 } elsif ($d->{type} eq 'boolean') {
270 &$print_result('0', '1');
271 } elsif ($d->{enum}) {
272 &$print_result(@{$d->{enum}});
273 }
274 };
275
276 # positional arguments
277 $pos += 1 if $simple_cmd;
278 if ($fpcount && $pos <= $fpcount) {
279 my $pname = $arg_param->[$pos -1];
280 &$print_parameter_completion($pname);
281 return;
282 }
283
284 my @option_list = ();
285 foreach my $key (keys %$prop) {
286 next if $skip_param->{$key};
287 push @option_list, "--$key";
288 }
289
290 if ($cur =~ m/^-/) {
291 &$print_result(@option_list);
292 return;
293 }
294
295 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
296 my $pname = $1;
297 &$print_parameter_completion($pname);
298 return;
299 }
300
301 &$print_result(@option_list);
302};
303
1f130ba6
DM
304sub verify_api {
305 my ($class) = @_;
306
307 # simply verify all registered methods
308 PVE::RESTHandler::validate_method_schemas();
309}
310
8f3712f8
DM
311my $get_exe_name = sub {
312 my ($class) = @_;
3ef20687 313
8f3712f8
DM
314 my $name = $class;
315 $name =~ s/^.*:://;
316 $name =~ s/_/-/g;
317
318 return $name;
319};
320
c45707a0
DM
321sub generate_bash_completions {
322 my ($class) = @_;
323
324 # generate bash completion config
325
8f3712f8 326 $exename = &$get_exe_name($class);
c45707a0
DM
327
328 print <<__EOD__;
329# $exename bash completion
330
331# see http://tiswww.case.edu/php/chet/bash/FAQ
332# and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
333# this modifies global var, but I found no better way
334COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
335
e4a1d8e2 336complete -o default -C '$exename bashcomplete' $exename
c45707a0
DM
337__EOD__
338}
339
fe3f1fde
DM
340sub generate_asciidoc_synopsys {
341 my ($class) = @_;
0a5a1eee
FG
342 $class->generate_asciidoc_synopsis();
343};
344
345sub generate_asciidoc_synopsis {
346 my ($class) = @_;
fe3f1fde
DM
347
348 $cli_handler_class = $class;
349
350 $exename = &$get_exe_name($class);
351
352 no strict 'refs';
353 my $def = ${"${class}::cmddef"};
57e67ea3 354 $cmddef = $def;
fe3f1fde
DM
355
356 if (ref($def) eq 'ARRAY') {
0a5a1eee 357 print_simple_asciidoc_synopsis(@$def);
fe3f1fde 358 } else {
fe3f1fde
DM
359 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
360
0a5a1eee 361 print_asciidoc_synopsis();
fe3f1fde
DM
362 }
363}
364
7b7f99c9
DM
365# overwrite this if you want to run/setup things early
366sub setup_environment {
367 my ($class) = @_;
368
369 # do nothing by default
370}
371
891b798d 372my $handle_cmd = sub {
57e67ea3 373 my ($args, $pwcallback, $preparefunc, $stringfilemap) = @_;
e143e9d8
DM
374
375 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
376
7b7f99c9
DM
377 # call verifyapi before setup_environment(), because we do not want to
378 # execute any real code in this case
379
57e67ea3 380 my $cmd = shift @$args;
7b7f99c9 381 if (!$cmd) {
e143e9d8
DM
382 print_usage_short (\*STDERR, "no command specified");
383 exit (-1);
384 } elsif ($cmd eq 'verifyapi') {
385 PVE::RESTHandler::validate_method_schemas();
386 return;
7b7f99c9
DM
387 }
388
389 $cli_handler_class->setup_environment();
390
391 if ($cmd eq 'bashcomplete') {
57e67ea3 392 &$print_bash_completion(undef, @$args);
d8053c08 393 return;
e143e9d8
DM
394 }
395
8e3e9929
WB
396 &$preparefunc() if $preparefunc;
397
e143e9d8
DM
398 $cmd = &$expand_command_name($cmddef, $cmd);
399
400 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef->{$cmd} || []};
401
402 if (!$class) {
403 print_usage_short (\*STDERR, "unknown command '$cmd'");
404 exit (-1);
405 }
406
407 my $prefix = "$exename $cmd";
408976c6 408 my $res = $class->cli_handler($prefix, $name, \@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
2026f4b5
DM
409
410 &$outsub($res) if $outsub;
891b798d 411};
2026f4b5 412
891b798d 413my $handle_simple_cmd = sub {
57e67ea3 414 my ($args, $pwcallback, $preparefunc, $stringfilemap) = @_;
2026f4b5 415
57e67ea3 416 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
2026f4b5
DM
417 die "no class specified" if !$class;
418
d8053c08 419 if (scalar(@$args) >= 1) {
2026f4b5
DM
420 if ($args->[0] eq 'help') {
421 my $str = "USAGE: $name help\n";
4845032a 422 $str .= $class->usage_str($name, $name, $arg_param, $uri_param, 'long', $pwcallback, $stringfilemap);
2026f4b5
DM
423 print STDERR "$str\n\n";
424 return;
425 } elsif ($args->[0] eq 'verifyapi') {
426 PVE::RESTHandler::validate_method_schemas();
427 return;
2026f4b5 428 }
e143e9d8 429 }
2026f4b5 430
7b7f99c9
DM
431 $cli_handler_class->setup_environment();
432
433 if (scalar(@$args) >= 1) {
434 if ($args->[0] eq 'bashcomplete') {
435 shift @$args;
57e67ea3 436 &$print_bash_completion($name, @$args);
7b7f99c9
DM
437 return;
438 }
439 }
440
7fe1f565
DM
441 &$preparefunc() if $preparefunc;
442
408976c6 443 my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
2026f4b5
DM
444
445 &$outsub($res) if $outsub;
891b798d
DM
446};
447
891b798d
DM
448sub run_cli_handler {
449 my ($class, %params) = @_;
450
451 $cli_handler_class = $class;
452
453 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
454
aa9b9af5 455 foreach my $key (keys %params) {
5ae87c41 456 next if $key eq 'prepare';
1042b82c
DM
457 next if $key eq 'no_init'; # not used anymore
458 next if $key eq 'no_rpcenv'; # not used anymore
aa9b9af5
DM
459 die "unknown parameter '$key'";
460 }
461
5ae87c41 462 my $preparefunc = $params{prepare};
891b798d
DM
463
464 my $pwcallback = $class->can('read_password');
408976c6 465 my $stringfilemap = $class->can('string_param_file_mapping');
891b798d
DM
466
467 $exename = &$get_exe_name($class);
468
469 initlog($exename);
470
891b798d 471 no strict 'refs';
57e67ea3 472 $cmddef = ${"${class}::cmddef"};
891b798d 473
57e67ea3
TL
474 if (ref($cmddef) eq 'ARRAY') {
475 &$handle_simple_cmd(\@ARGV, $pwcallback, $preparefunc, $stringfilemap);
891b798d 476 } else {
57e67ea3 477 &$handle_cmd(\@ARGV, $pwcallback, $preparefunc, $stringfilemap);
891b798d
DM
478 }
479
480 exit 0;
e143e9d8
DM
481}
482
4831;