-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathos.go
68 lines (56 loc) · 1.43 KB
/
os.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
package funny
import (
"io/ioutil"
"os"
"path/filepath"
"strings"
)
// BacktracePathFromCurrentDir trace path in parents dir from current dir.
// Usage: trace some path like go.mod, .git, .gitignore...
func BacktracePathFromCurrentDir(path string) (string, os.FileInfo, error) {
return BacktracePath(".", path)
}
// BacktracePath trace path in parents dir from given @from.
// Usage: trace some path like go.mod, .git, .gitignore...
func BacktracePath(from string, path string) (string, os.FileInfo, error) {
path = strings.Trim(path, "/")
from = TryGetAbsPath(from)
flagRoot := false
if TryGetAbsPath(from) == "/" {
flagRoot = true
}
items, e := ioutil.ReadDir(from)
if e != nil {
return "", nil, e
}
for _, item := range items {
if item.Name() == path {
return TryGetAbsPath(filepath.Join(from, item.Name())), item, nil
}
}
if flagRoot {
return "", nil, os.ErrNotExist
}
return BacktracePath(filepath.Join(from, ".."), path)
}
// TryGetAbsPath try to get absolute path of path but ignore the error.
// When got an error, it would return "" instead.
func TryGetAbsPath(path string) string {
if path == "" {
panic("got empty path param")
}
abs, e := filepath.Abs(path)
if e != nil {
return ""
}
return abs
}
//TryGetwd try to get current work directory and ignore the error.
// When got an error, it would return "" instead.
func TryGetwd() string {
wd, e := os.Getwd()
if e != nil {
return ""
}
return wd
}