-
Notifications
You must be signed in to change notification settings - Fork 259
/
exec_script.go
97 lines (86 loc) · 2.21 KB
/
exec_script.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
package daemon
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/rs/zerolog/log"
"golang.org/x/mod/modfile"
"encr.dev/cli/daemon/run"
"encr.dev/internal/optracker"
"encr.dev/pkg/paths"
daemonpb "encr.dev/proto/encore/daemon"
)
// ExecScript executes a one-off script.
func (s *Server) ExecScript(req *daemonpb.ExecScriptRequest, stream daemonpb.Daemon_ExecScriptServer) error {
ctx := stream.Context()
slog := &streamLog{stream: stream, buffered: true}
stderr := slog.Stderr(false)
sendErr := func(err error) {
if err := run.AsErrorList(err); err != nil {
_ = err.SendToStream(stream)
} else {
errStr := err.Error()
if !strings.HasSuffix(errStr, "\n") {
errStr += "\n"
}
slog.Stderr(false).Write([]byte(errStr))
}
streamExit(stream, 1)
}
ctx, tracer, err := s.beginTracing(ctx, req.AppRoot, req.WorkingDir, req.TraceFile)
if err != nil {
sendErr(err)
return nil
}
defer tracer.Close()
app, err := s.apps.Track(req.AppRoot)
if err != nil {
sendErr(err)
return nil
}
modPath := filepath.Join(app.Root(), "go.mod")
modData, err := os.ReadFile(modPath)
if err != nil {
sendErr(err)
return nil
}
mod, err := modfile.Parse(modPath, modData, nil)
if err != nil {
sendErr(err)
return nil
}
commandPkg := paths.Pkg(mod.Module.Mod.Path).JoinSlash(paths.RelSlash(req.CommandRelPath))
ops := optracker.New(stderr, stream)
defer ops.AllDone() // Kill the tracker when we exit this function
testResults := make(chan error, 1)
defer func() {
if recovered := recover(); recovered != nil {
var err error
switch recovered := recovered.(type) {
case error:
err = recovered
default:
err = fmt.Errorf("%v", recovered)
}
log.Err(err).Msg("panic during script execution")
testResults <- fmt.Errorf("panic occured within Encore during script execution: %v\n", recovered)
}
}()
p := run.ExecScriptParams{
App: app,
WorkingDir: req.WorkingDir,
Environ: req.Environ,
MainPkg: commandPkg,
ScriptArgs: req.ScriptArgs,
Stdout: slog.Stdout(false),
Stderr: slog.Stderr(false),
OpTracker: ops,
}
if err := s.mgr.ExecScript(stream.Context(), p); err != nil {
sendErr(err)
} else {
streamExit(stream, 0)
}
return nil
}