Debian Codegraph @

internal/testutils/glob.go

raw symbols SCIP
1 package testutils
2
3 import (
4 "fmt"
5 "path/filepath"
6 "strings"
7 "testing"
8
9 "golang.org/x/sys/cpu"
10 )
11
12 // Files calls fn for each given file.
13 //
14 // The function errors out if the pattern matches no files.
15 func Files(t *testing.T, files []string, fn func(*testing.T, string)) {
16 t.Helper()
17
18 if len(files) == 0 {
19 t.Fatalf("No files given")
20 }
21
22 for _, f := range files {
23 file := f // force copy
24 name := filepath.Base(file)
25 t.Run(name, func(t *testing.T) {
26 fn(t, file)
27 })
28 }
29 }
30
31 // Glob finds files matching a pattern.
32 //
33 // The pattern should may include full path. Excludes use the same syntax as
34 // pattern, but are only applied to the basename instead of the full path.
35 func Glob(tb testing.TB, pattern string, excludes ...string) []string {
36 tb.Helper()
37
38 files, err := filepath.Glob(pattern)
39 if err != nil {
40 tb.Fatal("Can't glob files:", err)
41 }
42
43 if len(excludes) == 0 {
44 return files
45 }
46
47 var filtered []string
48 nextFile:
49 for _, file := range files {
50 base := filepath.Base(file)
51 for _, exclude := range excludes {
52 if matched, err := filepath.Match(exclude, base); err != nil {
53 tb.Fatal(err)
54 } else if matched {
55 continue nextFile
56 }
57 }
58 filtered = append(filtered, file)
59 }
60
61 return filtered
62 }
63
64 // NativeFile substitutes %s with an abbreviation of the host endianness.
65 func NativeFile(tb testing.TB, path string) string {
66 tb.Helper()
67
68 if !strings.Contains(path, "%s") {
69 tb.Fatalf("File %q doesn't contain %%s", path)
70 }
71
72 if cpu.IsBigEndian {
73 return fmt.Sprintf(path, "eb")
74 }
75
76 return fmt.Sprintf(path, "el")
77 }