-
Notifications
You must be signed in to change notification settings - Fork 289
/
path.go
92 lines (77 loc) · 2.19 KB
/
path.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package utils
import (
"errors"
"os"
"os/user"
"path/filepath"
)
// NormalizeCommand has very similar semantics to `NormalizeFilePath`, except
// we only "absolute" the path if it exists on the filesystem. This will ensure
// that:
//
// "templates/bootstrap.sh" => "/Users/keithpitt/Development/.../templates/bootstrap.sh"
// "~/.buildkite-agent/bootstrap.sh" => "/Users/keithpitt/.buildkite-agent/bootstrap.sh"
// "cat Readme.md" => "cat Readme.md"
func NormalizeCommand(commandPath string) (string, error) {
// don't normalize empty strings
if commandPath == "" {
return "", nil
}
// expand env and home directory
var err error
commandPath, err = ExpandHome(os.ExpandEnv(commandPath))
if err != nil {
return "", err
}
// if the file exists, absolute it
if _, err := os.Stat(commandPath); err == nil {
// make sure it's absolute
absoluteCommandPath, err := filepath.Abs(commandPath)
if err != nil {
return "", err
}
commandPath = absoluteCommandPath
}
return commandPath, nil
}
// Normalizes a path and returns an clean absolute version. It correctly
// expands environment variables inside paths, converts "~/" into the users
// home directory, and replaces "./" with the current working directory.
func NormalizeFilePath(path string) (string, error) {
// don't normalize empty strings
if path == "" {
return "", nil
}
// expand env and home directory
var err error
path, err = ExpandHome(os.ExpandEnv(path))
if err != nil {
return "", err
}
// make sure its absolute
absolutePath, err := filepath.Abs(path)
if err != nil {
return "", err
}
return absolutePath, nil
}
// ExpandHome expands the path to include the home directory if the path
// is prefixed with `~`. If it isn't prefixed with `~`, the path is
// returned as-is.
// Via https://github.com/mitchellh/go-homedir/blob/master/homedir.go
func ExpandHome(path string) (string, error) {
if len(path) == 0 {
return path, nil
}
if path[0] != '~' {
return path, nil
}
if len(path) > 1 && path[1] != '/' && path[1] != '\\' {
return "", errors.New("cannot expand user-specific home dir")
}
usr, err := user.Current()
if err != nil {
return "", err
}
return filepath.Join(usr.HomeDir, path[1:]), nil
}