-
-
Notifications
You must be signed in to change notification settings - Fork 104
/
envvars.go
35 lines (32 loc) · 1.19 KB
/
envvars.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
// Package envvars provides helper functions to work with lists of environment variables as provided by `os.Environ`.
package test
import (
"fmt"
"os"
"strings"
)
// PrependPath provides a new envvars with the given directory appended to the PATH entry of the given envvars.
// This function assumes there is only one PATH entry.
func PrependEnvPath(envVars []string, directory string) []string {
for e, envVar := range envVars {
if strings.HasPrefix(envVar, "PATH=") {
parts := strings.SplitN(envVar, "=", 2)
envVars[e] = "PATH=" + directory + string(os.PathListSeparator) + parts[1]
return envVars
}
}
return append(envVars, fmt.Sprintf("PATH=%s", directory))
}
// Replace provides a new envvars in which the entry with the given key contains the given value instead of its original value.
// If no entry with the given key exists, appends one at the end.
// This function assumes that keys are unique, i.e. no duplicate keys exist.
func ReplaceEnvVar(envVars []string, key string, value string) []string {
prefix := key + "="
for e, envVar := range envVars {
if strings.HasPrefix(envVar, prefix) {
envVars[e] = prefix + value
return envVars
}
}
return append(envVars, prefix+value)
}