Skip to content

Commit 9d62b0a

Browse files
authored
feat: find file via file system search (#157)
1 parent f5435e9 commit 9d62b0a

File tree

1 file changed

+56
-2
lines changed

1 file changed

+56
-2
lines changed

pkg/testcoverage/coverage/cover.go

Lines changed: 56 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,8 +121,10 @@ func findFiles(profiles []*cover.Profile, prefix string) (map[string]fileInfo, e
121121
return result, nil
122122
}
123123

124-
func findFileCreator() func(file, prefix string) (string, string, bool) {
124+
//nolint:maintidx // relax
125+
func findFileCreator() func(file, prefix string) (string, string, bool) { // coverage-ignore
125126
cache := make(map[string]*build.Package)
127+
files := []string(nil)
126128

127129
findRelative := func(file, prefix string) (string, string, bool) {
128130
noPrefixName := stripPrefix(file, prefix)
@@ -153,8 +155,23 @@ func findFileCreator() func(file, prefix string) (string, string, bool) {
153155
return file, noPrefixName, err == nil
154156
}
155157

158+
findWalk := func(file, prefix string) (string, string, bool) {
159+
if files == nil {
160+
files = listAllFiles("./")
161+
}
162+
163+
noPrefixName := stripPrefix(file, prefix)
164+
f, found := hasFile(files, noPrefixName)
165+
166+
return path.NormalizeForOS(f), noPrefixName, found
167+
}
168+
156169
return func(file, prefix string) (string, string, bool) {
157-
if fPath, fNoPrefix, found := findRelative(file, prefix); found { // coverage-ignore
170+
if fPath, fNoPrefix, found := findRelative(file, prefix); found {
171+
return fPath, fNoPrefix, found
172+
}
173+
174+
if fPath, fNoPrefix, found := findWalk(file, prefix); found {
158175
return fPath, fNoPrefix, found
159176
}
160177

@@ -166,6 +183,43 @@ func findFileCreator() func(file, prefix string) (string, string, bool) {
166183
}
167184
}
168185

186+
func listAllFiles(rootDir string) []string {
187+
var files []string
188+
189+
//nolint:errcheck // error ignored because there is fallback mechanism for finding files
190+
filepath.Walk(rootDir, func(file string, info os.FileInfo, err error) error {
191+
if err != nil { // coverage-ignore
192+
return err
193+
}
194+
195+
if !info.IsDir() &&
196+
strings.HasSuffix(file, ".go") &&
197+
!strings.HasSuffix(file, "_test.go") {
198+
files = append(files, path.NormalizeForTool(file))
199+
}
200+
201+
return nil
202+
})
203+
204+
return files
205+
}
206+
207+
func hasFile(files []string, search string) (string, bool) {
208+
var result string
209+
210+
for _, f := range files {
211+
if strings.HasSuffix(f, search) {
212+
if result != "" {
213+
return "", false
214+
}
215+
216+
result = f
217+
}
218+
}
219+
220+
return result, result != ""
221+
}
222+
169223
func findAnnotations(source []byte) ([]extent, error) {
170224
fset := token.NewFileSet()
171225

0 commit comments

Comments
 (0)