Skip to content

Commit

Permalink
Flow context to command in SetHelpFunc
Browse files Browse the repository at this point in the history
Fixes #2240
  • Loading branch information
Frassle committed Feb 20, 2025
1 parent f98cf42 commit 5c63ef0
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
3 changes: 3 additions & 0 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -1296,6 +1296,9 @@ Simply type ` + c.DisplayName() + ` help [path to command] for full details.`,
c.Printf("Unknown help topic %#q\n", args)
CheckErr(c.Root().Usage())
} else {
// FLow the context down to be used in help text
cmd.ctx = c.ctx

cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown
cmd.InitDefaultVersionFlag() // make possible 'version' flag to be shown
CheckErr(cmd.Help())
Expand Down
26 changes: 26 additions & 0 deletions command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2921,3 +2921,29 @@ func TestUnknownFlagShouldReturnSameErrorRegardlessOfArgPosition(t *testing.T) {
})
}
}

func TestHelpFuncExecuted(t *testing.T) {
helpExecuted := false

child := &Command{Use: "child", Long: "Long description", Run: emptyRun}
child.SetHelpFunc(func(cmd *Command, args []string) {
helpExecuted = true

if cmd.Context() == nil {
t.Error("Context is nil")
}
})

rootCmd := &Command{Use: "root", Run: emptyRun}
rootCmd.AddCommand(child)

output, err := executeCommand(rootCmd, "help", "child")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}

checkStringContains(t, output, rootCmd.Long)
if !helpExecuted {
t.Error("Help function not executed")
}
}

0 comments on commit 5c63ef0

Please sign in to comment.