Tobias Bosch | 900dbc9 | 2019-06-24 09:31:39 -0700 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "os/exec" |
| 6 | "runtime" |
| 7 | "strings" |
| 8 | "syscall" |
| 9 | ) |
| 10 | |
| 11 | type userError struct { |
| 12 | err string |
| 13 | } |
| 14 | |
| 15 | var _ error = userError{} |
| 16 | |
| 17 | func (err userError) Error() string { |
| 18 | return err.err |
| 19 | } |
| 20 | |
| 21 | func newUserErrorf(format string, v ...interface{}) userError { |
| 22 | return userError{err: fmt.Sprintf(format, v...)} |
| 23 | } |
| 24 | |
| 25 | func newErrorwithSourceLocf(format string, v ...interface{}) error { |
| 26 | return newErrorwithSourceLocfInternal(2, format, v...) |
| 27 | } |
| 28 | |
| 29 | func wrapErrorwithSourceLocf(err error, format string, v ...interface{}) error { |
| 30 | return newErrorwithSourceLocfInternal(2, "%s: %s", fmt.Sprintf(format, v...), err.Error()) |
| 31 | } |
| 32 | |
| 33 | // Based on the implementation of log.Output |
| 34 | func newErrorwithSourceLocfInternal(skip int, format string, v ...interface{}) error { |
| 35 | _, file, line, ok := runtime.Caller(skip) |
| 36 | if !ok { |
| 37 | file = "???" |
| 38 | line = 0 |
| 39 | } |
| 40 | if lastSlash := strings.LastIndex(file, "/"); lastSlash >= 0 { |
| 41 | file = file[lastSlash+1:] |
| 42 | } |
| 43 | |
| 44 | return fmt.Errorf("%s:%d: %s", file, line, fmt.Sprintf(format, v...)) |
| 45 | } |
| 46 | |
| 47 | func getExitCode(err error) (exitCode int, ok bool) { |
| 48 | if err == nil { |
| 49 | return 0, true |
| 50 | } |
| 51 | if exiterr, ok := err.(*exec.ExitError); ok { |
| 52 | if status, ok := exiterr.Sys().(syscall.WaitStatus); ok { |
| 53 | return status.ExitStatus(), true |
| 54 | } |
| 55 | } |
| 56 | return 0, false |
| 57 | } |