mirror of
https://github.com/spf13/cobra
synced 2025-04-01 04:19:15 +00:00
Flow context to command in SetHelpFunc (#2241)
Fixes https://github.com/spf13/cobra/issues/2240
This commit is contained in:
parent
f98cf4216d
commit
1995054b00
2 changed files with 36 additions and 0 deletions
|
@ -1296,6 +1296,11 @@ 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
|
||||
if cmd.ctx == nil {
|
||||
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())
|
||||
|
|
|
@ -2921,3 +2921,34 @@ func TestUnknownFlagShouldReturnSameErrorRegardlessOfArgPosition(t *testing.T) {
|
|||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHelpFuncExecuted(t *testing.T) {
|
||||
helpText := "Long description"
|
||||
|
||||
// Create a context that will be unique, not just the background context
|
||||
//nolint:golint,staticcheck // We can safely use a basic type as key in tests.
|
||||
executionCtx := context.WithValue(context.Background(), "testKey", "123")
|
||||
|
||||
child := &Command{Use: "child", Run: emptyRun}
|
||||
child.SetHelpFunc(func(cmd *Command, args []string) {
|
||||
_, err := cmd.OutOrStdout().Write([]byte(helpText))
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
// Test for https://github.com/spf13/cobra/issues/2240
|
||||
if cmd.Context() != executionCtx {
|
||||
t.Error("Context doesn't equal the execution context")
|
||||
}
|
||||
})
|
||||
|
||||
rootCmd := &Command{Use: "root", Run: emptyRun}
|
||||
rootCmd.AddCommand(child)
|
||||
|
||||
output, err := executeCommandWithContext(executionCtx, rootCmd, "help", "child")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
checkStringContains(t, output, helpText)
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue