X-Git-Url: https://gerrit.automotivelinux.org/gerrit/gitweb?a=blobdiff_plain;ds=sidebyside;f=lib%2Fcommon%2Ffilepath.go;h=4c8c0da5487f60a02b9fa46eccb3276f37d96f1b;hb=db2c02a9bfd709c662872fccc86d011136e9d8d1;hp=603c2a2685d8d9a92cdd656a0a5d690b878c3f7b;hpb=40a7183f3b4aa32379aa8b4949f5f9c5e32f79f6;p=src%2Fxds%2Fxds-server.git diff --git a/lib/common/filepath.go b/lib/common/filepath.go index 603c2a2..4c8c0da 100644 --- a/lib/common/filepath.go +++ b/lib/common/filepath.go @@ -1,6 +1,13 @@ package common -import "os" +import ( + "fmt" + "os" + "os/user" + "path" + "path/filepath" + "regexp" +) // Exists returns whether the given file or directory exists or not func Exists(path string) bool { @@ -13,3 +20,38 @@ func Exists(path string) bool { } return true } + +// ResolveEnvVar Resolved environment variable regarding the syntax ${MYVAR} +// or $MYVAR following by a slash or a backslash +func ResolveEnvVar(s string) (string, error) { + if s == "" { + return s, nil + } + + // Resolved tilde : ~/ + if len(s) > 2 && s[:2] == "~/" { + if usr, err := user.Current(); err == nil { + s = filepath.Join(usr.HomeDir, s[2:]) + } + } + + // Resolved ${MYVAR} + re := regexp.MustCompile("\\${([^}]+)}") + vars := re.FindAllStringSubmatch(s, -1) + res := s + for _, v := range vars { + val := os.Getenv(v[1]) + if val == "" { + return res, fmt.Errorf("ERROR: %s env variable not defined", v[1]) + } + + rer := regexp.MustCompile("\\${" + v[1] + "}") + res = rer.ReplaceAllString(res, val) + } + + // Resolved $MYVAR following by a slash (or a backslash for Windows) + // TODO + //re := regexp.MustCompile("\\$([^\\/])+/") + + return path.Clean(res), nil +}