/
env.go
71 lines (63 loc) · 1.66 KB
/
env.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
package utils
import (
"errors"
"os"
"strings"
)
// GetHomeDir returns '~' as a path
func GetHomeDir() string {
if homeDir := os.Getenv("HOME"); homeDir != "" {
return homeDir
}
if homeDir := os.Getenv("USERPROFILE"); homeDir != "" {
return homeDir
}
return ""
}
// ExpandEnvSafe replaces ${var} or $var in the string according to the values
// of the current environment variables.
// As opposed to os.ExpandEnv, ExpandEnvSafe won't remove the dollar in '$(...)'
// See https://golang.org/src/os/env.go?s=963:994#L22 for the original function
func ExpandEnvSafe(s string) string {
buf := make([]byte, 0, 2*len(s))
i := 0
for j := 0; j < len(s); j++ {
// the following line is the only one changing
if s[j] == '$' && j+1 < len(s) && s[j+1] != '(' {
buf = append(buf, s[i:j]...)
name, w := getShellName(s[j+1:])
buf = append(buf, os.Getenv(name)...)
j += w
i = j + 1
}
}
return string(buf) + s[i:]
}
// ExpandUser expands tild and env vars in unix paths
func ExpandUser(path string) (string, error) {
// Expand variables
path = ExpandEnvSafe(path)
if path[:2] == "~/" {
homeDir := GetHomeDir()
if homeDir == "" {
return "", errors.New("user home directory not found")
}
return strings.Replace(path, "~", homeDir, 1), nil
}
return path, nil
}
// ExpandField expands environment variables in field
func ExpandField(input string) string {
if input == "" {
return ""
}
return ExpandEnvSafe(input)
}
// ExpandSliceField expands environment variables in every entries of a slice field
func ExpandSliceField(input []string) []string {
ret := []string{}
for _, entry := range input {
ret = append(ret, ExpandField(entry))
}
return ret
}