This repository has been archived by the owner on Jan 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
commands.go
123 lines (97 loc) · 2.31 KB
/
commands.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package caddygit
import (
"context"
"os/exec"
"syscall"
)
// Commander runs the given command in order. If a command throws an error,
// it terminates the execution of further commands if `ExitOnError` is set
// true. An error func can also be provided which is run when there's an
// error in running command.
type Commander struct {
commands []Command
OnError func(error)
OnStart func(Command)
}
// AddCommand adds a command into the commander.
func (c *Commander) AddCommand(cmd Command) {
if len(cmd.Args) == 0 {
// don't add an empty commands, this causes trouble in future
return
}
c.commands = append(c.commands, cmd)
}
// Run runs the commands.
func (c *Commander) Run(ctx context.Context) error {
for _, cmd := range c.commands {
if cmd.String() == "" {
continue
}
if c.OnStart != nil {
c.OnStart(cmd)
}
if err := cmd.Execute(ctx); err != nil {
if c.OnError != nil {
c.OnError(err)
}
}
select {
case <-ctx.Done():
return ctx.Err()
default:
continue
}
}
return nil
}
// Command is the representation of a shell command that can be run async
// or synchronously depending on the async parameter.
type Command struct {
Args []string `json:"command,omitempty"`
Async bool `json:"async,omitempty"`
}
func (c *Command) cmd() *exec.Cmd {
var name string
var args []string
if len(c.Args) == 0 {
return nil
}
name = c.Args[0]
if len(c.Args) > 1 {
args = c.Args[1:]
}
command := exec.Command(name, args...) // nolint:gosec
command.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
return command
}
// String returns the command in a string format.
func (c *Command) String() string {
return c.cmd().String()
}
// Execute runs the command with the given context. The process is killed
// when the context is canceled.
func (c *Command) Execute(ctx context.Context) error {
stream := make(chan error)
cmd := c.cmd()
if err := cmd.Start(); err != nil {
return err
}
if c.Async {
// exit if the process is run asynchronously
return nil
}
go func(ex *exec.Cmd, err chan<- error) {
err <- ex.Wait()
}(cmd, stream)
select {
case <-ctx.Done():
// Elegantly close the parent along-with the children.
err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
if err != nil {
return err
}
return ctx.Err()
case err := <-stream:
return err
}
}