/
go.go
68 lines (53 loc) · 1.32 KB
/
go.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
package runner
import (
"context"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"github.com/pkg/errors"
)
type Go struct {
*ExecutableConfig
Source string
command *exec.Cmd
}
var _ Executable = (*Go)(nil)
func (g Go) DryRun(ctx context.Context, w io.Writer) {
_, err := exec.LookPath("go")
if err != nil {
_, _ = fmt.Fprintf(w, "failed to find %q executable: %s\n", "go", err)
}
_, _ = fmt.Fprintf(w, "// go run main.go in $TEMP\n\n")
_, _ = fmt.Fprintf(w, "%s\n", g.Source)
}
func (g *Go) Run(ctx context.Context) error {
executable, err := exec.LookPath("go")
if err != nil {
return errors.Wrapf(err, "failed to find %q executable", "go")
}
tmpDir, err := os.MkdirTemp("", "runme-*")
if err != nil {
return errors.Wrapf(err, "failed to create a temp dir")
}
defer os.RemoveAll(tmpDir)
mainFile := filepath.Join(tmpDir, "main.go")
err = os.WriteFile(mainFile, []byte(g.Source), 0o600)
if err != nil {
return errors.Wrapf(err, "failed to write source to file")
}
c := exec.CommandContext(ctx, executable, "run", mainFile)
c.Dir = g.Dir
c.Stderr = g.Stderr
c.Stdout = g.Stdout
c.Stdin = g.Stdin
g.command = c
return errors.Wrapf(c.Run(), "failed to run command %q", "go run main.go")
}
func (g Go) ExitCode() int {
if g.command == nil {
return -1
}
return g.command.ProcessState.ExitCode()
}