Skip to content

Commit

Permalink
chore(cmdx): do not run commands in the background when not needed (#794
Browse files Browse the repository at this point in the history
)

to preserve the call stack properly
  • Loading branch information
zepatrik authored Jul 5, 2024
1 parent 46c2f21 commit 3f26104
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions cmdx/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,7 @@ func (c *CallbackWriter) String() string {

var _ io.Writer = (*CallbackWriter)(nil)

// ExecBackgroundCtx runs the cobra command in the background.
func ExecBackgroundCtx(ctx context.Context, cmd *cobra.Command, stdIn io.Reader, stdOut, stdErr io.Writer, args ...string) *errgroup.Group {
func prepareCmd(cmd *cobra.Command, stdIn io.Reader, stdOut, stdErr io.Writer, args []string) {
cmd.SetIn(stdIn)
cmd.SetOut(io.MultiWriter(stdOut, debugStdout))
cmd.SetErr(io.MultiWriter(stdErr, debugStderr))
Expand All @@ -154,6 +153,11 @@ func ExecBackgroundCtx(ctx context.Context, cmd *cobra.Command, stdIn io.Reader,
args = []string{}
}
cmd.SetArgs(args)
}

// ExecBackgroundCtx runs the cobra command in the background.
func ExecBackgroundCtx(ctx context.Context, cmd *cobra.Command, stdIn io.Reader, stdOut, stdErr io.Writer, args ...string) *errgroup.Group {
prepareCmd(cmd, stdIn, stdOut, stdErr, args)

eg := &errgroup.Group{}
eg.Go(func() error {
Expand All @@ -175,7 +179,12 @@ func Exec(t testing.TB, cmd *cobra.Command, stdIn io.Reader, args ...string) (st

func ExecCtx(ctx context.Context, cmd *cobra.Command, stdIn io.Reader, args ...string) (string, string, error) {
stdOut, stdErr := &bytes.Buffer{}, &bytes.Buffer{}
err := ExecBackgroundCtx(ctx, cmd, stdIn, stdOut, stdErr, args...).Wait()

prepareCmd(cmd, stdIn, stdOut, stdErr, args)

// needs to be on a separate line to ensure that the ouput buffers are read AFTER the command ran
err := cmd.ExecuteContext(ctx)

return stdOut.String(), stdErr.String(), err
}

Expand Down

0 comments on commit 3f26104

Please sign in to comment.