-
Notifications
You must be signed in to change notification settings - Fork 9
/
command.go
77 lines (66 loc) · 1.96 KB
/
command.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
package helpers
import (
"fmt"
"os"
"os/exec"
"strings"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gexec"
)
const (
DebugCommandPrefix = "\nCMD>"
DebugOutPrefix = "OUT: "
DebugErrPrefix = "ERR: "
)
func Stembuild(command string, args ...string) *Session {
return StembuildWithEnv(map[string]string{}, command, args...)
}
func RunCommandInDir(workingDir, command string, args ...string) *Session {
WriteCommand(command, args)
session, err := Start(
&exec.Cmd{
Path: command,
Args: append([]string{command}, args...),
Dir: workingDir,
},
NewPrefixedWriter(DebugOutPrefix, GinkgoWriter),
NewPrefixedWriter(DebugErrPrefix, GinkgoWriter))
Expect(err).NotTo(HaveOccurred())
return session
}
func StembuildWithEnv(passedEnv map[string]string, command string, args ...string) *Session {
WriteCommand(command, args)
execComand := exec.Command(command, args...)
env := os.Environ()
for key, val := range passedEnv {
env = AddOrReplaceEnvironment(env, key, val)
}
execComand.Env = env
session, err := Start(
execComand,
NewPrefixedWriter(DebugOutPrefix, GinkgoWriter),
NewPrefixedWriter(DebugErrPrefix, GinkgoWriter))
Expect(err).NotTo(HaveOccurred())
return session
}
func WriteCommand(command string, args []string) {
display := append([]string{DebugCommandPrefix, command}, args...)
GinkgoWriter.Write([]byte(strings.Join(append(display, "\n"), " "))) //nolint:errcheck
}
// AddOrReplaceEnvironment will update environment if it already exists or will add
// a new environment with the given environment name and details.
func AddOrReplaceEnvironment(env []string, newEnvName string, newEnvVal string) []string {
var found bool
for i, envPair := range env {
splitEnv := strings.Split(envPair, "=")
if splitEnv[0] == newEnvName {
env[i] = fmt.Sprintf("%s=%s", newEnvName, newEnvVal)
found = true
}
}
if !found {
env = append(env, fmt.Sprintf("%s=%s", newEnvName, newEnvVal))
}
return env
}