Skip to content

Commit

Permalink
make x.Parsed() return true after AddGoFlagSet(x) and pflag.Parse() (#…
Browse files Browse the repository at this point in the history
…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
  • Loading branch information
childe authored and eparis committed Apr 3, 2018
1 parent 1cd4a0c commit 1ce0cc6
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
8 changes: 8 additions & 0 deletions flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ package pflag
import (
"bytes"
"errors"
goflag "flag"
"fmt"
"io"
"os"
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand Down
4 changes: 4 additions & 0 deletions golangflag.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
8 changes: 8 additions & 0 deletions golangflag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}

0 comments on commit 1ce0cc6

Please sign in to comment.