Merge pull request #112 from GeertJohan/master
Deny an option (or something that looks like an option) as flag argument.
diff --git a/parser_private.go b/parser_private.go
index 67a5b02..c0811fc 100644
--- a/parser_private.go
+++ b/parser_private.go
@@ -171,6 +171,10 @@
arg = *argument
} else {
arg = s.pop()
+ if argumentIsOption(arg) {
+ msg := fmt.Sprintf("expected argument for flag `%s', but got option `%s'", option, arg)
+ return newError(ErrExpectedArgument, msg)
+ }
}
if option.tag.Get("unquote") != "false" {
diff --git a/parser_test.go b/parser_test.go
index ea5006e..30ecb5e 100644
--- a/parser_test.go
+++ b/parser_test.go
@@ -305,3 +305,43 @@
}
}
}
+
+func TestOptionAsArgument(t *testing.T) {
+ var tests = []struct {
+ args []string
+ expectError bool
+ errType ErrorType
+ errMsg string
+ }{
+ {
+ // short option must not be accepted as argument
+ args: []string{"--string-slice", "foobar", "--string-slice", "-o"},
+ expectError: true,
+ errType: ErrExpectedArgument,
+ errMsg: "expected argument for flag `--string-slice', but got option `-o'",
+ },
+ {
+ // long option must not be accepted as argument
+ args: []string{"--string-slice", "foobar", "--string-slice", "--other-option"},
+ expectError: true,
+ errType: ErrExpectedArgument,
+ errMsg: "expected argument for flag `--string-slice', but got option `--other-option'",
+ },
+ {
+ // quoted and appended option should be accepted as argument (even if it looks like an option)
+ args: []string{"--string-slice", "foobar", "--string-slice=\"--other-option\""},
+ },
+ }
+ var opts struct {
+ StringSlice []string `long:"string-slice"`
+ OtherOption bool `long:"other-option" short:"o"`
+ }
+
+ for _, test := range tests {
+ if test.expectError {
+ assertParseFail(t, test.errType, test.errMsg, &opts, test.args...)
+ } else {
+ assertParseSuccess(t, &opts, test.args...)
+ }
+ }
+}