Skip to content
Open
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
41 changes: 41 additions & 0 deletions src/pkg/shell/shell.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,49 @@ func RunContextWithExitCode(ctx context.Context,
return 0, nil
}

func RunContextWithExitCode2(ctx context.Context,
name string,
stdin io.Reader,
stdout, stderr io.Writer,
arg ...string) (int, error) {

logLevel := logrus.GetLevel()
if stderr == nil && logLevel >= logrus.DebugLevel {
stderr = os.Stderr
}

cmd := exec.CommandContext(ctx, name, arg...)
cmd.Stdin = stdin
cmd.Stdout = stdout
cmd.Stderr = stderr

if err := cmd.Run(); err != nil {
exitCode := 1

if ctxErr := ctx.Err(); ctxErr != nil {
return 1, ctxErr
}

var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
exitCode = exitErr.ExitCode()
return exitCode, err
}

return exitCode, err
Comment on lines +101 to +113
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The error handling logic can be simplified by removing the redundant exitCode variable and returning values directly. This makes the function more idiomatic and easier to read.

		if ctxErr := ctx.Err(); ctxErr != nil {
			return 1, ctxErr
		}

		var exitErr *exec.ExitError
		if errors.As(err, &exitErr) {
			return exitErr.ExitCode(), err
		}

		return 1, err

}

return 0, nil
}
Comment thread
DaliborKr marked this conversation as resolved.

func RunWithExitCode(name string, stdin io.Reader, stdout, stderr io.Writer, arg ...string) (int, error) {
ctx := context.Background()
exitCode, err := RunContextWithExitCode(ctx, name, stdin, stdout, stderr, arg...)
return exitCode, err
}

func RunWithExitCode2(name string, stdin io.Reader, stdout, stderr io.Writer, arg ...string) (int, error) {
ctx := context.Background()
exitCode, err := RunContextWithExitCode2(ctx, name, stdin, stdout, stderr, arg...)
return exitCode, err
}
Loading