Fix ResolveEnvVar function and add support of tilde (~/...)
[src/xds/xds-agent.git] / lib / common / filepath.go
1 package common
2
3 import (
4         "fmt"
5         "os"
6         "os/user"
7         "path"
8         "path/filepath"
9         "regexp"
10 )
11
12 // Exists returns whether the given file or directory exists or not
13 func Exists(path string) bool {
14         _, err := os.Stat(path)
15         if err == nil {
16                 return true
17         }
18         if os.IsNotExist(err) {
19                 return false
20         }
21         return true
22 }
23
24 // ResolveEnvVar Resolved environment variable regarding the syntax ${MYVAR}
25 // or $MYVAR following by a slash or a backslash
26 func ResolveEnvVar(s string) (string, error) {
27
28         // Resolved tilde : ~/
29         if s[:2] == "~/" {
30                 if usr, err := user.Current(); err == nil {
31                         s = filepath.Join(usr.HomeDir, s[2:])
32                 }
33         }
34
35         // Resolved ${MYVAR}
36         re := regexp.MustCompile("\\${([^}]+)}")
37         vars := re.FindAllStringSubmatch(s, -1)
38         res := s
39         for _, v := range vars {
40                 val := os.Getenv(v[1])
41                 if val == "" {
42                         return res, fmt.Errorf("ERROR: %s env variable not defined", v[1])
43                 }
44
45                 rer := regexp.MustCompile("\\${" + v[1] + "}")
46                 res = rer.ReplaceAllString(res, val)
47         }
48
49         // Resolved $MYVAR following by a slash (or a backslash for Windows)
50         // TODO
51         //re := regexp.MustCompile("\\$([^\\/])+/")
52
53         return path.Clean(res), nil
54 }