From b7ae6498423f4831af1de9d3b90809dca7e055f0 Mon Sep 17 00:00:00 2001 From: Sergey Kamardin Date: Sun, 6 Sep 2020 18:30:09 +0300 Subject: [PATCH] parse/pargs: do not guess on boolean flags with values --- parse/pargs/posix.go | 13 +++++++++++ parse/pargs/posix_test.go | 45 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 55 insertions(+), 3 deletions(-) diff --git a/parse/pargs/posix.go b/parse/pargs/posix.go index c93b51e..2626868 100644 --- a/parse/pargs/posix.go +++ b/parse/pargs/posix.go @@ -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++ } diff --git a/parse/pargs/posix_test.go b/parse/pargs/posix_test.go index d1055cc..1685409 100644 --- a/parse/pargs/posix_test.go +++ b/parse/pargs/posix_test.go @@ -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, @@ -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{