aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorchilde <[email protected]>2018-04-03 19:55:18 +0800
committerEric Paris <[email protected]>2018-04-03 07:55:18 -0400
commit1ce0cc6db4029d97571db82f85092fccedb572ce (patch)
tree8c833fbe5daaefd3898388d4a979a696d151302d
parent1cd4a0c365d95803411bec89fb7b76bade17053b (diff)
make x.Parsed() return true after AddGoFlagSet(x) and pflag.Parse() (#162)
* make GoFlagSets.Parsed() true after pflag.Parse some third part lib such as glog use go flag package, and its some actions depends on if goflag.Parsed(). * add test case for goflag.CommandLine.Parsed() * add comment to goflag.CommandLine.Parsed test case
-rw-r--r--flag.go8
-rw-r--r--golangflag.go4
-rw-r--r--golangflag_test.go8
3 files changed, 20 insertions, 0 deletions
diff --git a/flag.go b/flag.go
index f0acbb8..e4e0c94 100644
--- a/flag.go
+++ b/flag.go
@@ -101,6 +101,7 @@ package pflag
import (
"bytes"
"errors"
+ goflag "flag"
"fmt"
"io"
"os"
@@ -162,6 +163,8 @@ type FlagSet struct {
output io.Writer // nil means stderr; use out() accessor
interspersed bool // allow interspersed option/non-option args
normalizeNameFunc func(f *FlagSet, name string) NormalizedName
+
+ addedGoFlagSets []*goflag.FlagSet
}
// A Flag represents the state of a flag.
@@ -1098,6 +1101,11 @@ func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) {
// are defined and before flags are accessed by the program.
// The return value will be ErrHelp if -help was set but not defined.
func (f *FlagSet) Parse(arguments []string) error {
+ if f.addedGoFlagSets != nil {
+ for _, goFlagSet := range f.addedGoFlagSets {
+ goFlagSet.Parse(nil)
+ }
+ }
f.parsed = true
if len(arguments) < 0 {
diff --git a/golangflag.go b/golangflag.go
index c4f47eb..d3dd72b 100644
--- a/golangflag.go
+++ b/golangflag.go
@@ -98,4 +98,8 @@ func (f *FlagSet) AddGoFlagSet(newSet *goflag.FlagSet) {
newSet.VisitAll(func(goflag *goflag.Flag) {
f.AddGoFlag(goflag)
})
+ if f.addedGoFlagSets == nil {
+ f.addedGoFlagSets = make([]*goflag.FlagSet, 0)
+ }
+ f.addedGoFlagSets = append(f.addedGoFlagSets, newSet)
}
diff --git a/golangflag_test.go b/golangflag_test.go
index 77e2d7d..5bd831b 100644
--- a/golangflag_test.go
+++ b/golangflag_test.go
@@ -36,4 +36,12 @@ func TestGoflags(t *testing.T) {
if getBool != true {
t.Fatalf("expected getBool=true but got getBool=%v", getBool)
}
+ if !f.Parsed() {
+ t.Fatal("f.Parsed() return false after f.Parse() called")
+ }
+
+ // in fact it is useless. because `go test` called flag.Parse()
+ if !goflag.CommandLine.Parsed() {
+ t.Fatal("goflag.CommandLine.Parsed() return false after f.Parse() called")
+ }
}