-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathgit_isolation_guard_test.go
More file actions
284 lines (261 loc) · 6.82 KB
/
Copy pathgit_isolation_guard_test.go
File metadata and controls
284 lines (261 loc) · 6.82 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"io/fs"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type gitIsolationPackage struct {
dir string
hasIsolatedTestMain bool
gitEvidence []string
}
func TestGitUsingTestPackagesUseIsolatedTestMain(t *testing.T) {
root := repoRootFromWorkingDir(t)
packages := map[string]*gitIsolationPackage{}
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if d.IsDir() {
if path != root && shouldSkipWalkDir(d.Name()) {
return filepath.SkipDir
}
return nil
}
if !strings.HasSuffix(path, "_test.go") {
return nil
}
relPath, err := filepath.Rel(root, path)
if err != nil {
return err
}
relDir := filepath.Dir(relPath)
if relDir == "." {
relDir = ""
}
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, path, nil, 0)
if err != nil {
return fmt.Errorf("parse %s: %w", relPath, err)
}
pkg := packages[relDir]
if pkg == nil {
pkg = &gitIsolationPackage{dir: relDir}
packages[relDir] = pkg
}
imports := importAliases(file)
if testFileCallsIsolatedMain(file, imports["go.kenn.io/roborev/internal/testenv"]) {
pkg.hasIsolatedTestMain = true
}
pkg.gitEvidence = append(pkg.gitEvidence, testFileGitUsage(
file,
fset,
relPath,
imports["os/exec"],
imports["go.kenn.io/roborev/internal/testutil"],
)...)
return nil
})
require.NoError(t, err)
var missing []string
for _, pkg := range packages {
if len(pkg.gitEvidence) == 0 || pkg.hasIsolatedTestMain {
continue
}
dir := pkg.dir
if dir == "" {
dir = "."
}
missing = append(missing, fmt.Sprintf("%s: %s", dir, pkg.gitEvidence[0]))
}
sort.Strings(missing)
require.Empty(t, missing, "Git-using test packages must call testenv.RunIsolatedMain in TestMain:\n%s", strings.Join(missing, "\n"))
}
// shouldSkipWalkDir reports whether the repository walk should skip a directory
// instead of descending into it. The go tool ignores directories whose names
// begin with "." or "_" and any directory named "testdata"; none of those hold
// buildable packages. We additionally skip dependency and build caches that can
// contain third-party *_test.go files (for example the module cache under
// .gocache or agent worktrees under .claude/worktrees), which are not part of
// this repository's own source tree.
func shouldSkipWalkDir(name string) bool {
if name == "testdata" {
return true
}
if strings.HasPrefix(name, ".") || strings.HasPrefix(name, "_") {
return true
}
switch name {
case "bin", "node_modules", "tmp", "vendor":
return true
default:
return false
}
}
func TestShouldSkipWalkDir(t *testing.T) {
assert := assert.New(t)
skip := []string{
".git", ".direnv", ".claude", ".gocache", ".github", ".ruff_cache",
"_build", "testdata", "bin", "node_modules", "tmp", "vendor",
}
keep := []string{"cmd", "internal", "scripts", "agent", "daemon", "git", "roborev"}
for _, name := range skip {
assert.True(shouldSkipWalkDir(name), "expected %q to be skipped", name)
}
for _, name := range keep {
assert.False(shouldSkipWalkDir(name), "expected %q to be walked", name)
}
}
func repoRootFromWorkingDir(t *testing.T) string {
t.Helper()
dir, err := os.Getwd()
require.NoError(t, err)
for {
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
return dir
}
parent := filepath.Dir(dir)
require.NotEqual(t, dir, parent, "could not find repo root from %s", dir)
dir = parent
}
}
func importAliases(file *ast.File) map[string]map[string]bool {
aliases := map[string]map[string]bool{}
for _, spec := range file.Imports {
importPath, err := strconv.Unquote(spec.Path.Value)
if err != nil {
continue
}
name := defaultImportName(importPath)
if spec.Name != nil {
name = spec.Name.Name
}
if name == "_" || name == "." {
continue
}
if aliases[importPath] == nil {
aliases[importPath] = map[string]bool{}
}
aliases[importPath][name] = true
}
return aliases
}
func defaultImportName(importPath string) string {
idx := strings.LastIndex(importPath, "/")
if idx == -1 {
return importPath
}
return importPath[idx+1:]
}
func testFileCallsIsolatedMain(file *ast.File, testenvAliases map[string]bool) bool {
if len(testenvAliases) == 0 {
return false
}
for _, decl := range file.Decls {
fn, ok := decl.(*ast.FuncDecl)
if !ok || fn.Name.Name != "TestMain" || fn.Body == nil {
continue
}
found := false
ast.Inspect(fn.Body, func(node ast.Node) bool {
call, ok := node.(*ast.CallExpr)
if !ok {
return true
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok || sel.Sel.Name != "RunIsolatedMain" {
return true
}
ident, ok := sel.X.(*ast.Ident)
if ok && testenvAliases[ident.Name] {
found = true
return false
}
return true
})
if found {
return true
}
}
return false
}
func testFileGitUsage(file *ast.File, fset *token.FileSet, relPath string, execAliases, testutilAliases map[string]bool) []string {
if len(execAliases) == 0 && len(testutilAliases) == 0 {
return nil
}
var evidence []string
ast.Inspect(file, func(node ast.Node) bool {
call, ok := node.(*ast.CallExpr)
if !ok {
return true
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
return true
}
ident, ok := sel.X.(*ast.Ident)
if !ok {
return true
}
switch {
case execAliases[ident.Name] && gitCommandCall(sel.Sel.Name, call.Args):
evidence = append(evidence, fmt.Sprintf("%s:%d runs git via os/exec", relPath, fset.Position(call.Pos()).Line))
case testutilAliases[ident.Name] && testutilGitHelper(sel.Sel.Name):
evidence = append(evidence, fmt.Sprintf("%s:%d uses testutil.%s", relPath, fset.Position(call.Pos()).Line, sel.Sel.Name))
}
return true
})
ast.Inspect(file, func(node ast.Node) bool {
call, ok := node.(*ast.CallExpr)
if !ok {
return true
}
ident, ok := call.Fun.(*ast.Ident)
if ok && testutilGitHelper(ident.Name) {
evidence = append(evidence, fmt.Sprintf("%s:%d uses %s", relPath, fset.Position(call.Pos()).Line, ident.Name))
}
return true
})
return evidence
}
func gitCommandCall(name string, args []ast.Expr) bool {
var commandArg ast.Expr
switch name {
case "Command":
if len(args) == 0 {
return false
}
commandArg = args[0]
case "CommandContext":
if len(args) < 2 {
return false
}
commandArg = args[1]
default:
return false
}
lit, ok := commandArg.(*ast.BasicLit)
if !ok || lit.Kind != token.STRING {
return false
}
value, err := strconv.Unquote(lit.Value)
return err == nil && value == "git"
}
func testutilGitHelper(name string) bool {
switch name {
case "GetHeadSHA", "InitTestGitRepo", "InitTestRepo", "NewGitRepo", "NewTestRepo", "NewTestRepoWithCommit":
return true
default:
return false
}
}