This repository has been archived by the owner on Jul 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
path.go
96 lines (74 loc) · 1.77 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
93
94
95
96
package gotk
import (
"os"
"path/filepath"
"runtime"
"strings"
)
type PathFn func() (path string, err error)
func Path(paths ...string) string {
delim := string([]rune{os.PathSeparator})
return strings.Join(paths, delim)
}
func PathFromExecutable(paths ...string) (file string, err error) {
return getPath(
getExecPathFromArgs(paths...),
getExecPathFromCaller(0, paths...),
getExecPathFromCaller(1, paths...),
getExecPathFromSource(paths...),
)
}
func IsDir(file string) bool {
info, err := os.Stat(file)
if os.IsNotExist(err) {
return false
}
return info.IsDir()
}
func IsFile(file string) bool {
info, err := os.Stat(file)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
func getPath(fns ...PathFn) (path string, err error) {
for _, fn := range fns {
path, err = fn()
if err != nil {
continue
}
if IsFile(path) {
break
}
}
return
}
func getExecPathFromCaller(skip int, paths ...string) PathFn {
return func() (path string, err error) {
_, file, _, _ := runtime.Caller(skip)
return getAbsolutePathFromFile(file, paths...)
}
}
func getExecPathFromArgs(paths ...string) PathFn {
return func() (path string, err error) {
return getAbsolutePathFromFile(os.Args[0], paths...)
}
}
func getExecPathFromSource(paths ...string) PathFn {
return func() (path string, err error) {
return getAbsolutePathFromDir("./", paths...)
}
}
func getAbsolutePathFromFile(fromFile string, paths ...string) (path string, err error) {
dir := filepath.Dir(fromFile)
return getAbsolutePathFromDir(dir, paths...)
}
func getAbsolutePathFromDir(dir string, paths ...string) (path string, err error) {
if dir, err = filepath.Abs(dir); err != nil {
return
}
allPaths := append([]string{dir}, paths...)
path = Path(allPaths...)
return
}