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.dat";
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)) {
42 open(my $fh, '<', $pve_api_definition_fn) ||
43 die "unable to open '$pve_api_definition_fn' - $!\n";
44 $pve_api_definition = Storable
::fd_retrieve
($fh);
45 $build_pve_api_path_hash->($pve_api_definition);
48 return $pve_api_definition;
51 sub lookup_api_method
{
52 my ($path, $method, $noerr) = @_;
54 get_api_definition
(); # make sure API data is loaded
56 my $info = $pve_api_path_hash->{$path};
59 return undef if $noerr;
60 die "unable to find API info for path '$path'\n";
63 my $data = $info->{info
}->{$method};
66 return undef if $noerr;
67 die "unable to find API method '$method' for path '$path'\n";
73 sub complete_api_call_options
{
74 my ($cmd, $prop, $prev, $cur, $args) = @_;
76 my $print_result = sub {
78 print "$p\n" if $p =~ m/^$cur/;
82 my $print_parameter_completion = sub {
84 my $d = $prop->{$pname};
85 if ($d->{completion
}) {
86 my $vt = ref($d->{completion
});
88 my $res = $d->{completion
}->($cmd, $pname, $cur, $args);
89 &$print_result(@$res);
91 } elsif ($d->{type
} eq 'boolean') {
92 &$print_result('0', '1');
93 } elsif ($d->{enum
}) {
94 &$print_result(@{$d->{enum
}});
99 foreach my $key (keys %$prop) {
100 push @option_list, "--$key";
104 &$print_result(@option_list);
108 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
110 &$print_parameter_completion($pname);
114 &$print_result(@option_list);
117 sub complete_api_path
{
120 get_api_definition
(); # make sure API data is loaded
124 my ($dir, $rest) = $text =~ m
|^(?
:(.*)/)?(?:([^/]*))?
$|;
127 if (!defined($dir)) {
129 $info = { children
=> $pve_api_definition };
131 $info = $pve_api_path_hash->{"/$dir"};
135 if (my $children = $info->{children
}) {
136 foreach my $c (@$children) {
137 if ($c->{path
} =~ m!\Q$dir/$rest!) {
138 print "$c->{path}\n";
139 print "$c->{path}/\n"if $c->{children
};