-
Notifications
You must be signed in to change notification settings - Fork 0
/
filepathx.go
65 lines (54 loc) · 1.43 KB
/
filepathx.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
package gdk
import (
"fmt"
"io/ioutil"
"path/filepath"
)
const maxRecursive = 100
// FindProjectAbs find absolute path that have go.mod in parent folder.
func FindProjectAbs() (string, error) {
p, err := filepath.Abs(".")
if err != nil {
return "", fmt.Errorf(
"can't find go.mod in parent ancestor: cannot find absolute path of '.'",
)
}
return findProjectAbs(p, 0)
}
func findProjectAbs(currentPath string, recursive int) (string, error) {
// Prevent too much recursive that can create deadlock.
if recursive > maxRecursive {
return "", fmt.Errorf(
"can't find go.mod in parent ancestor: '%s' nested more than %d level",
currentPath,
maxRecursive,
)
}
// Check if current path is already project root.
if currentPath == "/" {
return "", fmt.Errorf("can't find go.mod in parent ancestor")
}
files, err := ioutil.ReadDir(currentPath)
if err != nil {
return "", fmt.Errorf(
"can't find go.mod in parent ancestor: cannot read in '%s'",
currentPath,
)
}
for _, f := range files {
if f.Name() == "go.mod" {
return currentPath, nil
}
}
newPath, err := filepath.Abs(currentPath + "/../")
if err != nil {
return "", fmt.Errorf(
"can't find go.mod in parent ancestor: cannot find absolute path of %s",
currentPath+"/../",
)
}
if currentPath == newPath {
return "", fmt.Errorf("can't find go.mod in parent ancestor: stuck in %s", newPath)
}
return findProjectAbs(newPath, recursive+1)
}