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
13 changes: 11 additions & 2 deletions exec.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"errors"
"log"
"os"
"os/exec"
Expand Down Expand Up @@ -50,8 +51,16 @@ func runCmd(ctx context.Context, cancel context.CancelFunc, cmd string, args ...
log.Println("Command finished successfully.")
} else {
log.Printf("Command exited with error: %s\n", err)
// OPTIMIZE: This could be cleaner
os.Exit(err.(*exec.ExitError).Sys().(syscall.WaitStatus).ExitStatus())

var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
os.Exit(status.ExitStatus())
}
}

// Fallback for non-ExitError types (e.g., *os.SyscallError)
os.Exit(1)
}

}
Expand Down
47 changes: 47 additions & 0 deletions exec_error_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package main

import (
"errors"
"os/exec"
"syscall"
"testing"
)

// helper function mirroring the exit code extraction logic
func extractExitCode(err error) int {
if err == nil {
return 0
}

var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
return status.ExitStatus()
}
}

return 1
}

func TestExtractExitCode_FromExitError(t *testing.T) {
cmd := exec.Command("sh", "-c", "exit 42")
err := cmd.Run()

if err == nil {
t.Fatalf("expected non-nil error")
}

code := extractExitCode(err)
if code != 42 {
t.Fatalf("expected exit code 42, got %d", code)
}
}

func TestExtractExitCode_FromGenericError(t *testing.T) {
err := errors.New("some generic error")

code := extractExitCode(err)
if code != 1 {
t.Fatalf("expected fallback exit code 1, got %d", code)
}
}