Skip to content

Commit

Permalink
Flow context to command in SetHelpFunc (#2241)
Browse files Browse the repository at this point in the history
Fixes #2240
  • Loading branch information
Frassle authored Feb 21, 2025
1 parent f98cf42 commit 1995054
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
5 changes: 5 additions & 0 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
31 changes: 31 additions & 0 deletions command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit 1995054

Please sign in to comment.