Repository navigation
Expand file tree
/
Copy pathtest-selection.ts
More file actions
164 lines (152 loc) · 5.43 KB
/
Copy pathtest-selection.ts
File metadata and controls
164 lines (152 loc) · 5.43 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
/**
* Test-selection heuristic for the `run_tests` tool.
*
* Deliberately simple — the goal is "much better than always running the
* full suite during the iterative edit-check-edit loop", not a perfect
* solver:
*
* 1. Direct match: `src/foo/bar.ts` changed → `src/foo/__tests__/bar.test.ts`
* if it exists (this repo's test-file convention). A changed file that
* IS itself a test runs itself.
* 2. Reverse-dependency match: reuse the REAL import graph
* (src/codeintel/import-graph.ts — the same resolution the `import_graph`
* tool uses, correct on `paths` aliases and extension resolution) to find
* which files import the changed file — directly (1 hop) or through one
* intermediate module (2 hops, the common "lib → helper → test" case).
* Any importer that is a test file is selected.
* 3. No match → the caller reports "no specific tests matched — consider
* running the full suite" rather than silently running nothing.
*
* A source file's own direct test wins over reverse-dependency matches for
* determinism; everything is deduped and sorted for stable output.
*/
import * as fs from "node:fs"
import * as path from "node:path"
import { getImportGraph } from "../codeintel/import-graph.js"
import type { CodeIntel } from "../codeintel/program.js"
/** True for `foo.test.ts` / `foo.spec.tsx` style names, or any file inside a `__tests__` dir. */
export function isTestFile(relPath: string): boolean {
const normalized = relPath.split(path.sep).join("/")
if (/(^|\/)__tests__(\/|$)/.test(normalized)) {
return true
}
return /[^/]+\.(test|spec)\.(m|c)?[tj]sx?$/i.test(normalized)
}
/**
* Direct match for a changed source file: `src/foo/bar.ts` →
* `src/foo/__tests__/bar.test.ts`. Only applies to source extensions the
* project can test (TS/JS); returns undefined for everything else (scripts,
* config, docs — those have no per-file test to run directly).
*/
export function directTestMatch(relSource: string): string | undefined {
const normalized = relSource.split(path.sep).join("/")
if (!/\.(m|c)?[tj]sx?$/i.test(normalized)) {
return undefined
}
const dir = path.posix.dirname(normalized)
const base = path.posix.basename(normalized).replace(/\.(m|c)?[tj]sx?$/i, "")
// Never map a test file onto a sibling test (it already matched itself).
if (isTestFile(normalized)) {
return undefined
}
return `${dir}/__tests__/${base}.test.ts`
}
/**
* Reverse-dependency match: every TEST file that (transitively, up to
* `maxDepth` hops) imports the changed file, per the real import graph.
* `absTarget` is the changed file's absolute path.
*/
export function reverseDependencyTests(
intel: CodeIntel,
workspaceRoot: string,
absTarget: string,
maxDepth = 2,
): string[] {
const graph = getImportGraph(intel)
const found: string[] = []
const seenFiles = new Set<string>([absTarget])
// BFS from the changed file along reverse import edges (`importedBy`).
let frontier = [absTarget]
for (let depth = 0; depth < maxDepth && frontier.length > 0; depth++) {
const next: string[] = []
for (const file of frontier) {
for (const importer of graph.importedBy.get(file) ?? []) {
if (seenFiles.has(importer)) {
continue
}
seenFiles.add(importer)
const rel = path.relative(workspaceRoot, importer).split(path.sep).join("/")
if (isTestFile(rel)) {
found.push(rel)
}
next.push(importer)
}
}
frontier = next
}
return found
}
export interface TestSelectionResult {
/** Selected test files, workspace-relative posix paths, sorted + deduped. */
tests: string[]
/** Human-readable notes on WHY each file was selected (for the tool result). */
notes: string[]
}
/**
* Select the test file(s) to run for a set of changed workspace-relative
* files. Returns an empty `tests` list (with a note) when nothing matches —
* the caller must report the fail-safe "no specific tests matched" instead
* of pretending zero tests ran. `intel` may be undefined when the caller
* already knows every file matches directly; the reverse-dependency tier is
* then skipped (review gates, #137).
*/
export function selectTestsForChangedFiles(
intel: CodeIntel | undefined,
workspaceRoot: string,
changedFiles: string[],
): TestSelectionResult {
const tests = new Set<string>()
const notes: string[] = []
const seenNotes = new Set<string>()
const note = (text: string): void => {
if (!seenNotes.has(text)) {
seenNotes.add(text)
notes.push(text)
}
}
for (const rel of changedFiles) {
const normalized = rel.split(path.sep).join("/")
if (isTestFile(normalized)) {
tests.add(normalized)
note(`direct: ${normalized} is itself a test file`)
continue
}
const direct = directTestMatch(normalized)
if (direct !== undefined && fileExists(path.join(workspaceRoot, direct))) {
tests.add(direct)
note(`direct: ${normalized} changed → ${direct}`)
continue
}
const abs = path.resolve(workspaceRoot, normalized)
const reverse = intel === undefined
? []
: reverseDependencyTests(intel, workspaceRoot, abs)
if (reverse.length > 0) {
for (const t of reverse) {
tests.add(t)
}
note(`reverse-dependency: ${normalized} is imported by ${reverse.join(", ")}`)
continue
}
note(`no test matched ${normalized} (no direct test, no test imports it)`)
}
const sorted = [...tests].sort()
return { tests: sorted, notes }
}
function fileExists(p: string): boolean {
try {
return fs.statSync(p).isFile()
} catch {
return false
}
}