Skip to content

Commit 1995054

Browse files
authored
Flow context to command in SetHelpFunc (#2241)
Fixes #2240
1 parent f98cf42 commit 1995054

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

command.go

+5
Original file line numberDiff line numberDiff line change
@@ -1296,6 +1296,11 @@ Simply type ` + c.DisplayName() + ` help [path to command] for full details.`,
12961296
c.Printf("Unknown help topic %#q\n", args)
12971297
CheckErr(c.Root().Usage())
12981298
} else {
1299+
// FLow the context down to be used in help text
1300+
if cmd.ctx == nil {
1301+
cmd.ctx = c.ctx
1302+
}
1303+
12991304
cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown
13001305
cmd.InitDefaultVersionFlag() // make possible 'version' flag to be shown
13011306
CheckErr(cmd.Help())

command_test.go

+31
Original file line numberDiff line numberDiff line change
@@ -2921,3 +2921,34 @@ func TestUnknownFlagShouldReturnSameErrorRegardlessOfArgPosition(t *testing.T) {
29212921
})
29222922
}
29232923
}
2924+
2925+
func TestHelpFuncExecuted(t *testing.T) {
2926+
helpText := "Long description"
2927+
2928+
// Create a context that will be unique, not just the background context
2929+
//nolint:golint,staticcheck // We can safely use a basic type as key in tests.
2930+
executionCtx := context.WithValue(context.Background(), "testKey", "123")
2931+
2932+
child := &Command{Use: "child", Run: emptyRun}
2933+
child.SetHelpFunc(func(cmd *Command, args []string) {
2934+
_, err := cmd.OutOrStdout().Write([]byte(helpText))
2935+
if err != nil {
2936+
t.Error(err)
2937+
}
2938+
2939+
// Test for https://github.com/spf13/cobra/issues/2240
2940+
if cmd.Context() != executionCtx {
2941+
t.Error("Context doesn't equal the execution context")
2942+
}
2943+
})
2944+
2945+
rootCmd := &Command{Use: "root", Run: emptyRun}
2946+
rootCmd.AddCommand(child)
2947+
2948+
output, err := executeCommandWithContext(executionCtx, rootCmd, "help", "child")
2949+
if err != nil {
2950+
t.Errorf("Unexpected error: %v", err)
2951+
}
2952+
2953+
checkStringContains(t, output, helpText)
2954+
}

0 commit comments

Comments
 (0)