blob: ab688382f813a55b3434438070e7d879e3eafa65 [file] [log] [blame]
Jiri Simsa1f97e1f2014-05-28 17:32:47 -07001package exec
2
3import (
4 "errors"
5 "strings"
6)
7
Jiri Simsa70c32052014-06-18 11:38:21 -07008// Getenv retrieves the value of the given variable from the given
9// slice of environment variable assignments.
10func Getenv(env []string, name string) (string, error) {
11 for _, v := range env {
12 if strings.HasPrefix(v, name+"=") {
13 return strings.TrimPrefix(v, name+"="), nil
14 }
15 }
16 return "", errors.New("not found")
17}
18
19// Setenv updates / adds the value assignment for the given variable
Jiri Simsa1f97e1f2014-05-28 17:32:47 -070020// in the given slice of environment variable assigments.
Jiri Simsa70c32052014-06-18 11:38:21 -070021func Setenv(env []string, name, value string) []string {
Jiri Simsa1f97e1f2014-05-28 17:32:47 -070022 newValue := name + "=" + value
23 for i, v := range env {
24 if strings.HasPrefix(v, name+"=") {
25 env[i] = newValue
26 return env
27 }
28 }
29 return append(env, newValue)
30}
Bogdan Caprita5420f172014-10-10 15:58:14 -070031
32// Mergeenv merges the values for the variables contained in 'other' with the
33// values contained in 'base'. If a variable exists in both, the value in
34// 'other' takes precedence.
35func Mergeenv(base, other []string) []string {
36 otherValues := make(map[string]string)
37 otherUsed := make(map[string]bool)
38 for _, v := range other {
39 if parts := strings.SplitN(v, "=", 2); len(parts) == 2 {
40 otherValues[parts[0]] = parts[1]
41 }
42 }
43 for i, v := range base {
44 if parts := strings.SplitN(v, "=", 2); len(parts) == 2 {
45 if otherValue, ok := otherValues[parts[0]]; ok {
46 base[i] = parts[0] + "=" + otherValue
47 otherUsed[parts[0]] = true
48 }
49 }
50 }
51 for k, v := range otherValues {
52 if !otherUsed[k] {
53 base = append(base, k+"="+v)
54 }
55 }
56 return base
57}