1
0
Fork 0
mirror of https://github.com/spf13/cobra synced 2025-04-01 04:19:15 +00:00

Flow context to command in SetHelpFunc ()

Fixes https://github.com/spf13/cobra/issues/2240
This commit is contained in:
Fraser Waters 2025-02-21 12:46:14 +00:00 committed by GitHub
parent f98cf4216d
commit 1995054b00
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 36 additions and 0 deletions

View file

@ -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())

View file

@ -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)
}