Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
Loading