From f21662750abbd76e54f307765b0986b357ed8b92 Mon Sep 17 00:00:00 2001 From: fabianofranz Date: Wed, 22 Apr 2015 14:20:17 -0300 Subject: Add support to short form with equal sign: -p=value --- flag.go | 17 +++++++++-------- flag_test.go | 11 ++++++++--- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/flag.go b/flag.go index 5dc5373..c43edad 100644 --- a/flag.go +++ b/flag.go @@ -141,12 +141,12 @@ type FlagSet struct { // A Flag represents the state of a flag. type Flag struct { - Name string // name as it appears on command line - Shorthand string // one-letter abbreviated flag - Usage string // help message - Value Value // value as set - DefValue string // default value (as text); for usage message - Changed bool // If the user set the value (or if left to default) + Name string // name as it appears on command line + Shorthand string // one-letter abbreviated flag + Usage string // help message + Value Value // value as set + DefValue string // default value (as text); for usage message + Changed bool // If the user set the value (or if left to default) Annotations map[string][]string // used by cobra.Command bash autocomple code } @@ -507,7 +507,8 @@ func (f *FlagSet) parseShortArg(s string, args []string) (a []string, err error) continue } if i < len(shorthands)-1 { - if e := f.setFlag(flag, shorthands[i+1:], s); e != nil { + v := strings.TrimPrefix(shorthands[i+1:], "=") + if e := f.setFlag(flag, v, s); e != nil { err = e return } @@ -554,7 +555,7 @@ func (f *FlagSet) parseArgs(args []string) (err error) { args, err = f.parseShortArg(s, args) } if err != nil { - return + return } } return diff --git a/flag_test.go b/flag_test.go index a33c601..d6aa308 100644 --- a/flag_test.go +++ b/flag_test.go @@ -185,7 +185,8 @@ func TestShorthand(t *testing.T) { boolaFlag := f.BoolP("boola", "a", false, "bool value") boolbFlag := f.BoolP("boolb", "b", false, "bool2 value") boolcFlag := f.BoolP("boolc", "c", false, "bool3 value") - stringFlag := f.StringP("string", "s", "0", "string value") + stringaFlag := f.StringP("stringa", "s", "0", "string value") + stringzFlag := f.StringP("stringz", "z", "0", "string value") extra := "interspersed-argument" notaflag := "--i-look-like-a-flag" args := []string{ @@ -193,6 +194,7 @@ func TestShorthand(t *testing.T) { extra, "-cs", "hello", + "-z=something", "--", notaflag, } @@ -212,8 +214,11 @@ func TestShorthand(t *testing.T) { if *boolcFlag != true { t.Error("boolc flag should be true, is ", *boolcFlag) } - if *stringFlag != "hello" { - t.Error("string flag should be `hello`, is ", *stringFlag) + if *stringaFlag != "hello" { + t.Error("stringa flag should be `hello`, is ", *stringaFlag) + } + if *stringzFlag != "something" { + t.Error("stringz flag should be `something`, is ", *stringzFlag) } if len(f.Args()) != 2 { t.Error("expected one argument, got", len(f.Args())) -- cgit v1.2.3