aboutsummaryrefslogtreecommitdiff
path: root/flag.go
diff options
context:
space:
mode:
authorEric Paris <[email protected]>2015-05-08 11:39:59 -0400
committerEric Paris <[email protected]>2015-05-08 11:41:55 -0400
commitea5408381a3a773ae7f9b671e19e72eadf76af31 (patch)
tree5fab6c78a0ef92702f632c3eca63a712592bc70a /flag.go
parent1bfac8f0cd77d2a18baf33d904b3ea0e6ea821f5 (diff)
Rewrite short arg parsing for readability
new function to parse each arg (less indentation) make it clear what value is being set and where it came from
Diffstat (limited to 'flag.go')
-rw-r--r--flag.go74
1 files changed, 36 insertions, 38 deletions
diff --git a/flag.go b/flag.go
index 4b96126..23ef501 100644
--- a/flag.go
+++ b/flag.go
@@ -536,50 +536,48 @@ func (f *FlagSet) parseLongArg(s string, args []string) (a []string, err error)
return
}
+func (f *FlagSet) parseSingleShortArg(shorthands string, args []string) (outShorts string, outArgs []string, err error) {
+ outArgs = args
+ outShorts = shorthands[1:]
+ c := shorthands[0]
+
+ flag, alreadythere := f.shorthands[c]
+ if !alreadythere {
+ if c == 'h' { // special case for nice help message.
+ f.usage()
+ err = ErrHelp
+ return
+ }
+ //TODO continue on error
+ err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands)
+ return
+ }
+ var value string
+ if bv, ok := flag.Value.(boolFlag); ok && bv.IsBoolFlag() {
+ value = "true"
+ } else if len(shorthands) > 1 {
+ value = strings.TrimPrefix(shorthands[1:], "=")
+ outShorts = ""
+ } else if len(args) > 0 {
+ value = args[0]
+ outArgs = args[1:]
+ } else {
+ err = f.failf("flag needs an argument: %q in -%s", c, shorthands)
+ return
+ }
+ err = f.setFlag(flag, value, shorthands)
+ return
+}
+
func (f *FlagSet) parseShortArg(s string, args []string) (a []string, err error) {
a = args
shorthands := s[1:]
- for i := 0; i < len(shorthands); i++ {
- c := shorthands[i]
- flag, alreadythere := f.shorthands[c]
- if !alreadythere {
- if c == 'h' { // special case for nice help message.
- f.usage()
- err = ErrHelp
- return
- }
- //TODO continue on error
- err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands)
- if len(args) == 0 {
- return
- }
+ for len(shorthands) > 0 {
+ shorthands, a, err = f.parseSingleShortArg(shorthands, args)
+ if err != nil {
return
}
- if alreadythere {
- if bv, ok := flag.Value.(boolFlag); ok && bv.IsBoolFlag() {
- f.setFlag(flag, "true", s)
- continue
- }
- if i < len(shorthands)-1 {
- v := strings.TrimPrefix(shorthands[i+1:], "=")
- if e := f.setFlag(flag, v, s); e != nil {
- err = e
- return
- }
- break
- }
- if len(args) == 0 {
- err = f.failf("flag needs an argument: %q in -%s", c, shorthands)
- return
- }
- if e := f.setFlag(flag, args[0], s); e != nil {
- err = e
- return
- }
- }
- a = args[1:]
- break // should be unnecessary
}
return