-
Notifications
You must be signed in to change notification settings - Fork 69
/
sh_recipe_executor.go
70 lines (56 loc) · 1.55 KB
/
sh_recipe_executor.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
package execution
import (
"context"
"fmt"
"io"
"os"
"strings"
"mvdan.cc/sh/v3/expand"
"mvdan.cc/sh/v3/interp"
"mvdan.cc/sh/v3/syntax"
log "github.com/sirupsen/logrus"
"github.com/newrelic/newrelic-cli/internal/install/types"
)
type ShRecipeExecutor struct {
Dir string
Stderr io.Writer
Stdin io.Reader
Stdout io.Writer
}
func NewShRecipeExecutor() *ShRecipeExecutor {
return &ShRecipeExecutor{
Stdin: os.Stdin,
}
}
func (e *ShRecipeExecutor) Execute(ctx context.Context, r types.OpenInstallationRecipe, v types.RecipeVars) error {
return e.execute(ctx, r.Install, v)
}
func (e *ShRecipeExecutor) ExecutePreInstall(ctx context.Context, r types.OpenInstallationRecipe, v types.RecipeVars) error {
log.Tracef("ExecutePreInstall script for recipe %s", r.Name)
return e.execute(ctx, r.PreInstall.RequireAtDiscovery, v)
}
func (e *ShRecipeExecutor) execute(ctx context.Context, script string, v types.RecipeVars) error {
p, err := syntax.NewParser().Parse(strings.NewReader(script), "")
if err != nil {
return err
}
environ := append(os.Environ(), v.ToSlice()...)
stdoutCapture := NewLineCaptureBuffer(e.Stdout)
stderrCapture := NewLineCaptureBuffer(e.Stderr)
i, err := interp.New(
interp.Params("-e"),
interp.Dir(e.Dir),
interp.Env(expand.ListEnviron(environ...)),
interp.StdIO(e.Stdin, stdoutCapture, stderrCapture),
)
if err != nil {
return err
}
if err := i.Run(ctx, p); err != nil {
if _, ok := interp.IsExitStatus(err); ok {
return fmt.Errorf("%w: %s", err, stderrCapture.LastFullLine)
}
return err
}
return nil
}