Skip to content

Commit

Permalink
parse/pargs: do not guess on boolean flags with values
Browse files Browse the repository at this point in the history
  • Loading branch information
gobwas committed Sep 6, 2020
1 parent 2857826 commit b7ae649
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 3 deletions.
13 changes: 13 additions & 0 deletions parse/pargs/posix.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,19 @@ func (p *Parser) next() bool {
if !hasValue && p.pos < len(p.Args) {
value = p.Args[p.pos]
if len(value) > 0 && value[0] != '-' {
if p.isBoolFlag(name) {
dash := "--"
if short {
dash = "-"
}
p.fail(""+
"ambiguous boolean flag %[1]s%[2]s value: can't guess whether "+
"the %[3]q is the flag value or the non-flag argument "+
"(consider using `%[1]s%[2]s=%[3]s` or `%[1]s%[2]s -- %[3]s`)",
dash, name, value,
)
return false
}
hasValue = true
p.pos++
}
Expand Down
45 changes: 42 additions & 3 deletions parse/pargs/posix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,10 @@ func TestPosixParse(t *testing.T) {
},
},
{
name: "booleans",
name: "short booleans",
args: []string{
"-t", "true",
"-f", "false",
"-t=true",
"-f=false",
},
flags: map[string]bool{
"t": true,
Expand All @@ -88,6 +88,45 @@ func TestPosixParse(t *testing.T) {
{"f", "false"},
},
},
{
name: "short ambiguous booleans",
args: []string{
"-t", "true",
"-f", "false",
},
flags: map[string]bool{
"t": true,
"f": true,
},
err: true,
},
{
name: "long booleans",
args: []string{
"--foo=true",
"--bar=false",
},
flags: map[string]bool{
"foo": true,
"bar": true,
},
expPairs: [][2]string{
{"foo", "true"},
{"bar", "false"},
},
},
{
name: "long ambiguous booleans",
args: []string{
"--foo", "true",
"--bar", "false",
},
flags: map[string]bool{
"foo": true,
"bar": true,
},
err: true,
},
{
name: "non-boolean without argument",
args: []string{
Expand Down

0 comments on commit b7ae649

Please sign in to comment.