-
Notifications
You must be signed in to change notification settings - Fork 206
Expand file tree
/
Copy pathexec.go
More file actions
101 lines (81 loc) · 2.03 KB
/
Copy pathexec.go
File metadata and controls
101 lines (81 loc) · 2.03 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
96
97
98
99
100
101
package exec
import (
"context"
"io"
"os"
osexec "os/exec"
)
type Command interface {
// Wait for command to terminate. It must have been previously started.
Wait() error
// StdinPipe returns a pipe that will be connected to the command's standard input when the command starts.
Stdout() io.ReadCloser
// StderrPipe returns a pipe that will be connected to the command's standard error when the command starts.
Stderr() io.ReadCloser
}
type command struct {
cmd *osexec.Cmd
execContext *execContext
stdout io.ReadCloser
stderr io.ReadCloser
}
func (c *command) Wait() error {
// After the command has finished (cmd.Wait call), remove the temporary script file
defer os.Remove(c.execContext.scriptFile)
err := c.cmd.Wait()
if err != nil {
return err
}
return nil
}
func (c *command) Stdout() io.ReadCloser {
return c.stdout
}
func (c *command) Stderr() io.ReadCloser {
return c.stderr
}
type Executor struct {
interpreter interpreter
dir string
}
func NewCommandExecutor(dir string) (*Executor, error) {
interpreter, err := findInterpreter()
if err != nil {
return nil, err
}
return &Executor{
interpreter: interpreter,
dir: dir,
}, nil
}
func (e *Executor) StartCommand(ctx context.Context, command string) (Command, error) {
ec, err := e.interpreter.prepare(command)
if err != nil {
return nil, err
}
return e.start(ctx, ec)
}
func (e *Executor) start(ctx context.Context, ec *execContext) (Command, error) {
cmd := osexec.CommandContext(ctx, ec.executable, ec.args...)
cmd.Dir = e.dir
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
return &command{cmd, ec, stdout, stderr}, cmd.Start()
}
func (e *Executor) Exec(ctx context.Context, command string) ([]byte, error) {
cmd, err := e.StartCommand(ctx, command)
if err != nil {
return nil, err
}
res, err := io.ReadAll(io.MultiReader(cmd.Stdout(), cmd.Stderr()))
if err != nil {
return nil, err
}
return res, cmd.Wait()
}