-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtesting.go
More file actions
102 lines (80 loc) · 1.96 KB
/
testing.go
File metadata and controls
102 lines (80 loc) · 1.96 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
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 utils
import (
"os"
"path/filepath"
"sync"
"testing"
)
func FindFile(tb testing.TB, fileName string) string {
tb.Helper()
workingDir := WorkingDir(tb)
root := ProjectRootDir(tb)
for entries, err := os.ReadDir(workingDir); err == nil; {
for _, entry := range entries {
if entry.Name() == fileName {
return workingDir
}
}
if workingDir == root {
tb.Error("got to he project root, file not found")
tb.FailNow()
}
workingDir, err = GetAbsolutePath(filepath.Join(workingDir, ".."))
if err != nil {
tb.Errorf("failed to get absolute path from %s", filepath.Join(workingDir, ".."))
tb.FailNow()
}
entries, err = os.ReadDir(workingDir)
}
tb.Errorf("failed to find file %s", fileName)
tb.FailNow()
return ""
}
var (
projectRootDirCache = make(map[string]string, 10)
projectRootDirCacheMu sync.RWMutex
)
const gomod = "go.mod"
func ProjectRootDir(tb testing.TB) string {
tb.Helper()
originalWorkingDir := WorkingDir(tb)
workingDir := originalWorkingDir
projectRootDirCacheMu.RLock()
if dir, ok := projectRootDirCache[originalWorkingDir]; ok {
projectRootDirCacheMu.RUnlock()
return dir
}
projectRootDirCacheMu.RUnlock()
for entries, err := os.ReadDir(workingDir); err == nil; {
for _, entry := range entries {
if entry.Name() == gomod {
projectRootDirCacheMu.Lock()
projectRootDirCache[originalWorkingDir] = workingDir
projectRootDirCacheMu.Unlock()
return workingDir
}
}
if workingDir == "/" {
tb.Error("got to FS Root, file not found")
tb.FailNow()
}
workingDir, err = GetAbsolutePath(filepath.Join(workingDir, ".."))
if err != nil {
tb.Errorf("failed to get absolute path from %s", filepath.Join(workingDir, ".."))
tb.FailNow()
}
entries, err = os.ReadDir(workingDir)
}
tb.Errorf("%s not found", gomod)
tb.FailNow()
return ""
}
func WorkingDir(tb testing.TB) string {
tb.Helper()
wd, err := os.Getwd()
if err != nil {
tb.Error(err)
tb.FailNow()
}
return wd
}