-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathpaths.go
66 lines (57 loc) · 1.58 KB
/
paths.go
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
58
59
60
61
62
63
64
65
66
package main
import (
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
)
var envSchemes = map[string]*regexp.Regexp{
"windows": regexp.MustCompile("%([a-zA-Z0-9]+)%"),
"linux": regexp.MustCompile("[$]([a-zA-Z0-9]+)"),
"darwin": regexp.MustCompile("[$]([a-zA-Z0-9]+)"),
}
func convertAbsolute(path string) (string, error) {
// if the path contains an environment variable at its beginning
// then replace that with its value
reg, ok := envSchemes[runtime.GOOS]
if ok && reg.MatchString(path) {
if matches := reg.FindAllStringSubmatch(path, -1); len(matches) > 0 {
// replace environment variable with its value
path = strings.Replace(path, matches[0][0], os.Getenv(matches[0][1]), 1)
}
}
abs, err := filepath.Abs(path)
if err == nil {
return abs, nil
} else {
return path, err
}
}
// takes an array of (maybe) relative paths and convert them to their absolute representatives
func convertAbsolutes(paths []string) []string {
for ind, path := range paths {
if newPath, err := convertAbsolute(path); err == nil {
paths[ind] = newPath
} else {
logger.Errorf("Error while attempting to translate file path %q to absolute path: %q", path, err.Error())
}
}
return paths
}
func parseGlobs(paths []string) []string {
allPaths := []string{}
for _, pattern := range paths {
found, err := filepath.Glob(pattern)
if err != nil {
logger.Errorf("Error while converting patterns to paths. %q", err.Error())
} else {
if len(found) == 0 {
allPaths = append(allPaths, pattern)
} else {
allPaths = append(allPaths, found...)
}
}
}
return allPaths
}