Fix ResolveEnvVar when param is empty.
[src/xds/xds-server.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         if s == "" {
28                 return s, nil
29         }
30
31         // Resolved tilde : ~/
32         if len(s) > 2 && s[:2] == "~/" {
33                 if usr, err := user.Current(); err == nil {
34                         s = filepath.Join(usr.HomeDir, s[2:])
35                 }
36         }
37
38         // Resolved ${MYVAR}
39         re := regexp.MustCompile("\\${([^}]+)}")
40         vars := re.FindAllStringSubmatch(s, -1)
41         res := s
42         for _, v := range vars {
43                 val := os.Getenv(v[1])
44                 if val == "" {
45                         return res, fmt.Errorf("ERROR: %s env variable not defined", v[1])
46                 }
47
48                 rer := regexp.MustCompile("\\${" + v[1] + "}")
49                 res = rer.ReplaceAllString(res, val)
50         }
51
52         // Resolved $MYVAR following by a slash (or a backslash for Windows)
53         // TODO
54         //re := regexp.MustCompile("\\$([^\\/])+/")
55
56         return path.Clean(res), nil
57 }