forked from theairkit/runcmd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathruncmd.go
88 lines (73 loc) · 1.63 KB
/
runcmd.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package runcmd
import (
"bytes"
"fmt"
"io"
"syscall"
"github.com/reconquest/karma-go"
)
// ExecError represents error messages occured while executing command.
type ExecError struct {
ExecutionError error
Args []string
Output []byte
}
// Runner creates command workers.
type Runner interface {
Command(name string, arg ...string) CmdWorker
}
// CmdWorker executes commands.
type CmdWorker interface {
Run() error
Output() ([]byte, []byte, error)
Start() error
Wait() error
StdinPipe() (io.WriteCloser, error)
StdoutPipe() (io.Reader, error)
StderrPipe() (io.Reader, error)
SetStdout(io.Writer)
SetStderr(io.Writer)
SetStdin(io.Reader)
GetArgs() []string
CmdError() error
Signal(syscall.Signal) error
}
func (err ExecError) Error() string {
errString := fmt.Sprintf(
"%q failed: %s", err.Args, err.ExecutionError,
)
if len(err.Output) > 0 {
errString = errString + ", output: \n" + string(err.Output)
}
return errString
}
func run(worker CmdWorker) error {
err := worker.Start()
if err != nil {
return karma.Format(
err, "can't exec %q", worker.GetArgs(),
)
}
err = worker.Wait()
if err != nil {
return ExecError{
ExecutionError: err,
Args: worker.GetArgs(),
}
}
return nil
}
func output(worker CmdWorker) ([]byte, []byte, error) {
var stdout bytes.Buffer
var stderr bytes.Buffer
worker.SetStdout(&stdout)
worker.SetStderr(&stderr)
err := run(worker)
if err != nil {
if execErr, ok := err.(ExecError); ok {
execErr.Output = append(stdout.Bytes(), stderr.Bytes()...)
}
return stdout.Bytes(), stderr.Bytes(), err
}
return stdout.Bytes(), stderr.Bytes(), nil
}