Allow passing negative number to a signed number option
Fixes #190.
diff --git a/option.go b/option.go
index 3635df3..934ea72 100644
--- a/option.go
+++ b/option.go
@@ -336,14 +336,27 @@
for {
switch tp.Kind() {
+ case reflect.Slice, reflect.Ptr:
+ tp = tp.Elem()
case reflect.Bool:
return true
- case reflect.Slice:
- return (tp.Elem().Kind() == reflect.Bool)
case reflect.Func:
return tp.NumIn() == 0
- case reflect.Ptr:
+ default:
+ return false
+ }
+ }
+}
+
+func (option *Option) isSignedNumber() bool {
+ tp := option.value.Type()
+
+ for {
+ switch tp.Kind() {
+ case reflect.Slice, reflect.Ptr:
tp = tp.Elem()
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Float32, reflect.Float64:
+ return true
default:
return false
}
diff --git a/parser.go b/parser.go
index 6477daa..3a55626 100644
--- a/parser.go
+++ b/parser.go
@@ -514,7 +514,7 @@
} else {
arg = s.pop()
- if argumentIsOption(arg) {
+ if argumentIsOption(arg) && !(option.isSignedNumber() && len(arg) > 1 && arg[0] == '-' && arg[1] >= '0' && arg[1] <= '9') {
return newErrorf(ErrExpectedArgument, "expected argument for flag `%s', but got option `%s'", option, arg)
} else if p.Options&PassDoubleDash != 0 && arg == "--" {
return newErrorf(ErrExpectedArgument, "expected argument for flag `%s', but got double dash `--'", option)
diff --git a/parser_test.go b/parser_test.go
index 9f527b7..374f21c 100644
--- a/parser_test.go
+++ b/parser_test.go
@@ -398,9 +398,30 @@
args: []string{"-o", "-", "-"},
rest: []string{"-", "-"},
},
+ {
+ // Accept arguments which start with '-' if the next character is a digit, for number options only
+ args: []string{"--int-slice", "-3"},
+ },
+ {
+ // Accept arguments which start with '-' if the next character is a digit, for number options only
+ args: []string{"--int16", "-3"},
+ },
+ {
+ // Accept arguments which start with '-' if the next character is a digit, for number options only
+ args: []string{"--float32", "-3.2"},
+ },
+ {
+ // Accept arguments which start with '-' if the next character is a digit, for number options only
+ args: []string{"--float32ptr", "-3.2"},
+ },
}
+
var opts struct {
StringSlice []string `long:"string-slice"`
+ IntSlice []int `long:"int-slice"`
+ Int16 int16 `long:"int16"`
+ Float32 float32 `long:"float32"`
+ Float32Ptr *float32 `long:"float32ptr"`
OtherOption bool `long:"other-option" short:"o"`
}