aboutsummaryrefslogtreecommitdiffstats
path: root/lib/common/filepath.go
blob: 4c8c0da5487f60a02b9fa46eccb3276f37d96f1b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package common

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 {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	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
}