Skip to content

Commit

Permalink
Merge pull request #1561 from dearchap/ext_global_flags_optional
Browse files Browse the repository at this point in the history
FIx: Allow ext flags to be opt-out by default rather than opt-in
  • Loading branch information
dearchap committed Nov 2, 2022
2 parents ae8d932 + fb3a9ce commit c3fccc0
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 7 deletions.
19 changes: 12 additions & 7 deletions app.go
Expand Up @@ -113,6 +113,9 @@ type App struct {
UseShortOptionHandling bool
// Enable suggestions for commands and flags
Suggest bool
// Allows global flags set by libraries which use flag.XXXVar(...) directly
// to be parsed through this library
AllowExtFlags bool

didSetup bool

Expand Down Expand Up @@ -199,13 +202,15 @@ func (a *App) Setup() {
a.ErrWriter = os.Stderr
}

// add global flags added by other packages
flag.VisitAll(func(f *flag.Flag) {
// skip test flags
if !strings.HasPrefix(f.Name, ignoreFlagPrefix) {
a.Flags = append(a.Flags, &extFlag{f})
}
})
if a.AllowExtFlags {
// add global flags added by other packages
flag.VisitAll(func(f *flag.Flag) {
// skip test flags
if !strings.HasPrefix(f.Name, ignoreFlagPrefix) {
a.Flags = append(a.Flags, &extFlag{f})
}
})
}

var newCommands []*Command

Expand Down
23 changes: 23 additions & 0 deletions app_test.go
Expand Up @@ -654,6 +654,7 @@ func TestApp_FlagsFromExtPackage(t *testing.T) {
}()

a := &App{
AllowExtFlags: true,
Flags: []Flag{
&StringFlag{
Name: "carly",
Expand All @@ -677,6 +678,28 @@ func TestApp_FlagsFromExtPackage(t *testing.T) {
if someint != 10 {
t.Errorf("Expected 10 got %d for someint", someint)
}

a = &App{
Flags: []Flag{
&StringFlag{
Name: "carly",
Aliases: []string{"c"},
Required: false,
},
&BoolFlag{
Name: "jimbob",
Aliases: []string{"j"},
Required: false,
Value: true,
},
},
}

// this should return an error since epflag shouldnt be registered
err = a.Run([]string{"foo", "-c", "cly", "--epflag", "10"})
if err == nil {
t.Error("Expected error")
}
}

func TestApp_Setup_defaultsReader(t *testing.T) {
Expand Down
3 changes: 3 additions & 0 deletions godoc-current.txt
Expand Up @@ -324,6 +324,9 @@ type App struct {
UseShortOptionHandling bool
// Enable suggestions for commands and flags
Suggest bool
// Allows global flags set by libraries which use flag.XXXVar(...) directly
// to be parsed through this library
AllowExtFlags bool

// Has unexported fields.
}
Expand Down
3 changes: 3 additions & 0 deletions testdata/godoc-v2.x.txt
Expand Up @@ -324,6 +324,9 @@ type App struct {
UseShortOptionHandling bool
// Enable suggestions for commands and flags
Suggest bool
// Allows global flags set by libraries which use flag.XXXVar(...) directly
// to be parsed through this library
AllowExtFlags bool

// Has unexported fields.
}
Expand Down

0 comments on commit c3fccc0

Please sign in to comment.