-
Notifications
You must be signed in to change notification settings - Fork 69
/
posix_shell_recipe_executor.go
75 lines (60 loc) · 1.72 KB
/
posix_shell_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
71
72
73
74
75
package execution
import (
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"regexp"
log "github.com/sirupsen/logrus"
"github.com/newrelic/newrelic-cli/internal/config"
"github.com/newrelic/newrelic-cli/internal/install/types"
)
const (
BashPath = "/bin/bash"
ShPath = "/bin/sh"
)
type PosixShellRecipeExecutor struct {
Stderr io.Writer
Stdin io.Reader
Stdout io.Writer
ShellPath string
Dir string
}
func NewPosixShellRecipeExecutor() *PosixShellRecipeExecutor {
writer := config.Logger.WriterLevel(log.DebugLevel)
return &PosixShellRecipeExecutor{
Stdin: os.Stdin,
Stdout: writer,
Stderr: writer,
ShellPath: BashPath,
}
}
func (e *PosixShellRecipeExecutor) Execute(ctx context.Context, r types.OpenInstallationRecipe, v types.RecipeVars) error {
return e.execute(ctx, r.Install, v)
}
func (e *PosixShellRecipeExecutor) ExecutePreInstall(ctx context.Context, r types.OpenInstallationRecipe, v types.RecipeVars) error {
return e.execute(ctx, r.PreInstall.RequireAtDiscovery, v)
}
func (e *PosixShellRecipeExecutor) execute(ctx context.Context, script string, v types.RecipeVars) error {
c := exec.Command(e.ShellPath, "-c", script)
stdoutCapture := NewLineCaptureBuffer(e.Stdout)
stderrCapture := NewLineCaptureBuffer(e.Stderr)
c.Dir = e.Dir
c.Env = append(os.Environ(), v.ToSlice()...)
c.Stderr = stderrCapture
c.Stdin = e.Stdin
c.Stdout = stdoutCapture
if err := c.Run(); err != nil {
var exitError *exec.ExitError
if ok := errors.As(err, &exitError); ok {
fmt.Println(stderrCapture.LastFullLine)
re := regexp.MustCompile(".+?: (.*)")
m := re.FindStringSubmatch(stderrCapture.LastFullLine)
return fmt.Errorf("%w: %s", err, m[1])
}
return err
}
return nil
}