d9cb3d55bf27d879edc43f6841d7e916a7e5e7c7
[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         "runtime"
11 )
12
13 // Exists returns whether the given file or directory exists or not
14 func Exists(path string) bool {
15         _, err := os.Stat(path)
16         if err == nil {
17                 return true
18         }
19         if os.IsNotExist(err) {
20                 return false
21         }
22         return true
23 }
24
25 // ResolveEnvVar Resolved environment variable regarding the syntax ${MYVAR}
26 // or $MYVAR following by a slash or a backslash
27 func ResolveEnvVar(s string) (string, error) {
28         if s == "" {
29                 return s, nil
30         }
31
32         // Resolved tilde : ~/
33         if len(s) > 2 && s[:2] == "~/" {
34                 if usr, err := user.Current(); err == nil {
35                         s = filepath.Join(usr.HomeDir, s[2:])
36                 }
37         }
38
39         // Resolved ${MYVAR}
40         re := regexp.MustCompile("\\${([^}]+)}")
41         vars := re.FindAllStringSubmatch(s, -1)
42         res := s
43         for _, v := range vars {
44                 val := os.Getenv(v[1])
45                 if val == "" {
46                         // Specific case to resolved $HOME or ${HOME} on Windows host
47                         if runtime.GOOS == "windows" && v[1] == "HOME" {
48                                 if usr, err := user.Current(); err == nil {
49                                         val = usr.HomeDir
50                                 }
51                         } else {
52                                 return res, fmt.Errorf("ERROR: %s env variable not defined", v[1])
53                         }
54                 }
55
56                 rer := regexp.MustCompile("\\${" + v[1] + "}")
57                 res = rer.ReplaceAllString(res, val)
58         }
59
60         // Resolved $MYVAR following by a slash (or a backslash for Windows)
61         // TODO
62         //re := regexp.MustCompile("\\$([^\\/])+/")
63
64         return path.Clean(res), nil
65 }