Refer xds-exec in doc instead of xds-make.
[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         "strings"
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                         return res, fmt.Errorf("ERROR: %s env variable not defined", v[1])
47                 }
48
49                 rer := regexp.MustCompile("\\${" + v[1] + "}")
50                 res = rer.ReplaceAllString(res, val)
51         }
52
53         // Resolved $MYVAR following by a slash (or a backslash for Windows)
54         // TODO
55         //re := regexp.MustCompile("\\$([^\\/])+/")
56
57         return path.Clean(res), nil
58 }
59
60 // PathNormalize
61 func PathNormalize(p string) string {
62         sep := string(filepath.Separator)
63         if sep != "/" {
64                 return p
65         }
66         // Replace drive like C: by C/
67         res := p
68         if p[1:2] == ":" {
69                 res = p[0:1] + sep + p[2:]
70         }
71         res = strings.Replace(res, "\\", "/", -1)
72         return filepath.Clean(res)
73 }