affected-tests.mjs
11.1 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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/**
* @file 根据 Git 变更集和知识图谱选择需要执行的离线测试。
*/
import path from 'node:path'
import { spawnSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'
import { buildKnowledgeGraph } from './build-knowledge-graph.mjs'
export const FULL_TEST_ROOTS = [
'tabWorkOrder/pages/createOrder/tests',
'tests',
'packageDynamicForm/tests',
'tabIndex/tests',
'packageEquity/tests',
'tabWorkOrder/pages/refundApply/tests/refundApplyMarketing.test.mjs',
'packageDynamicForm/pages/upgradeStaffDaily/tests/dailyReportInconsistency.helpers.test.mjs',
]
const DOCS_TESTS = [
'tests/knowledge-graph/artifactsAndImpact.test.mjs',
'tests/knowledge-graph/buildKnowledgeGraph.test.mjs',
'tests/project-governance/agentDocsLayout.test.mjs',
]
const FULL_EXACT_FILES = new Set([
'app.js',
'app.json',
'package.json',
'package-lock.json',
'npm-shrinkwrap.json',
'yarn.lock',
'pnpm-lock.yaml',
])
const SHARED_ROOTS = ['components/', 'api/', 'store/', 'utils/']
const DEV_ONLY_ROOTS = ['docs/', 'scripts/', 'tests/', '.agents/', '.github/']
const KNOWLEDGE_TOOLING_ROOTS = [
'scripts/knowledge-graph/',
'tests/knowledge-graph/',
]
function compareText(left, right) {
return left < right ? -1 : left > right ? 1 : 0
}
function normalizeFiles(files) {
return [...new Set((files || []).map((file) => file.replace(/\\/g, '/').replace(/^\.\//, '')).filter(Boolean))].sort(compareText)
}
function fullPlan(changedFiles, reasons, tests) {
return {
mode: 'full',
reasons: [...new Set(reasons)].sort(compareText),
changedFiles,
domains: [],
tests,
commands: ['npm test'],
unresolved: [],
}
}
function testFiles(graph) {
return graph.nodes
.filter((node) => node.type === 'test' && node.path)
.map((node) => node.path)
.sort(compareText)
}
function nodeIdsForChangedFiles(graph, changedFiles) {
const paths = new Set(changedFiles)
return new Set(
graph.nodes
.filter((node) => node.path && paths.has(node.path))
.map((node) => node.id),
)
}
function consumerClosure(graph, seeds, depth = 3) {
const relevant = new Set(seeds)
let frontier = new Set(seeds)
for (let level = 0; level < depth; level += 1) {
const next = new Set()
for (const edge of graph.edges) {
if (!frontier.has(edge.to)) continue
if (!['imports', 'calls', 'callsApi', 'usesComponent', 'contains'].includes(edge.type)) {
continue
}
if (relevant.has(edge.from)) continue
relevant.add(edge.from)
next.add(edge.from)
}
frontier = next
if (!frontier.size) break
}
return relevant
}
function relatedTests(graph, relevantIds) {
const nodeById = new Map(graph.nodes.map((node) => [node.id, node]))
const relevantPaths = new Set(
[...relevantIds].map((id) => nodeById.get(id)?.path).filter(Boolean),
)
const tests = new Set()
for (const edge of graph.edges) {
const from = nodeById.get(edge.from)
const to = nodeById.get(edge.to)
if (to?.type !== 'test') continue
if (
relevantIds.has(edge.from) ||
relevantPaths.has(from?.path) ||
(edge.type === 'imports' && relevantIds.has(edge.to))
) {
tests.add(to.path)
}
}
for (const id of relevantIds) {
const node = nodeById.get(id)
if (node?.type === 'test') tests.add(node.path)
}
return [...tests].sort(compareText)
}
function domainsForChanges(graph, changedIds) {
const nodeById = new Map(graph.nodes.map((node) => [node.id, node]))
return [...new Set([...changedIds].map((id) => nodeById.get(id)?.domain).filter(Boolean))].sort(compareText)
}
/**
* 选择某个变更集对应的测试计划。
*
* @param {{graph: object, changedFiles: string[], forceFull?: boolean}} options 图谱、变更路径和强制全量开关。
* @returns {{mode: string, reasons: string[], changedFiles: string[], domains: string[], tests: string[], commands: string[], unresolved: object[]}} 测试计划。
*/
export function selectAffectedTests({ graph, changedFiles, forceFull = false }) {
const files = normalizeFiles(changedFiles)
const allTests = testFiles(graph)
if (forceFull) return fullPlan(files, ['forced-full'], allTests)
if (!files.length) {
return {
mode: 'none',
reasons: ['no-local-changes'],
changedFiles: [],
domains: [],
tests: [],
commands: [],
unresolved: [],
}
}
const documentationOnly = files.every((file) =>
['docs/', '.agents/'].some((root) => file.startsWith(root)),
)
if (documentationOnly) {
const knowledgeConfigChange = files.some((file) =>
file.startsWith('docs/knowledge/'),
)
return {
mode: 'docs-only',
reasons: [
knowledgeConfigChange ? 'knowledge-config-change' : 'documentation-only',
],
changedFiles: files,
domains: [],
tests: knowledgeConfigChange
? ['tests/knowledge-graph', 'tests/project-governance']
: DOCS_TESTS,
commands: ['npm run knowledge:check'],
unresolved: [],
}
}
const reasons = []
if (files.some((file) => FULL_EXACT_FILES.has(file))) reasons.push('global-entry-or-dependency')
if (files.some((file) => SHARED_ROOTS.some((root) => file.startsWith(root)))) {
reasons.push('shared-runtime-layer')
}
const changedIds = nodeIdsForChangedFiles(graph, files)
const domains = domainsForChanges(graph, changedIds)
if (domains.length > 1) reasons.push('cross-domain-change')
const unresolved = graph.unresolved.filter((item) => files.includes(item.path))
if (unresolved.length) reasons.push('unresolved-relation')
const unclassifiedRuntime = files.some((file) => {
if (DEV_ONLY_ROOTS.some((root) => file.startsWith(root))) return false
if (/\.(?:md|txt|pdf|docx)$/i.test(file)) return false
return !graph.nodes.some((node) => node.path === file && node.domain)
})
if (unclassifiedRuntime) reasons.push('unclassified-runtime-file')
if (
files.some(
(file) =>
file.startsWith('scripts/') &&
!file.startsWith('scripts/knowledge-graph/'),
)
) {
reasons.push('unclassified-tooling-file')
}
if (reasons.length) {
const plan = fullPlan(files, reasons, allTests)
plan.domains = domains
plan.unresolved = unresolved
return plan
}
const relevantIds = consumerClosure(graph, changedIds)
const targetedReasons = []
const toolingTests = []
if (
files.some((file) =>
KNOWLEDGE_TOOLING_ROOTS.some((root) => file.startsWith(root)),
)
) {
targetedReasons.push('knowledge-tooling-change')
toolingTests.push('tests/knowledge-graph')
}
if (files.some((file) => file.startsWith('.github/'))) {
targetedReasons.push('automation-config-change')
toolingTests.push('tests/project-governance')
}
if (domains.length) targetedReasons.push('page-local-change')
const selected = [
...new Set([
...relatedTests(graph, relevantIds),
...graph.nodes
.filter((node) => node.type === 'test' && domains.includes(node.domain))
.map((node) => node.path),
...toolingTests,
]),
].sort(compareText)
if (!selected.length) {
const plan = fullPlan(files, ['no-test-candidates'], allTests)
plan.domains = domains
return plan
}
return {
mode: 'targeted',
reasons: [...new Set(targetedReasons.length ? targetedReasons : ['page-local-change'])].sort(compareText),
changedFiles: files,
domains,
tests: selected,
commands: [],
unresolved: [],
}
}
function gitLines(rootDir, args) {
const result = spawnSync('git', args, { cwd: rootDir, encoding: 'utf8' })
if (result.status !== 0) throw new Error(result.stderr.trim() || `git ${args.join(' ')} failed`)
return result.stdout.split(/\r?\n/).filter(Boolean)
}
/**
* 读取本地未提交变更,或 CI 指定的 base/head 变更范围。
*
* @param {{rootDir: string, base?: string, head?: string}} options Git 根目录和可选引用。
* @returns {string[]} 固定排序的变更路径。
*/
export function readChangedFiles({ rootDir, base, head }) {
if ((base && !head) || (!base && head)) throw new Error('--base and --head must be used together')
if (base && head) {
return normalizeFiles(gitLines(rootDir, ['diff', '--no-renames', '--name-only', '--diff-filter=ACMRD', base, head]))
}
return normalizeFiles([
...gitLines(rootDir, ['diff', '--no-renames', '--name-only', '--diff-filter=ACMRD']),
...gitLines(rootDir, ['diff', '--cached', '--no-renames', '--name-only', '--diff-filter=ACMRD']),
...gitLines(rootDir, ['ls-files', '--others', '--exclude-standard']),
])
}
/**
* 从当前工作树构建 affected 专用图谱,避免受已提交生成物漂移影响。
*
* @param {string} rootDir 项目根目录。
* @returns {Promise<object>} 当前源码对应的内存图谱。
*/
export async function buildCurrentGraph(rootDir) {
return buildKnowledgeGraph({ rootDir })
}
function parseArguments(argv) {
const result = {
base: null,
head: null,
list: false,
format: 'text',
verbose: false,
full: false,
}
for (let index = 0; index < argv.length; index += 1) {
const argument = argv[index]
if (argument === '--base') result.base = argv[++index]
else if (argument === '--head') result.head = argv[++index]
else if (argument === '--list') result.list = true
else if (argument === '--format') result.format = argv[++index]
else if (argument === '--verbose') result.verbose = true
else if (argument === '--full') result.full = true
else throw new Error(`unknown argument: ${argument}`)
}
return result
}
function printPlan(plan, format) {
if (format === 'json') {
console.log(JSON.stringify(plan, null, 2))
return
}
console.log(`mode: ${plan.mode}`)
console.log(`reasons: ${plan.reasons.join(', ') || 'none'}`)
console.log(`domains: ${plan.domains.join(', ') || 'none'}`)
console.log(`tests: ${plan.tests.length}`)
for (const testFile of plan.tests) console.log(`- ${testFile}`)
}
function runNodeTests(rootDir, targets, verbose) {
if (!targets.length) return 0
const reporter = verbose ? 'spec' : 'dot'
const result = spawnSync(
process.execPath,
['--experimental-detect-module', '--test', `--test-reporter=${reporter}`, ...targets],
{ cwd: rootDir, stdio: 'inherit' },
)
return result.status ?? 1
}
async function main() {
const rootDir = process.cwd()
const options = parseArguments(process.argv.slice(2))
const graph = await buildCurrentGraph(rootDir)
const changedFiles = readChangedFiles({
rootDir,
base: options.base,
head: options.head,
})
const plan = selectAffectedTests({ graph, changedFiles, forceFull: options.full })
printPlan(plan, options.format)
if (options.list || plan.mode === 'none') return
if (plan.mode === 'docs-only') {
const check = spawnSync('npm', ['run', 'knowledge:check'], { cwd: rootDir, stdio: 'inherit', shell: process.platform === 'win32' })
if (check.status !== 0) {
process.exitCode = check.status ?? 1
return
}
}
process.exitCode = runNodeTests(
rootDir,
plan.mode === 'full' ? FULL_TEST_ROOTS : plan.tests,
options.verbose,
)
}
const isMain =
process.argv[1] &&
path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url))
if (isMain) await main()