forked from golangci/golangci-lint
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfsutils.go
102 lines (83 loc) · 1.99 KB
/
fsutils.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
97
98
99
100
101
102
package fsutils
import (
"fmt"
"os"
"path/filepath"
"sync"
)
func IsDir(filename string) bool {
fi, err := os.Stat(filename)
return err == nil && fi.IsDir()
}
var (
cachedWd string
cachedWdError error
getWdOnce sync.Once
useCache = true
)
func UseWdCache(use bool) {
useCache = use
}
func Getwd() (string, error) {
if !useCache { // for tests
return os.Getwd()
}
getWdOnce.Do(func() {
cachedWd, cachedWdError = os.Getwd()
if cachedWdError != nil {
return
}
evaluatedWd, err := EvalSymlinks(cachedWd)
if err != nil {
cachedWd, cachedWdError = "", fmt.Errorf("can't eval symlinks on wd %s: %w", cachedWd, err)
return
}
cachedWd = evaluatedWd
})
return cachedWd, cachedWdError
}
var evalSymlinkCache sync.Map
type evalSymlinkRes struct {
path string
err error
}
func EvalSymlinks(path string) (string, error) {
r, ok := evalSymlinkCache.Load(path)
if ok {
er := r.(evalSymlinkRes)
return er.path, er.err
}
var er evalSymlinkRes
er.path, er.err = evalSymlinks(path)
evalSymlinkCache.Store(path, er)
return er.path, er.err
}
func ShortestRelPath(path, wd string) (string, error) {
if wd == "" { // get it if user don't have cached working dir
var err error
wd, err = Getwd()
if err != nil {
return "", fmt.Errorf("can't get working directory: %w", err)
}
}
evaledPath, err := EvalSymlinks(path)
if err != nil {
return "", fmt.Errorf("can't eval symlinks for path %s: %w", path, err)
}
path = evaledPath
// make path absolute and then relative to be able to fix this case:
// we are in `/test` dir, we want to normalize `../test`, and have file `file.go` in this dir;
// it must have normalized path `file.go`, not `../test/file.go`,
var absPath string
if filepath.IsAbs(path) {
absPath = path
} else {
absPath = filepath.Join(wd, path)
}
relPath, err := filepath.Rel(wd, absPath)
if err != nil {
return "", fmt.Errorf("can't get relative path for path %s and root %s: %w",
absPath, wd, err)
}
return relPath, nil
}