1 package PVE
::APIClient
::Helpers
;
8 use PVE
::APIClient
::Exception
qw(raise);
11 use HTTP
::Status
qw(:constants);
13 my $pve_api_definition;
14 my $pve_api_path_hash;
16 my $pve_api_definition_fn = "/usr/share/pve-client/pve-api-definition.js";
18 my $build_pve_api_path_hash;
19 $build_pve_api_path_hash = sub {
22 my $class = ref($tree);
23 return $tree if !$class;
25 if ($class eq 'ARRAY') {
26 foreach my $el (@$tree) {
27 $build_pve_api_path_hash->($el);
29 } elsif ($class eq 'HASH') {
30 if (defined($tree->{leaf
}) && defined(my $path = $tree->{path
})) {
31 $pve_api_path_hash->{$path} = $tree;
33 foreach my $k (keys %$tree) {
34 $build_pve_api_path_hash->($tree->{$k});
39 sub get_api_definition
{
41 if (!defined($pve_api_definition)) {
43 open(my $fh, '<', $pve_api_definition_fn) ||
44 die "unable to open '$pve_api_definition_fn' - $!\n";
45 my $json_text = <$fh>;
46 $pve_api_definition = decode_json
($json_text);
48 $build_pve_api_path_hash->($pve_api_definition);
52 return $pve_api_definition;
55 sub lookup_api_method
{
56 my ($path, $method, $noerr) = @_;
58 get_api_definition
(); # make sure API data is loaded
60 my $info = $pve_api_path_hash->{$path};
63 return undef if $noerr;
64 die "unable to find API info for path '$path'\n";
67 my $data = $info->{info
}->{$method};
70 return undef if $noerr;
71 die "unable to find API method '$method' for path '$path'\n";
77 sub complete_api_call_options
{
78 my ($cmd, $prop, $prev, $cur, $args) = @_;
80 my $print_result = sub {
82 print "$p\n" if $p =~ m/^$cur/;
86 my $print_parameter_completion = sub {
88 my $d = $prop->{$pname};
89 if ($d->{completion
}) {
90 my $vt = ref($d->{completion
});
92 my $res = $d->{completion
}->($cmd, $pname, $cur, $args);
93 &$print_result(@$res);
95 } elsif ($d->{type
} eq 'boolean') {
96 &$print_result('0', '1');
97 } elsif ($d->{enum
}) {
98 &$print_result(@{$d->{enum
}});
102 my @option_list = ();
103 foreach my $key (keys %$prop) {
104 push @option_list, "--$key";
108 &$print_result(@option_list);
112 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
114 &$print_parameter_completion($pname);
118 &$print_result(@option_list);
121 sub complete_api_path
{
124 get_api_definition
(); # make sure API data is loaded
128 my ($dir, $rest) = $text =~ m
|^(?
:(.*)/)?(?:([^/]*))?
$|;
131 if (!defined($dir)) {
133 $info = { children
=> $pve_api_definition };
135 $info = $pve_api_path_hash->{"/$dir"};
139 if (my $children = $info->{children
}) {
140 foreach my $c (@$children) {
141 if ($c->{path
} =~ m!\Q$dir/$rest!) {
142 print "$c->{path}\n";
143 print "$c->{path}/\n"if $c->{children
};