Skip to content

Commit

Permalink
Merge pull request #1796 from wxiaoguang/fix-nil-flag-v3
Browse files Browse the repository at this point in the history
 Fix nil HelpFlag panic (v3)
  • Loading branch information
dearchap authored Jul 23, 2023
2 parents bafe0ce + d6b81bb commit 7b25ef5
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
4 changes: 4 additions & 0 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,10 @@ func (cmd *Command) Run(ctx context.Context, osArgs []string) (deferErr error) {
func (cmd *Command) checkHelp() bool {
tracef("checking if help is wanted (cmd=%[1]q)", cmd.Name)

if HelpFlag == nil {
return false
}

for _, name := range HelpFlag.Names() {
if cmd.Bool(name) {
return true
Expand Down
18 changes: 18 additions & 0 deletions help_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,24 @@ func Test_Help_Custom_Flags(t *testing.T) {
require.Len(t, out.String(), 0)
}

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

cmd := &Command{
Action: func(_ context.Context, cmd *Command) error {
return nil
},
}
out := new(bytes.Buffer)
cmd.Writer = out
_ = cmd.Run(buildTestContext(t), []string{"test"})
require.Len(t, out.String(), 0)
}

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 @@ -31,7 +31,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 7b25ef5

Please sign in to comment.