[pve-devel] [PATCH common] schema/cli: allow hyphens for underscores in CLI options

Wolfgang Bumiller w.bumiller at proxmox.com
Tue Sep 26 10:02:10 CEST 2017


---
Underscores in command line options are stupid. Even more than the
inconsistency we have there.

And since many of them come from the API backend, changing them breaks
stuff (deprecating+aliasing them would work, though, but that's much
more work as well...)

Next step, make the man page generator replace underscores in options.

 src/PVE/JSONSchema.pm | 33 +++++++++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)

diff --git a/src/PVE/JSONSchema.pm b/src/PVE/JSONSchema.pm
index 3295599..642f918 100644
--- a/src/PVE/JSONSchema.pm
+++ b/src/PVE/JSONSchema.pm
@@ -1283,6 +1283,37 @@ sub method_get_child_link {
     return $found;
 }
 
+sub add_hyphenized_options {
+    my ($options) = @_;
+    my $hyphenized_opts = {};
+    my @new_opts;
+    foreach my $opt (@$options) {
+	my ($name, $type) = ($opt =~ /^([^:=]+)([:=].*)?$/);
+	my $hyphenized = ($name =~ s/_/-/gr);
+	if ($hyphenized ne $name) {
+	    # If your parameters define both --foo-bar as well as --foo_bar
+	    # you're doing it wrong...
+	    die "conflicting options: '$name' and '$hyphenized'\n"
+		if exists $hyphenized_opts->{$hyphenized};
+	    push @new_opts, $hyphenized.$type;
+	    $hyphenized_opts->{$hyphenized} = $name;
+	}
+    }
+    push @$options, @new_opts;
+    return $hyphenized_opts;
+}
+
+sub resolve_hyphenized_options {
+    my ($hyphenized, $options) = @_;
+    # Sort so that eg. `pvesm set foo --is-mountpoint X --is_mountpoint Y`
+    # doesn't decide at random whether X or Y ends up in the config...
+    foreach my $opt (sort keys %$options) {
+	if (defined(my $regular = $hyphenized->{$opt})) {
+	    $options->{$regular} = delete $options->{$opt};
+	}
+    }
+}
+
 # a way to parse command line parameters, using a 
 # schema to configure Getopt::Long
 sub get_options {
@@ -1327,8 +1358,10 @@ sub get_options {
     Getopt::Long::Configure('prefix_pattern=(--|-)');
 
     my $opts = {};
+    my $hyphenized = add_hyphenized_options(\@getopt);
     raise("unable to parse option\n", code => HTTP_BAD_REQUEST)
 	if !Getopt::Long::GetOptionsFromArray($args, $opts, @getopt);
+    resolve_hyphenized_options($hyphenized, $opts);
 
     if (@$args) {
 	if ($list_param) {
-- 
2.11.0





More information about the pve-devel mailing list