]> git.proxmox.com Git - pve-common.git/blame - src/PVE/CLIHandler.pm
cli: refactor print_bash_completion
[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 16
d204696c
TL
17my $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
918140af
TL
23my $abort = sub {
24 my ($reason, $cmd) = @_;
25 print_usage_short (\*STDERR, $reason, $cmd);
26 exit (-1);
27};
28
e143e9d8
DM
29my $expand_command_name = sub {
30 my ($def, $cmd) = @_;
31
32 if (!$def->{$cmd}) {
7bac844e
TL
33 my @expanded = grep { /^\Q$cmd\E/ } keys %$def;
34 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
e143e9d8
DM
35 }
36 return $cmd;
37};
38
edf3d572 39my $complete_command_names = sub {
7bac844e 40 return [ sort keys %$cmddef ];
edf3d572
DM
41};
42
e143e9d8 43__PACKAGE__->register_method ({
3ef20687 44 name => 'help',
e143e9d8
DM
45 path => 'help',
46 method => 'GET',
47 description => "Get help about specified command.",
48 parameters => {
3ef20687 49 additionalProperties => 0,
e143e9d8
DM
50 properties => {
51 cmd => {
52 description => "Command name",
53 type => 'string',
54 optional => 1,
edf3d572 55 completion => $complete_command_names,
e143e9d8
DM
56 },
57 verbose => {
58 description => "Verbose output format.",
59 type => 'boolean',
60 optional => 1,
61 },
62 },
63 },
64 returns => { type => 'null' },
3ef20687 65
e143e9d8
DM
66 code => sub {
67 my ($param) = @_;
68
d204696c 69 $assert_initialized->();
e143e9d8
DM
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();
3ef20687 79 } else {
e143e9d8
DM
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
891b798d 91 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 92 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
e143e9d8 93
891b798d 94 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param,
4845032a
FG
95 $verbose ? 'full' : 'short', $pwcallback,
96 $stringfilemap);
e143e9d8
DM
97 if ($verbose) {
98 print "$str\n";
99 } else {
100 print "USAGE: $str\n";
101 }
102
103 return undef;
104
105 }});
106
0a5a1eee 107sub print_simple_asciidoc_synopsis {
fe3f1fde
DM
108 my ($class, $name, $arg_param, $uri_param) = @_;
109
d204696c 110 $assert_initialized->();
fe3f1fde
DM
111
112 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 113 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
fe3f1fde
DM
114
115 my $synopsis = "*${name}* `help`\n\n";
116
4845032a
FG
117 $synopsis .= $class->usage_str($name, $name, $arg_param, $uri_param,
118 'asciidoc', $pwcallback, $stringfilemap);
fe3f1fde
DM
119
120 return $synopsis;
121}
122
0a5a1eee 123sub print_asciidoc_synopsis {
fe3f1fde 124
d204696c 125 $assert_initialized->();
fe3f1fde
DM
126
127 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 128 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
fe3f1fde
DM
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,
4845032a
FG
138 $uri_param, 'asciidoc', $pwcallback,
139 $stringfilemap);
fe3f1fde
DM
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
e143e9d8
DM
151sub print_usage_verbose {
152
d204696c 153 $assert_initialized->();
891b798d
DM
154
155 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 156 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
e143e9d8
DM
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}};
891b798d 162 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param,
4845032a 163 'full', $pwcallback, $stringfilemap);
e143e9d8
DM
164 print "$str\n\n";
165 }
166}
167
168sub sorted_commands {
169 return sort { ($cmddef->{$a}->[0] cmp $cmddef->{$b}->[0]) || ($a cmp $b)} keys %$cmddef;
170}
171
172sub print_usage_short {
173 my ($fd, $msg) = @_;
174
d204696c 175 $assert_initialized->();
891b798d
DM
176
177 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 178 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
e143e9d8
DM
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}};
4845032a 186 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param, 'short', $pwcallback, $stringfilemap);
e143e9d8
DM
187 print $fd "\n" if $oldclass && $oldclass ne $class;
188 print $fd " $str";
189 $oldclass = $class;
190 }
191}
192
d8053c08 193my $print_bash_completion = sub {
57e67ea3 194 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
d8053c08
DM
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
58d9e664 205 my $args = PVE::Tools::split_args($cmdline);
5fa768fc 206 shift @$args; # no need for program name
d8053c08
DM
207 my $print_result = sub {
208 foreach my $p (@_) {
209 print "$p\n" if $p =~ m/^$cur/;
210 }
211 };
212
5fa768fc
TL
213 my ($cmd, $def) = ($simple_cmd, $cmddef);
214 if (!$simple_cmd) {
215 if (!scalar(@$args)) {
216 &$print_result(keys %$def);
d8053c08
DM
217 return;
218 }
5fa768fc 219 $cmd = $args->[0];
d8053c08 220 }
5fa768fc 221 $def = $def->{$cmd};
d8053c08
DM
222 return if !$def;
223
5fa768fc
TL
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;
d8053c08
DM
228
229 my $skip_param = {};
230
231 my ($class, $name, $arg_param, $uri_param) = @$def;
232 $arg_param //= [];
233 $uri_param //= {};
234
d90a2fd0
DM
235 $arg_param = [ $arg_param ] if !ref($arg_param);
236
d8053c08
DM
237 map { $skip_param->{$_} = 1; } @$arg_param;
238 map { $skip_param->{$_} = 1; } keys %$uri_param;
239
d8053c08
DM
240 my $info = $class->map_method_by_name($name);
241
5fa768fc 242 my $prop = $info->{parameters}->{properties};
d8053c08
DM
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') {
58d9e664 250 my $res = $d->{completion}->($cmd, $pname, $cur, $args);
d8053c08
DM
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
5fa768fc
TL
261 $pos++ if $simple_cmd;
262 if ($pos < scalar(@$arg_param)) {
263 my $pname = $arg_param->[$pos];
d8053c08
DM
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
1f130ba6
DM
288sub verify_api {
289 my ($class) = @_;
290
291 # simply verify all registered methods
292 PVE::RESTHandler::validate_method_schemas();
293}
294
8f3712f8
DM
295my $get_exe_name = sub {
296 my ($class) = @_;
3ef20687 297
8f3712f8
DM
298 my $name = $class;
299 $name =~ s/^.*:://;
300 $name =~ s/_/-/g;
301
302 return $name;
303};
304
c45707a0
DM
305sub generate_bash_completions {
306 my ($class) = @_;
307
308 # generate bash completion config
309
8f3712f8 310 $exename = &$get_exe_name($class);
c45707a0
DM
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
318COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
319
e4a1d8e2 320complete -o default -C '$exename bashcomplete' $exename
c45707a0
DM
321__EOD__
322}
323
fe3f1fde
DM
324sub generate_asciidoc_synopsys {
325 my ($class) = @_;
0a5a1eee
FG
326 $class->generate_asciidoc_synopsis();
327};
328
329sub generate_asciidoc_synopsis {
330 my ($class) = @_;
fe3f1fde
DM
331
332 $cli_handler_class = $class;
333
334 $exename = &$get_exe_name($class);
335
336 no strict 'refs';
337 my $def = ${"${class}::cmddef"};
57e67ea3 338 $cmddef = $def;
fe3f1fde
DM
339
340 if (ref($def) eq 'ARRAY') {
0a5a1eee 341 print_simple_asciidoc_synopsis(@$def);
fe3f1fde 342 } else {
fe3f1fde
DM
343 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
344
0a5a1eee 345 print_asciidoc_synopsis();
fe3f1fde
DM
346 }
347}
348
7b7f99c9
DM
349# overwrite this if you want to run/setup things early
350sub setup_environment {
351 my ($class) = @_;
352
353 # do nothing by default
354}
355
891b798d 356my $handle_cmd = sub {
57e67ea3 357 my ($args, $pwcallback, $preparefunc, $stringfilemap) = @_;
e143e9d8
DM
358
359 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
360
7b7f99c9 361
57e67ea3 362 my $cmd = shift @$args;
918140af
TL
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') {
e143e9d8
DM
368 PVE::RESTHandler::validate_method_schemas();
369 return;
7b7f99c9
DM
370 }
371
372 $cli_handler_class->setup_environment();
373
374 if ($cmd eq 'bashcomplete') {
57e67ea3 375 &$print_bash_completion(undef, @$args);
d8053c08 376 return;
e143e9d8
DM
377 }
378
8e3e9929
WB
379 &$preparefunc() if $preparefunc;
380
e143e9d8
DM
381 $cmd = &$expand_command_name($cmddef, $cmd);
382
383 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef->{$cmd} || []};
918140af 384 $abort->("unknown command '$cmd'") if !$class;
e143e9d8
DM
385
386 my $prefix = "$exename $cmd";
408976c6 387 my $res = $class->cli_handler($prefix, $name, \@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
2026f4b5
DM
388
389 &$outsub($res) if $outsub;
891b798d 390};
2026f4b5 391
891b798d 392my $handle_simple_cmd = sub {
57e67ea3 393 my ($args, $pwcallback, $preparefunc, $stringfilemap) = @_;
2026f4b5 394
57e67ea3 395 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
2026f4b5
DM
396 die "no class specified" if !$class;
397
d8053c08 398 if (scalar(@$args) >= 1) {
2026f4b5
DM
399 if ($args->[0] eq 'help') {
400 my $str = "USAGE: $name help\n";
4845032a 401 $str .= $class->usage_str($name, $name, $arg_param, $uri_param, 'long', $pwcallback, $stringfilemap);
2026f4b5
DM
402 print STDERR "$str\n\n";
403 return;
404 } elsif ($args->[0] eq 'verifyapi') {
405 PVE::RESTHandler::validate_method_schemas();
406 return;
2026f4b5 407 }
e143e9d8 408 }
2026f4b5 409
7b7f99c9
DM
410 $cli_handler_class->setup_environment();
411
412 if (scalar(@$args) >= 1) {
413 if ($args->[0] eq 'bashcomplete') {
414 shift @$args;
57e67ea3 415 &$print_bash_completion($name, @$args);
7b7f99c9
DM
416 return;
417 }
418 }
419
7fe1f565
DM
420 &$preparefunc() if $preparefunc;
421
408976c6 422 my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
2026f4b5
DM
423
424 &$outsub($res) if $outsub;
891b798d
DM
425};
426
891b798d
DM
427sub run_cli_handler {
428 my ($class, %params) = @_;
429
430 $cli_handler_class = $class;
431
432 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
433
aa9b9af5 434 foreach my $key (keys %params) {
5ae87c41 435 next if $key eq 'prepare';
1042b82c
DM
436 next if $key eq 'no_init'; # not used anymore
437 next if $key eq 'no_rpcenv'; # not used anymore
aa9b9af5
DM
438 die "unknown parameter '$key'";
439 }
440
5ae87c41 441 my $preparefunc = $params{prepare};
891b798d
DM
442
443 my $pwcallback = $class->can('read_password');
408976c6 444 my $stringfilemap = $class->can('string_param_file_mapping');
891b798d
DM
445
446 $exename = &$get_exe_name($class);
447
448 initlog($exename);
449
891b798d 450 no strict 'refs';
57e67ea3 451 $cmddef = ${"${class}::cmddef"};
891b798d 452
57e67ea3
TL
453 if (ref($cmddef) eq 'ARRAY') {
454 &$handle_simple_cmd(\@ARGV, $pwcallback, $preparefunc, $stringfilemap);
891b798d 455 } else {
57e67ea3 456 &$handle_cmd(\@ARGV, $pwcallback, $preparefunc, $stringfilemap);
891b798d
DM
457 }
458
459 exit 0;
e143e9d8
DM
460}
461
4621;