generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
exec.go
74 lines (63 loc) · 1.65 KB
/
exec.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
package exec
import (
"context"
"os"
"os/exec" //nolint:depguard
"syscall"
"github.com/kballard/go-shellquote"
"github.com/TBD54566975/ftl/internal/log"
)
type Cmd struct {
*exec.Cmd
level log.Level
}
func LookPath(exe string) (string, error) {
path, err := exec.LookPath(exe)
return path, err
}
func Capture(ctx context.Context, dir, exe string, args ...string) ([]byte, error) {
cmd := Command(ctx, log.Debug, dir, exe, args...)
cmd.Stdout = nil
cmd.Stderr = nil
out, err := cmd.CombinedOutput()
return out, err
}
func Command(ctx context.Context, level log.Level, dir, exe string, args ...string) *Cmd {
logger := log.FromContext(ctx)
pgid, err := syscall.Getpgid(0)
if err != nil {
panic(err)
}
logger.Tracef("exec: cd %s && %s %s", shellquote.Join(dir), exe, shellquote.Join(args...))
cmd := exec.CommandContext(ctx, exe, args...)
cmd.SysProcAttr = &syscall.SysProcAttr{
Pgid: pgid,
Setpgid: true,
}
cmd.Dir = dir
output := logger.WriterAt(level)
cmd.Stdout = output
cmd.Stderr = output
cmd.Env = os.Environ()
return &Cmd{cmd, level}
}
// RunBuffered runs the command and captures the output. If the command fails, the output is logged.
func (c *Cmd) RunBuffered(ctx context.Context) error {
outputBuffer := NewCircularBuffer(100)
output := outputBuffer.WriterAt(ctx, c.level)
c.Cmd.Stdout = output
c.Cmd.Stderr = output
err := c.Run()
if err != nil {
log.FromContext(ctx).Infof("%s", outputBuffer.Bytes())
return err
}
return nil
}
// Kill sends a signal to the process group of the command.
func (c *Cmd) Kill(signal syscall.Signal) error {
if c.Process == nil {
return nil
}
return syscall.Kill(c.Process.Pid, signal)
}