Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add cobra cmd to context #9

Merged
merged 6 commits into from
Dec 20, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
8 changes: 7 additions & 1 deletion decorators.go
Original file line number Diff line number Diff line change
Expand Up @@ -621,6 +621,8 @@ type CommandWithExecute interface {
// CommandWithExecuteDecorator is a decorator that sets the command execution.
type CommandWithExecuteDecorator struct{}

type CobraCtxCmd struct{}
raulb marked this conversation as resolved.
Show resolved Hide resolved

// Decorate sets the command execution.
func (CommandWithExecuteDecorator) Decorate(_ *Ecdysis, cmd *cobra.Command, c Command) error {
v, ok := c.(CommandWithExecute)
Expand All @@ -636,7 +638,11 @@ func (CommandWithExecuteDecorator) Decorate(_ *Ecdysis, cmd *cobra.Command, c Co
return err
}
}
return v.Execute(cmd.Context())

// Provide the cobra command to the context.
// This is useful for situations such as wanting to execute cmd.Help() directly from Execute().
ctx := context.WithValue(cmd.Context(), CobraCtxCmd{}, cmd)
return v.Execute(ctx)
}

return nil
Expand Down
3 changes: 2 additions & 1 deletion ecdysis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ func TestBuildCobraCommand_Behavioral(t *testing.T) {
ctx := context.Background()
ctrl := gomock.NewController(t)
cmd := NewMockBehavioralTestCommand(ctrl)
ctx = context.WithValue(ctx, CobraCtxCmd{}, cmd)

wantLogger := slog.New(slog.NewTextHandler(nil, nil))
ecdysis := New(WithDecorators(CommandWithLoggerDecorator{Logger: wantLogger}))
Expand All @@ -124,7 +125,7 @@ func TestBuildCobraCommand_Behavioral(t *testing.T) {

// Set up the remaining expectations before executing the command.
call = cmd.EXPECT().Args(gomock.Any()).Return(nil).After(call)
cmd.EXPECT().Execute(ctx).Return(nil).After(call)
cmd.EXPECT().Execute(gomock.AssignableToTypeOf(ctx)).Return(nil).After(call)

err := got.ExecuteContext(ctx)
if err != nil {
Expand Down
Loading