exitcode.go 902 B

123456789101112131415161718192021222324252627282930313233343536
  1. package main
  2. import (
  3. "os/exec"
  4. "syscall"
  5. "github.com/pkg/errors"
  6. )
  7. // Copied from gotestyourself/icmd
  8. // GetExitCode returns the ExitStatus of a process from the error returned by
  9. // exec.Run(). If the exit status is not available an error is returned.
  10. func GetExitCode(err error) (int, error) {
  11. if exiterr, ok := err.(*exec.ExitError); ok {
  12. if procExit, ok := exiterr.Sys().(syscall.WaitStatus); ok {
  13. return procExit.ExitStatus(), nil
  14. }
  15. }
  16. return 0, errors.Wrap(err, "failed to get exit code")
  17. }
  18. // ExitCodeWithDefault returns ExitStatus of a process from the error returned by
  19. // exec.Run(). If the exit status is not available return a default of 127.
  20. func ExitCodeWithDefault(err error) int {
  21. if err == nil {
  22. return 0
  23. }
  24. exitCode, exiterr := GetExitCode(err)
  25. if exiterr != nil {
  26. // we've failed to retrieve exit code, so we set it to 127
  27. return 127
  28. }
  29. return exitCode
  30. }