Skip to content

Commit

Permalink
Merge pull request #1795 from wxiaoguang/fix-nil-flag
Browse files Browse the repository at this point in the history
Fix nil HelpFlag panic (v2)
  • Loading branch information
dearchap committed Jul 23, 2023
2 parents 2f36a1f + 09c4e07 commit 0eaf592
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 19 deletions.
21 changes: 3 additions & 18 deletions help.go
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,9 @@ func checkVersion(cCtx *Context) bool {
}

func checkHelp(cCtx *Context) bool {
if HelpFlag == nil {
return false
}
found := false
for _, name := range HelpFlag.Names() {
if cCtx.Bool(name) {
Expand All @@ -426,24 +429,6 @@ func checkHelp(cCtx *Context) bool {
return found
}

func checkCommandHelp(c *Context, name string) bool {
if c.Bool("h") || c.Bool("help") {
_ = ShowCommandHelp(c, name)
return true
}

return false
}

func checkSubcommandHelp(cCtx *Context) bool {
if cCtx.Bool("h") || cCtx.Bool("help") {
_ = ShowSubcommandHelp(cCtx)
return true
}

return false
}

func checkShellCompleteFlag(a *App, arguments []string) (bool, []string) {
if !a.EnableBashCompletion {
return false, arguments
Expand Down
20 changes: 20 additions & 0 deletions help_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,26 @@ func Test_Help_Custom_Flags(t *testing.T) {
}
}

func Test_Help_Nil_Flags(t *testing.T) {
oldFlag := HelpFlag
defer func() {
HelpFlag = oldFlag
}()
HelpFlag = nil

app := App{
Action: func(context *Context) error {
return nil
},
}
output := new(bytes.Buffer)
app.Writer = output
_ = app.Run([]string{"test"})
if output.Len() > 0 {
t.Errorf("unexpected output: %s", output.String())
}
}

func Test_Version_Custom_Flags(t *testing.T) {
oldFlag := VersionFlag
defer func() {
Expand Down
2 changes: 1 addition & 1 deletion suggestions.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func suggestFlag(flags []Flag, provided string, hideHelp bool) string {

for _, flag := range flags {
flagNames := flag.Names()
if !hideHelp {
if !hideHelp && HelpFlag != nil {
flagNames = append(flagNames, HelpFlag.Names()...)
}
for _, name := range flagNames {
Expand Down

0 comments on commit 0eaf592

Please sign in to comment.