forked from carvel-dev/kapp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkapp.go
105 lines (87 loc) · 1.96 KB
/
kapp.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
98
99
100
101
102
103
104
105
// Copyright 2020 VMware, Inc.
// SPDX-License-Identifier: Apache-2.0
package e2e
import (
"bytes"
"fmt"
"io"
"os"
"os/exec"
"strings"
"testing"
)
type Kapp struct {
t *testing.T
namespace string
kappPath string
l Logger
}
type RunOpts struct {
NoNamespace bool
IntoNs bool
AllowError bool
StderrWriter io.Writer
StdoutWriter io.Writer
StdinReader io.Reader
CancelCh chan struct{}
Redact bool
Interactive bool
}
func (k Kapp) Run(args []string) string {
out, _ := k.RunWithOpts(args, RunOpts{})
return out
}
func (k Kapp) RunWithOpts(args []string, opts RunOpts) (string, error) {
if !opts.NoNamespace {
args = append(args, []string{"-n", k.namespace}...)
}
if opts.IntoNs {
args = append(args, []string{"--into-ns", k.namespace}...)
}
if !opts.Interactive {
args = append(args, "--yes")
}
k.l.Debugf("Running '%s'...\n", k.cmdDesc(args, opts))
cmd := exec.Command(k.kappPath, args...)
cmd.Stdin = opts.StdinReader
var stderr, stdout bytes.Buffer
if opts.StderrWriter != nil {
cmd.Stderr = opts.StderrWriter
} else {
cmd.Stderr = &stderr
}
if opts.StdoutWriter != nil {
cmd.Stdout = opts.StdoutWriter
} else {
cmd.Stdout = &stdout
}
if opts.CancelCh != nil {
go func() {
select {
case <-opts.CancelCh:
cmd.Process.Signal(os.Interrupt)
}
}()
}
err := cmd.Run()
stdoutStr := stdout.String()
if err != nil {
exitCode := -1
if exitErr, ok := err.(*exec.ExitError); ok {
exitCode = exitErr.ExitCode()
}
err = fmt.Errorf("Execution error: stdout: '%s' stderr: '%s' error: '%s' exit code: '%d'",
stdoutStr, stderr.String(), err, exitCode)
if !opts.AllowError {
k.t.Fatalf("Failed to successfully execute '%s': %v", k.cmdDesc(args, opts), err)
}
}
return stdoutStr, err
}
func (k Kapp) cmdDesc(args []string, opts RunOpts) string {
prefix := "kapp"
if opts.Redact {
return prefix + " -redacted-"
}
return fmt.Sprintf("%s %s", prefix, strings.Join(args, " "))
}