summaryrefslogtreecommitdiffstats
path: root/lib/common/filepath.go
diff options
context:
space:
mode:
authorSebastien Douheret <sebastien.douheret@iot.bzh>2017-05-18 11:04:44 +0200
committerSebastien Douheret <sebastien.douheret@iot.bzh>2017-05-18 11:04:44 +0200
commitca0326f03972b9adf5a5ee21a963c7ef8a5ad366 (patch)
tree3e8efc249a8bc35bfa4affdfa6eca73dcb838194 /lib/common/filepath.go
parent2c9ae6a5a27ae2f2e23495c613e7a53aed8e786c (diff)
Improved ResolveEnvVar and add support of tilde (~/...)
Diffstat (limited to 'lib/common/filepath.go')
-rw-r--r--lib/common/filepath.go41
1 files changed, 40 insertions, 1 deletions
diff --git a/lib/common/filepath.go b/lib/common/filepath.go
index 603c2a2..42ef82f 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,35 @@ 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) {
+
+ // Resolved tilde : ~/
+ if 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
+}