File: exitcode.go

package info (click to toggle)
golang-github-hlandau-goutils 0.0~git20160722.0.0cdb66a-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 160 kB
  • sloc: makefile: 2
file content (28 lines) | stat: -rw-r--r-- 677 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package os

import (
	"fmt"
	"os/exec"
	"syscall"
)

// Given an error, determines if that error is an os/exec ExitError. If it is,
// and the platform is supported, returns the exitCode and nil error.
// Otherwise, passes through the error, and exitCode is undefined.
func GetExitCode(exitErr error) (exitCode int, err error) {
	if e, ok := exitErr.(*exec.ExitError); ok {
		return getExitCodeSys(e.ProcessState.Sys())
	}

	return 0, err
}

func getExitCodeSys(sys interface{}) (exitCode int, err error) {
	ws, ok := sys.(syscall.WaitStatus)
	if !ok {
		// Should never happen.
		panic(fmt.Sprintf("unknown system exit code type: %T", sys))
	}

	return ws.ExitStatus(), nil
}