-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrunner.go
More file actions
95 lines (74 loc) · 1.61 KB
/
runner.go
File metadata and controls
95 lines (74 loc) · 1.61 KB
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
89
90
91
92
93
94
95
package managers
import (
"bytes"
"context"
"os/exec"
"time"
)
type Runner interface {
Run(ctx context.Context, dir string, args ...string) (*Result, error)
}
type ExecRunner struct{}
func NewExecRunner() *ExecRunner {
return &ExecRunner{}
}
func (r *ExecRunner) Run(ctx context.Context, dir string, args ...string) (*Result, error) {
if len(args) == 0 {
return nil, ErrNoCommand
}
start := time.Now()
cmd := exec.CommandContext(ctx, args[0], args[1:]...)
cmd.Dir = dir
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
result := &Result{
Command: args,
Stdout: stdout.String(),
Stderr: stderr.String(),
Duration: time.Since(start),
Cwd: dir,
Context: ContextProject,
}
if cmd.ProcessState != nil {
result.ExitCode = cmd.ProcessState.ExitCode()
} else {
result.ExitCode = -1
}
if err != nil && result.ExitCode == -1 {
return result, err
}
return result, nil
}
type MockRunner struct {
Captured [][]string
Results []*Result
Errors []error
callIdx int
}
func NewMockRunner() *MockRunner {
return &MockRunner{}
}
func (m *MockRunner) Run(ctx context.Context, dir string, args ...string) (*Result, error) {
m.Captured = append(m.Captured, args)
idx := m.callIdx
m.callIdx++
if idx < len(m.Errors) && m.Errors[idx] != nil {
return nil, m.Errors[idx]
}
if idx < len(m.Results) {
return m.Results[idx], nil
}
return &Result{
Command: args,
ExitCode: 0,
Cwd: dir,
}, nil
}
func (m *MockRunner) LastCaptured() []string {
if len(m.Captured) == 0 {
return nil
}
return m.Captured[len(m.Captured)-1]
}