-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpathresolver.go
More file actions
70 lines (59 loc) · 1.6 KB
/
pathresolver.go
File metadata and controls
70 lines (59 loc) · 1.6 KB
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
//Package pathresolver provides a simple path resolving mechanism relative to a defined basedir
package pathresolver
import (
"fmt"
"runtime"
"strings"
"github.com/mitchellh/go-homedir"
"path/filepath"
)
var (
basedirectory string
isinit bool = false
)
//Init initializes the pathresolver with a basedir for the respective system.
//If only one of the parameters is set, it is used of all systems
//If both parameters are set, the basedirectory is set according to the current system
//If the given paths are relative, they are set relative to the users homedir (~ and %HOMEDIR% respectively)
func Init(unix string, windows string) error {
isinit = false
path := ""
if unix == "" && windows == "" {
return fmt.Errorf("either unixbase or windowsbase must be set")
} else if unix == "" {
path = windows
} else if windows == "" {
path = unix
} else if strings.Contains(runtime.GOOS, "windows") {
path = windows
} else {
path = unix
}
if filepath.IsAbs(path) {
basedirectory = path
isinit = true
return nil
}
home, err := homedir.Dir()
if err != nil {
return err
}
basedirectory = filepath.Join(home, path)
isinit = true
return nil
}
//Path resolves a subpath relative to the basedir
//If subpath is empty, basedir is returned
//Subpath must not be an absolute path
func Path(subpath string) (string, error) {
if !isinit {
return "", fmt.Errorf("pathresolver not initialized")
}
if subpath == "" {
return basedirectory, nil
}
if filepath.IsAbs(subpath) {
return "", fmt.Errorf("cannot use absolute path as subpath")
}
return filepath.Join(basedirectory, subpath), nil
}