remove + from getopt's prefix_pattern
[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::Exception qw(raise raise_param_exc);
8 use PVE::RESTHandler;
9 use PVE::PodParser;
10
11 use base qw(PVE::RESTHandler);
12
13 my $cmddef;
14 my $exename;
15
16 my $expand_command_name = sub {
17 my ($def, $cmd) = @_;
18
19 if (!$def->{$cmd}) {
20 my $expanded;
21 for my $k (keys(%$def)) {
22 if ($k =~ m/^$cmd/) {
23 if ($expanded) {
24 $expanded = undef; # more than one match
25 last;
26 } else {
27 $expanded = $k;
28 }
29 }
30 }
31 $cmd = $expanded if $expanded;
32 }
33 return $cmd;
34 };
35
36 __PACKAGE__->register_method ({
37 name => 'help',
38 path => 'help',
39 method => 'GET',
40 description => "Get help about specified command.",
41 parameters => {
42 additionalProperties => 0,
43 properties => {
44 cmd => {
45 description => "Command name",
46 type => 'string',
47 optional => 1,
48 },
49 verbose => {
50 description => "Verbose output format.",
51 type => 'boolean',
52 optional => 1,
53 },
54 },
55 },
56 returns => { type => 'null' },
57
58 code => sub {
59 my ($param) = @_;
60
61 die "not initialized" if !($cmddef && $exename);
62
63 my $cmd = $param->{cmd};
64
65 my $verbose = defined($cmd) && $cmd;
66 $verbose = $param->{verbose} if defined($param->{verbose});
67
68 if (!$cmd) {
69 if ($verbose) {
70 print_usage_verbose();
71 } else {
72 print_usage_short(\*STDOUT);
73 }
74 return undef;
75 }
76
77 $cmd = &$expand_command_name($cmddef, $cmd);
78
79 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd} || []};
80
81 raise_param_exc({ cmd => "no such command '$cmd'"}) if !$class;
82
83
84 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param, $verbose ? 'full' : 'short');
85 if ($verbose) {
86 print "$str\n";
87 } else {
88 print "USAGE: $str\n";
89 }
90
91 return undef;
92
93 }});
94
95 sub print_pod_manpage {
96 my ($podfn) = @_;
97
98 die "not initialized" if !($cmddef && $exename);
99 die "no pod file specified" if !$podfn;
100
101 my $synopsis = "";
102
103 $synopsis .= " $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
104
105 my $style = 'full'; # or should we use 'short'?
106 my $oldclass;
107 foreach my $cmd (sorted_commands()) {
108 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
109 my $str = $class->usage_str($name, "$exename $cmd", $arg_param,
110 $uri_param, $style);
111 $str =~ s/^USAGE: //;
112
113 $synopsis .= "\n" if $oldclass && $oldclass ne $class;
114 $str =~ s/\n/\n /g;
115 $synopsis .= " $str\n\n";
116 $oldclass = $class;
117 }
118
119 $synopsis .= "\n";
120
121 my $parser = PVE::PodParser->new();
122 $parser->{include}->{synopsis} = $synopsis;
123 $parser->parse_from_file($podfn);
124 }
125
126 sub print_usage_verbose {
127
128 die "not initialized" if !($cmddef && $exename);
129
130 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
131
132 foreach my $cmd (sort keys %$cmddef) {
133 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
134 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param, 'full');
135 print "$str\n\n";
136 }
137 }
138
139 sub sorted_commands {
140 return sort { ($cmddef->{$a}->[0] cmp $cmddef->{$b}->[0]) || ($a cmp $b)} keys %$cmddef;
141 }
142
143 sub print_usage_short {
144 my ($fd, $msg) = @_;
145
146 die "not initialized" if !($cmddef && $exename);
147
148 print $fd "ERROR: $msg\n" if $msg;
149 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
150
151 my $oldclass;
152 foreach my $cmd (sorted_commands()) {
153 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
154 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param, 'short');
155 print $fd "\n" if $oldclass && $oldclass ne $class;
156 print $fd " $str";
157 $oldclass = $class;
158 }
159 }
160
161 my $print_bash_completion = sub {
162 my ($cmddef, $simple_cmd, $bash_command, $cur, $prev) = @_;
163
164 my $debug = 0;
165
166 return if !(defined($cur) && defined($prev) && defined($bash_command));
167 return if !defined($ENV{COMP_LINE});
168 return if !defined($ENV{COMP_POINT});
169
170 my $cmdline = substr($ENV{COMP_LINE}, 0, $ENV{COMP_POINT});
171 print STDERR "\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
172
173 # fixme: shell quoting??
174 my @args = split(/\s+/, $cmdline);
175 my $pos = scalar(@args) - 2;
176 $pos += 1 if $cmdline =~ m/\s+$/;
177
178 print STDERR "CMDLINE:$pos:$cmdline\n" if $debug;
179
180 return if $pos < 0;
181
182 my $print_result = sub {
183 foreach my $p (@_) {
184 print "$p\n" if $p =~ m/^$cur/;
185 }
186 };
187
188 my $cmd;
189 if ($simple_cmd) {
190 $cmd = $simple_cmd;
191 } else {
192 if ($pos == 0) {
193 &$print_result(keys %$cmddef);
194 return;
195 }
196 $cmd = $args[1];
197 }
198
199 my $def = $cmddef->{$cmd};
200 return if !$def;
201
202 print STDERR "CMDLINE1:$pos:$cmdline\n" if $debug;
203
204 my $skip_param = {};
205
206 my ($class, $name, $arg_param, $uri_param) = @$def;
207 $arg_param //= [];
208 $uri_param //= {};
209
210 map { $skip_param->{$_} = 1; } @$arg_param;
211 map { $skip_param->{$_} = 1; } keys %$uri_param;
212
213 my $fpcount = scalar(@$arg_param);
214
215 my $info = $class->map_method_by_name($name);
216
217 my $schema = $info->{parameters};
218 my $prop = $schema->{properties};
219
220 my $print_parameter_completion = sub {
221 my ($pname) = @_;
222 my $d = $prop->{$pname};
223 if ($d->{completion}) {
224 my $vt = ref($d->{completion});
225 if ($vt eq 'CODE') {
226 my $res = $d->{completion}->($cmd, $pname, $cur);
227 &$print_result(@$res);
228 }
229 } elsif ($d->{type} eq 'boolean') {
230 &$print_result('0', '1');
231 } elsif ($d->{enum}) {
232 &$print_result(@{$d->{enum}});
233 }
234 };
235
236 # positional arguments
237 $pos += 1 if $simple_cmd;
238 if ($fpcount && $pos <= $fpcount) {
239 my $pname = $arg_param->[$pos -1];
240 &$print_parameter_completion($pname);
241 return;
242 }
243
244 my @option_list = ();
245 foreach my $key (keys %$prop) {
246 next if $skip_param->{$key};
247 push @option_list, "--$key";
248 }
249
250 if ($cur =~ m/^-/) {
251 &$print_result(@option_list);
252 return;
253 }
254
255 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
256 my $pname = $1;
257 &$print_parameter_completion($pname);
258 return;
259 }
260
261 &$print_result(@option_list);
262 };
263
264 sub handle_cmd {
265 my ($def, $cmdname, $cmd, $args, $pwcallback, $podfn, $preparefunc) = @_;
266
267 $cmddef = $def;
268 $exename = $cmdname;
269
270 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
271
272 if (!$cmd) {
273 print_usage_short (\*STDERR, "no command specified");
274 exit (-1);
275 } elsif ($cmd eq 'verifyapi') {
276 PVE::RESTHandler::validate_method_schemas();
277 return;
278 } elsif ($cmd eq 'printmanpod') {
279 print_pod_manpage($podfn);
280 return;
281 } elsif ($cmd eq 'bashcomplete') {
282 &$print_bash_completion($cmddef, 0, @$args);
283 return;
284 }
285
286 &$preparefunc() if $preparefunc;
287
288 $cmd = &$expand_command_name($cmddef, $cmd);
289
290 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef->{$cmd} || []};
291
292 if (!$class) {
293 print_usage_short (\*STDERR, "unknown command '$cmd'");
294 exit (-1);
295 }
296
297 my $prefix = "$exename $cmd";
298 my $res = $class->cli_handler($prefix, $name, \@ARGV, $arg_param, $uri_param, $pwcallback);
299
300 &$outsub($res) if $outsub;
301 }
302
303 sub handle_simple_cmd {
304 my ($def, $args, $pwcallback, $podfn) = @_;
305
306 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def};
307 die "no class specified" if !$class;
308
309 if (scalar(@$args) >= 1) {
310 if ($args->[0] eq 'help') {
311 my $str = "USAGE: $name help\n";
312 $str .= $class->usage_str($name, $name, $arg_param, $uri_param, 'long');
313 print STDERR "$str\n\n";
314 return;
315 } elsif ($args->[0] eq 'bashcomplete') {
316 shift @$args;
317 &$print_bash_completion({ $name => $def }, $name, @$args);
318 return;
319 } elsif ($args->[0] eq 'verifyapi') {
320 PVE::RESTHandler::validate_method_schemas();
321 return;
322 } elsif ($args->[0] eq 'printmanpod') {
323 my $synopsis = " $name help\n\n";
324 my $str = $class->usage_str($name, $name, $arg_param, $uri_param, 'long');
325 $str =~ s/^USAGE://;
326 $str =~ s/\n/\n /g;
327 $synopsis .= $str;
328
329 my $parser = PVE::PodParser->new();
330 $parser->{include}->{synopsis} = $synopsis;
331 $parser->parse_from_file($podfn);
332 return;
333 }
334 }
335
336 my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $pwcallback);
337
338 &$outsub($res) if $outsub;
339 }
340
341 1;