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