forked from digitalocean/doctl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.go
91 lines (77 loc) · 1.88 KB
/
command.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
89
90
91
package doit
import (
"os"
"os/exec"
)
// Command runs commands.
type Command interface {
Run(args ...string) ([]byte, error)
Start(args ...string) error
Stop() error
}
// LiveCommand is a live implementation of Command.
type LiveCommand struct {
path string
cmd *exec.Cmd
}
// NewLiveCommand creates a LiveCommand.
func NewLiveCommand(path string) *LiveCommand {
return &LiveCommand{
path: path,
}
}
var _ Command = &LiveCommand{}
// Run runs a LiveCommand with args and returns stdout and an error if there was one.
func (c *LiveCommand) Run(args ...string) ([]byte, error) {
return exec.Command(c.path, args...).Output()
}
// Start runs a LiveCommand with args and starts it. This would most likely block,
// so you should call it in a goroutine.
func (c *LiveCommand) Start(args ...string) error {
c.cmd = exec.Command(c.path, args...)
c.cmd.Stderr = os.Stderr
return c.cmd.Start()
}
// Stop stops an existing LiveCommand.
func (c *LiveCommand) Stop() error {
return c.cmd.Process.Kill()
}
// MockCommand is a mock command implementation. It allows you simulate running
// an external command.
type MockCommand struct {
path string
running bool
runFn func() error
startFn func() error
stopFn func() error
}
var _ Command = &MockCommand{}
// NewMockCommand createsd a MockCommand.
func NewMockCommand(path string) *MockCommand {
return &MockCommand{
path: path,
runFn: func() error {
return nil
},
startFn: func() error {
return nil
},
stopFn: func() error {
return nil
},
}
}
// Run simulates the running of a command.
func (c *MockCommand) Run(args ...string) ([]byte, error) {
return nil, c.runFn()
}
// Start simulates starting a command.
func (c *MockCommand) Start(args ...string) error {
c.running = true
return c.startFn()
}
// Stop simulates stoping a command.
func (c *MockCommand) Stop() error {
c.running = false
return c.stopFn()
}