forked from buildpacks/packs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sys.go
73 lines (64 loc) · 1.38 KB
/
sys.go
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package packs
import (
"bytes"
"fmt"
"log"
"os"
"os/exec"
"strings"
)
const (
CodeFailed = 1
CodeInvalidArgs = iota + 2
CodeInvalidEnv
CodeNotFound
CodeFailedDetect
CodeFailedBuild
CodeFailedLaunch
CodeFailedUpdate
)
type ErrorFail struct {
Err error
Code int
Action []string
}
func (e *ErrorFail) Error() string {
message := "failed to " + strings.Join(e.Action, " ")
if e.Err == nil {
return message
}
return fmt.Sprintf("%s: %s", message, e.Err)
}
func FailCode(code int, action ...string) error {
return FailErrCode(nil, code, action...)
}
func FailErr(err error, action ...string) error {
code := CodeFailed
if err, ok := err.(*ErrorFail); ok {
code = err.Code
}
return FailErrCode(err, code, action...)
}
func FailErrCode(err error, code int, action ...string) error {
return &ErrorFail{Err: err, Code: code, Action: action}
}
func Exit(err error) {
if err == nil {
os.Exit(0)
}
log.Printf("Error: %s\n", err)
if err, ok := err.(*ErrorFail); ok {
os.Exit(err.Code)
}
os.Exit(CodeFailed)
}
func Run(name string, arg ...string) (string, error) {
stdout, stderr := &bytes.Buffer{}, &bytes.Buffer{}
cmd := exec.Command(name, arg...)
cmd.Stdout = stdout
cmd.Stderr = stderr
if err := cmd.Run(); err != nil {
return "", FailErr(err, "run:", name, strings.Join(arg, " "), "\n", stderr.String())
}
return strings.TrimSpace(stdout.String()), nil
}