]> git.proxmox.com Git - pve-common.git/blob - src/PVE/CLIHandler.pm
CLIHandler: add helper to generate bash completion config
[pve-common.git] / src / PVE / CLIHandler.pm
1 package PVE::CLIHandler;
2
3 use strict;
4 use warnings;
5 use Data::Dumper;
6
7 use PVE::SafeSyslog;
8 use PVE::Exception qw(raise raise_param_exc);
9 use PVE::RESTHandler;
10 use PVE::PodParser;
11
12 use base qw(PVE::RESTHandler);
13
14 my $cmddef;
15 my $exename;
16
17 my $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
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 },
50 verbose => {
51 description => "Verbose output format.",
52 type => 'boolean',
53 optional => 1,
54 },
55 },
56 },
57 returns => { type => 'null' },
58
59 code => sub {
60 my ($param) = @_;
61
62 die "not initialized" if !($cmddef && $exename);
63
64 my $cmd = $param->{cmd};
65
66 my $verbose = defined($cmd) && $cmd;
67 $verbose = $param->{verbose} if defined($param->{verbose});
68
69 if (!$cmd) {
70 if ($verbose) {
71 print_usage_verbose();
72 } else {
73 print_usage_short(\*STDOUT);
74 }
75 return undef;
76 }
77
78 $cmd = &$expand_command_name($cmddef, $cmd);
79
80 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd} || []};
81
82 raise_param_exc({ cmd => "no such command '$cmd'"}) if !$class;
83
84
85 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param, $verbose ? 'full' : 'short');
86 if ($verbose) {
87 print "$str\n";
88 } else {
89 print "USAGE: $str\n";
90 }
91
92 return undef;
93
94 }});
95
96 sub print_pod_manpage {
97 my ($podfn) = @_;
98
99 die "not initialized" if !($cmddef && $exename);
100 die "no pod file specified" if !$podfn;
101
102 my $synopsis = "";
103
104 $synopsis .= " $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
105
106 my $style = 'full'; # or should we use 'short'?
107 my $oldclass;
108 foreach my $cmd (sorted_commands()) {
109 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
110 my $str = $class->usage_str($name, "$exename $cmd", $arg_param,
111 $uri_param, $style);
112 $str =~ s/^USAGE: //;
113
114 $synopsis .= "\n" if $oldclass && $oldclass ne $class;
115 $str =~ s/\n/\n /g;
116 $synopsis .= " $str\n\n";
117 $oldclass = $class;
118 }
119
120 $synopsis .= "\n";
121
122 my $parser = PVE::PodParser->new();
123 $parser->{include}->{synopsis} = $synopsis;
124 $parser->parse_from_file($podfn);
125 }
126
127 sub print_usage_verbose {
128
129 die "not initialized" if !($cmddef && $exename);
130
131 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
132
133 foreach my $cmd (sort keys %$cmddef) {
134 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
135 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param, 'full');
136 print "$str\n\n";
137 }
138 }
139
140 sub sorted_commands {
141 return sort { ($cmddef->{$a}->[0] cmp $cmddef->{$b}->[0]) || ($a cmp $b)} keys %$cmddef;
142 }
143
144 sub print_usage_short {
145 my ($fd, $msg) = @_;
146
147 die "not initialized" if !($cmddef && $exename);
148
149 print $fd "ERROR: $msg\n" if $msg;
150 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
151
152 my $oldclass;
153 foreach my $cmd (sorted_commands()) {
154 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
155 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param, 'short');
156 print $fd "\n" if $oldclass && $oldclass ne $class;
157 print $fd " $str";
158 $oldclass = $class;
159 }
160 }
161
162 my $print_bash_completion = sub {
163 my ($cmddef, $simple_cmd, $bash_command, $cur, $prev) = @_;
164
165 my $debug = 0;
166
167 return if !(defined($cur) && defined($prev) && defined($bash_command));
168 return if !defined($ENV{COMP_LINE});
169 return if !defined($ENV{COMP_POINT});
170
171 my $cmdline = substr($ENV{COMP_LINE}, 0, $ENV{COMP_POINT});
172 print STDERR "\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
173
174 # fixme: shell quoting??
175 my @args = split(/\s+/, $cmdline);
176 my $pos = scalar(@args) - 2;
177 $pos += 1 if $cmdline =~ m/\s+$/;
178
179 print STDERR "CMDLINE:$pos:$cmdline\n" if $debug;
180
181 return if $pos < 0;
182
183 my $print_result = sub {
184 foreach my $p (@_) {
185 print "$p\n" if $p =~ m/^$cur/;
186 }
187 };
188
189 my $cmd;
190 if ($simple_cmd) {
191 $cmd = $simple_cmd;
192 } else {
193 if ($pos == 0) {
194 &$print_result(keys %$cmddef);
195 return;
196 }
197 $cmd = $args[1];
198 }
199
200 my $def = $cmddef->{$cmd};
201 return if !$def;
202
203 print STDERR "CMDLINE1:$pos:$cmdline\n" if $debug;
204
205 my $skip_param = {};
206
207 my ($class, $name, $arg_param, $uri_param) = @$def;
208 $arg_param //= [];
209 $uri_param //= {};
210
211 map { $skip_param->{$_} = 1; } @$arg_param;
212 map { $skip_param->{$_} = 1; } keys %$uri_param;
213
214 my $fpcount = scalar(@$arg_param);
215
216 my $info = $class->map_method_by_name($name);
217
218 my $schema = $info->{parameters};
219 my $prop = $schema->{properties};
220
221 my $print_parameter_completion = sub {
222 my ($pname) = @_;
223 my $d = $prop->{$pname};
224 if ($d->{completion}) {
225 my $vt = ref($d->{completion});
226 if ($vt eq 'CODE') {
227 my $res = $d->{completion}->($cmd, $pname, $cur);
228 &$print_result(@$res);
229 }
230 } elsif ($d->{type} eq 'boolean') {
231 &$print_result('0', '1');
232 } elsif ($d->{enum}) {
233 &$print_result(@{$d->{enum}});
234 }
235 };
236
237 # positional arguments
238 $pos += 1 if $simple_cmd;
239 if ($fpcount && $pos <= $fpcount) {
240 my $pname = $arg_param->[$pos -1];
241 &$print_parameter_completion($pname);
242 return;
243 }
244
245 my @option_list = ();
246 foreach my $key (keys %$prop) {
247 next if $skip_param->{$key};
248 push @option_list, "--$key";
249 }
250
251 if ($cur =~ m/^-/) {
252 &$print_result(@option_list);
253 return;
254 }
255
256 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
257 my $pname = $1;
258 &$print_parameter_completion($pname);
259 return;
260 }
261
262 &$print_result(@option_list);
263 };
264
265 sub verify_api {
266 my ($class) = @_;
267
268 # simply verify all registered methods
269 PVE::RESTHandler::validate_method_schemas();
270 }
271
272 sub generate_bash_completions {
273 my ($class) = @_;
274
275 # generate bash completion config
276
277 $exename = $class;
278 $exename =~ s/^.*:://;
279
280 print <<__EOD__;
281 # $exename bash completion
282
283 # see http://tiswww.case.edu/php/chet/bash/FAQ
284 # and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
285 # this modifies global var, but I found no better way
286 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
287
288 complete -C '$exename bashcomplete' $exename
289 __EOD__
290 }
291
292 sub generate_pod_manpage {
293 my ($class, $podfn) = @_;
294
295 no strict 'refs';
296 $cmddef = ${"${class}::cmddef"};
297
298 $exename = $class;
299 $exename =~ s/^.*:://;
300
301 if (!defined($podfn)) {
302 my $cpath = "$class.pm";
303 $cpath =~ s/::/\//g;
304 foreach my $p (@INC) {
305 my $testfn = "$p/$cpath";
306 if (-f $testfn) {
307 $podfn = $testfn;
308 last;
309 }
310 }
311 }
312
313 die "unable to find source for class '$class'" if !$podfn;
314
315 print_pod_manpage($podfn);
316 }
317
318 sub run {
319 my ($class, $pwcallback, $preparefunc) = @_;
320
321 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
322
323 no strict 'refs';
324 $cmddef = ${"${class}::cmddef"};
325
326 $exename = $class;
327 $exename =~ s/^.*:://;
328
329 initlog($exename);
330
331 die "please run as root\n" if $> != 0;
332
333 PVE::INotify::inotify_init();
334
335 my $rpcenv = PVE::RPCEnvironment->init('cli');
336 $rpcenv->init_request();
337 $rpcenv->set_language($ENV{LANG});
338 $rpcenv->set_user('root@pam');
339
340 my $cmd = shift @ARGV;
341
342 handle_cmd($cmddef, $exename, $cmd, \@ARGV, $pwcallback, $0, $preparefunc);
343
344 exit 0;
345 }
346
347 sub handle_cmd {
348 my ($def, $cmdname, $cmd, $args, $pwcallback, $podfn, $preparefunc) = @_;
349
350 $cmddef = $def;
351 $exename = $cmdname;
352
353 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
354
355 if (!$cmd) {
356 print_usage_short (\*STDERR, "no command specified");
357 exit (-1);
358 } elsif ($cmd eq 'verifyapi') {
359 PVE::RESTHandler::validate_method_schemas();
360 return;
361 } elsif ($cmd eq 'printmanpod') {
362 print_pod_manpage($podfn);
363 return;
364 } elsif ($cmd eq 'bashcomplete') {
365 &$print_bash_completion($cmddef, 0, @$args);
366 return;
367 }
368
369 &$preparefunc() if $preparefunc;
370
371 $cmd = &$expand_command_name($cmddef, $cmd);
372
373 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef->{$cmd} || []};
374
375 if (!$class) {
376 print_usage_short (\*STDERR, "unknown command '$cmd'");
377 exit (-1);
378 }
379
380 my $prefix = "$exename $cmd";
381 my $res = $class->cli_handler($prefix, $name, \@ARGV, $arg_param, $uri_param, $pwcallback);
382
383 &$outsub($res) if $outsub;
384 }
385
386 sub handle_simple_cmd {
387 my ($def, $args, $pwcallback, $podfn) = @_;
388
389 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def};
390 die "no class specified" if !$class;
391
392 if (scalar(@$args) >= 1) {
393 if ($args->[0] eq 'help') {
394 my $str = "USAGE: $name help\n";
395 $str .= $class->usage_str($name, $name, $arg_param, $uri_param, 'long');
396 print STDERR "$str\n\n";
397 return;
398 } elsif ($args->[0] eq 'bashcomplete') {
399 shift @$args;
400 &$print_bash_completion({ $name => $def }, $name, @$args);
401 return;
402 } elsif ($args->[0] eq 'verifyapi') {
403 PVE::RESTHandler::validate_method_schemas();
404 return;
405 } elsif ($args->[0] eq 'printmanpod') {
406 my $synopsis = " $name help\n\n";
407 my $str = $class->usage_str($name, $name, $arg_param, $uri_param, 'long');
408 $str =~ s/^USAGE://;
409 $str =~ s/\n/\n /g;
410 $synopsis .= $str;
411
412 my $parser = PVE::PodParser->new();
413 $parser->{include}->{synopsis} = $synopsis;
414 $parser->parse_from_file($podfn);
415 return;
416 }
417 }
418
419 my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $pwcallback);
420
421 &$outsub($res) if $outsub;
422 }
423
424 1;