Added ability to specify true/false for bool opts
License: MIT Signed-off-by: ForrestWeston <Forrest.Weston@gmail.com>
ForrestWeston committed
Oct 9, 2015 at 17:29 UTC
107409cee80562b57637a00e1bf72e5bffc24680
2 files changed
+33
-10
commands/cli/parse.go
+20
-5
@@ -85,13 +85,28 @@ func parseOpts(args []string, root *cmds.Command) (
85
err = fmt.Errorf("Unrecognized option '%s'", name)
86
return false, err
87
}
88
-
88
+ // mustUse implies that you must use the argument given after the '='
89
+ // eg. -r=true means you must take true into consideration
90
+ // mustUse == true in the above case
91
+ // eg. ipfs -r <file> means disregard <file> since there is no '='
92
+ // mustUse == false in the above situation
93
+ //arg == nil implies the flag was specified without an argument
94
if optDef.Type() == cmds.Bool {
90
- if mustUse {
91
- return false, fmt.Errorf("Option '%s' takes no arguments, but was passed '%s'", name, *arg)
95
+ if arg == nil || !mustUse {
96
+ opts[name] = true
97
+ return false, nil
98
+ }
99
+ argVal := strings.ToLower(*arg)
100
+ switch argVal {
101
+ case "true":
102
+ opts[name] = true
103
+ return true, nil
104
+ case "false":
105
+ opts[name] = false
106
+ return true, nil
107
+ default:
108
+ return true, fmt.Errorf("Option '%s' takes true/false arguments, but was passed '%s'", name, argVal)
109
}
93
- opts[name] = ""
94
- return false, nil
110
} else {
111
if arg == nil {
112
return true, fmt.Errorf("Missing argument for option '%s'", name)
commands/cli/parse_test.go
+13
-5
@@ -106,17 +106,25 @@ func TestOptionParsing(t *testing.T) {
106
test("-s foo", kvs{"s": "foo"}, words{})
107
test("-sfoo", kvs{"s": "foo"}, words{})
108
test("-s=foo", kvs{"s": "foo"}, words{})
109
- test("-b", kvs{"b": ""}, words{})
110
- test("-bs foo", kvs{"b": "", "s": "foo"}, words{})
109
+ test("-b", kvs{"b": true}, words{})
110
+ test("-bs foo", kvs{"b": true, "s": "foo"}, words{})
111
test("-sb", kvs{"s": "b"}, words{})
112
- test("-b foo", kvs{"b": ""}, words{"foo"})
113
- test("--bool foo", kvs{"bool": ""}, words{"foo"})
112
+ test("-b foo", kvs{"b": true}, words{"foo"})
113
+ test("--bool foo", kvs{"bool": true}, words{"foo"})
114
testFail("--bool=foo")
115
testFail("--string")
116
test("--string foo", kvs{"string": "foo"}, words{})
117
test("--string=foo", kvs{"string": "foo"}, words{})
118
test("-- -b", kvs{}, words{"-b"})
119
- test("foo -b", kvs{"b": ""}, words{"foo"})
119
+ test("foo -b", kvs{"b": true}, words{"foo"})
120
+ test("-b=false", kvs{"b": false}, words{})
121
+ test("-b=true", kvs{"b": true}, words{})
122
+ test("-b=false foo", kvs{"b": false}, words{"foo"})
123
+ test("-b=true foo", kvs{"b": true}, words{"foo"})
124
+ test("--bool=true foo", kvs{"bool": true}, words{"foo"})
125
+ test("--bool=false foo", kvs{"bool": false}, words{"foo"})
126
+ test("-b=FaLsE foo", kvs{"b": false}, words{"foo"})
127
+ test("-b=TrUe foo", kvs{"b": true}, words{"foo"})
128
}
129
130
func TestArgumentParsing(t *testing.T) {