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