Skip to content
Myr

Flow context to command in SetHelpFunc (#2241)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Fixes https://github.com/spf13/cobra/issues/2240

authored by Fraser Waters · committed by GitHub · parent f98cf42 · Browse files · 2 files+36 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+36 added−0 removed

  • other:+36 added−0 removed

2 files+36 added−0 removed

modified:command_test.go+31 added
2919 unmodified lines
2920 checkStringContains(t, output, "unknown flag: --unknown")2921 })2922 }2923}29242925func TestHelpFuncExecuted(t *testing.T) {2926 helpText := "Long description"29272928 // Create a context that will be unique, not just the background context2929 //nolint:golint,staticcheck // We can safely use a basic type as key in tests.2930 executionCtx := context.WithValue(context.Background(), "testKey", "123")29312932 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 }29382939 // Test for https://github.com/spf13/cobra/issues/22402940 if cmd.Context() != executionCtx {2941 t.Error("Context doesn't equal the execution context")2942 }2943 })29442945 rootCmd := &Command{Use: "root", Run: emptyRun}2946 rootCmd.AddCommand(child)29472948 output, err := executeCommandWithContext(executionCtx, rootCmd, "help", "child")2949 if err != nil {2950 t.Errorf("Unexpected error: %v", err)2951 }29522953 checkStringContains(t, output, helpText)2954}
modified:command.go+5 added
1294 unmodified lines
1295 if cmd == nil || e != nil {1296 c.Printf("Unknown help topic %#q\n", args)1297 CheckErr(c.Root().Usage())1298 } else {1299 // FLow the context down to be used in help text1300 if cmd.ctx == nil {1301 cmd.ctx = c.ctx1302 }13031304 cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown1305 cmd.InitDefaultVersionFlag() // make possible 'version' flag to be shown1306 CheckErr(cmd.Help())1307 }
765 unmodified lines