-
Notifications
You must be signed in to change notification settings - Fork 288
/
kubectl_runner.go
59 lines (47 loc) · 1.64 KB
/
kubectl_runner.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
package k8s
import (
"bytes"
"context"
"os"
"os/exec"
"strings"
)
type kubectlRunner interface {
exec(ctx context.Context, argv []string) (stdout string, stderr string, err error)
execWithStdin(ctx context.Context, argv []string, stdin string) (stdout string, stderr string, err error)
}
type realKubectlRunner struct {
kubeContext KubeContext
}
var _ kubectlRunner = realKubectlRunner{}
func (k realKubectlRunner) tiltPath() string {
// TODO(nick): It might be better to dependency inject this. Right now, this
// only works if os.Args[0] is the Tilt binary. It won't work right if this
// is linked into separately compiled binaries that don't have a kubectl
// sub-command.
return os.Args[0]
}
func (k realKubectlRunner) prependGlobalArgs(args []string) []string {
return append([]string{"kubectl", "--context", string(k.kubeContext)}, args...)
}
func (k realKubectlRunner) exec(ctx context.Context, args []string) (stdout string, stderr string, err error) {
args = k.prependGlobalArgs(args)
c := exec.CommandContext(ctx, k.tiltPath(), args...)
stdoutBuf := &bytes.Buffer{}
stderrBuf := &bytes.Buffer{}
c.Stdout = stdoutBuf
c.Stderr = stderrBuf
err = c.Run()
return stdoutBuf.String(), stderrBuf.String(), err
}
func (k realKubectlRunner) execWithStdin(ctx context.Context, args []string, stdin string) (stdout string, stderr string, err error) {
args = k.prependGlobalArgs(args)
c := exec.CommandContext(ctx, k.tiltPath(), args...)
c.Stdin = strings.NewReader(stdin)
stdoutBuf := &bytes.Buffer{}
stderrBuf := &bytes.Buffer{}
c.Stdout = stdoutBuf
c.Stderr = stderrBuf
err = c.Run()
return stdoutBuf.String(), stderrBuf.String(), err
}