| 1 | package os |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "os/exec" |
| 6 | "syscall" |
| 7 | ) |
| 8 | |
| 9 | // Given an error, determines if that error is an os/exec ExitError. If it is, |
| 10 | // and the platform is supported, returns the exitCode and nil error. |
| 11 | // Otherwise, passes through the error, and exitCode is undefined. |
| 12 | func GetExitCode(exitErr error) (exitCode int, err error) { |
| 13 | if e, ok := exitErr.(*exec.ExitError); ok { |
| 14 | return getExitCodeSys(e.ProcessState.Sys()) |
| 15 | } |
| 16 | |
| 17 | return 0, err |
| 18 | } |
| 19 | |
| 20 | func getExitCodeSys(sys interface{}) (exitCode int, err error) { |
| 21 | ws, ok := sys.(syscall.WaitStatus) |
| 22 | if !ok { |
| 23 | // Should never happen. |
| 24 | panic(fmt.Sprintf("unknown system exit code type: %T", sys)) |
| 25 | } |
| 26 | |
| 27 | return ws.ExitStatus(), nil |
| 28 | } |