Jiri Simsa | 1f97e1f | 2014-05-28 17:32:47 -0700 | [diff] [blame] | 1 | package exec |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "strings" |
| 6 | ) |
| 7 | |
Jiri Simsa | 70c3205 | 2014-06-18 11:38:21 -0700 | [diff] [blame] | 8 | // Getenv retrieves the value of the given variable from the given |
| 9 | // slice of environment variable assignments. |
| 10 | func 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 Simsa | 1f97e1f | 2014-05-28 17:32:47 -0700 | [diff] [blame] | 20 | // in the given slice of environment variable assigments. |
Jiri Simsa | 70c3205 | 2014-06-18 11:38:21 -0700 | [diff] [blame] | 21 | func Setenv(env []string, name, value string) []string { |
Jiri Simsa | 1f97e1f | 2014-05-28 17:32:47 -0700 | [diff] [blame] | 22 | 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 Caprita | 5420f17 | 2014-10-10 15:58:14 -0700 | [diff] [blame] | 31 | |
| 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. |
| 35 | func 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 | } |