-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathrun.go
More file actions
80 lines (61 loc) · 1.36 KB
/
run.go
File metadata and controls
80 lines (61 loc) · 1.36 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
package command
import (
"context"
"os/exec"
"time"
"go.uber.org/zap"
)
// Runner runs a command.
type Runner interface {
Run() error
}
type runnerFunc func() error
func (r runnerFunc) Run() error { return r() }
func (c *Cmd) run(args []string) error {
cmdInfo := zap.Any("command", append([]string{c.Command}, args...))
log := c.log.With(cmdInfo)
startTime := time.Now()
cmd := exec.Command(c.Command, args...)
done := make(chan struct{}, 1)
// timeout
if c.timeout > 0 {
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
// the context must not be cancelled before the command is done
go func() {
<-done
cancel()
}()
cmd = exec.CommandContext(ctx, c.Command, args...)
}
// configure command
{
cmd.Stdout = c.stdWriter
cmd.Stderr = c.stdWriter
if c.errWriter != nil {
cmd.Stderr = c.errWriter
}
cmd.Dir = c.Directory
}
wait := func(err error) error {
// only wait if start was successful
if cmd.Process != nil {
// err is empty, we can reuse it without losing any info
err = cmd.Wait()
}
done <- struct{}{}
log = log.With(zap.Duration("duration", time.Since(startTime))).Named("exit")
if err != nil {
log.Error("", zap.Error(err))
return err
}
log.Info("")
return nil
}
// start command
err := cmd.Start()
if c.Foreground {
return wait(err)
}
go wait(err)
return err
}