affected-tests.js 5.86 KB
const fs = require("node:fs");
const path = require("node:path");
const process = require("node:process");

const GLOBAL_FILES = new Set([
	"package.json",
	"package-lock.json",
	"babel.config.js",
	"jest.config.js",
	"vue.config.js",
	"eslint.config.js",
	"src/main.js",
	"src/router/index.js",
	"src/router/routes.js",
	"src/store/index.js",
	"src/api/request.js",
]);
const GLOBAL_PREFIXES = [
	"src/components/",
	"src/libs/",
	"src/common/",
	"src/plugin/",
	"src/store/modules/d2admin/",
];

function isRuntimeFile(filePath) {
	return /^src\/.*\.(?:js|vue)$/.test(filePath);
}

function isKnowledgeOnly(filePath) {
	return /^\.ai\/(?:docs\/knowledge|knowledge|generated)\//.test(filePath)
		|| /^\.ai\/skills\/requirement-impact-analysis\//.test(filePath)
		|| /^scripts\/knowledge-graph\//.test(filePath)
		|| filePath.endsWith(".md")
		|| filePath === ".gitlab-ci.yml"
		|| filePath === "AGENTS.md"
		|| filePath === "README.md";
}

function uniqueSorted(values) {
	return [...new Set(values)].sort((left, right) => left.localeCompare(right, "en"));
}

function inferDomains(graph, changedFiles) {
	const result = new Set(graph.nodes
		.filter(node => node.path && changedFiles.includes(node.path))
		.flatMap(node => node.domainIds || []));
	for (const node of graph.nodes.filter(item => item.type === "domain")) {
		const entrypoints = [...(node.meta?.entrypoints || []), ...(node.meta?.roots || [])];
		if (changedFiles.some(file => file === node.path
			|| entrypoints.some(entrypoint => file === entrypoint || file.startsWith(`${entrypoint}/`)))) {
			result.add(node.id.slice("domain:".length));
		}
	}
	return uniqueSorted(result);
}

function relatedNodes(graph, startIds, maxDepth = 4) {
	const visited = new Set(startIds);
	let frontier = [...startIds];
	for (let depth = 0; depth < maxDepth && frontier.length; depth += 1) {
		const next = [];
		for (const edge of graph.edges) {
			if (frontier.includes(edge.from) && !visited.has(edge.to)) {
				visited.add(edge.to);
				next.push(edge.to);
			}
			if (frontier.includes(edge.to) && !visited.has(edge.from)) {
				visited.add(edge.from);
				next.push(edge.from);
			}
		}
		frontier = next;
	}
	return visited;
}

function targetedCommand(testFiles, verbose) {
	const reporter = verbose ? " --verbose" : "";
	return `npm run test:unit -- --runTestsByPath ${testFiles.map(file => `"${file}"`).join(" ")}${reporter}`;
}

function planAffectedTests(options) {
	const rootDir = path.resolve(options.rootDir || process.cwd());
	const graph = options.graph;
	const changedFiles = uniqueSorted((options.changedFiles || []).map(file => file.replace(/\\/g, "/")));
	const deletedFiles = new Set((options.deletedFiles || []).map(file => file.replace(/\\/g, "/")));
	const renamedFiles = new Set((options.renamedFiles || []).map(file => file.replace(/\\/g, "/")));
	const reasons = [];

	if (options.full) {
		reasons.push("forced-full");
	}
	if (changedFiles.some(file => deletedFiles.has(file) && isRuntimeFile(file))) {
		reasons.push("deleted-runtime-file");
	}
	if (changedFiles.some(file => renamedFiles.has(file) && isRuntimeFile(file))) {
		reasons.push("renamed-runtime-file");
	}
	if (changedFiles.some(file => GLOBAL_FILES.has(file) || GLOBAL_PREFIXES.some(prefix => file.startsWith(prefix)))) {
		reasons.push("global-infrastructure");
	}
	if (reasons.length) {
		return {
			mode: "full",
			changedFiles,
			reasons: uniqueSorted(reasons),
			domains: [],
			testFiles: [],
			commands: ["npm run test:unit -- --ci"],
		};
	}

	if (changedFiles.length && changedFiles.every(isKnowledgeOnly)) {
		return {
			mode: "knowledge-only",
			changedFiles,
			reasons: ["knowledge-only-change"],
			domains: [],
			testFiles: [],
			commands: ["npm run knowledge:test", "npm run knowledge:check"],
		};
	}
	const changedTestFiles = changedFiles
		.filter(file => /\.(?:spec|test)\.js$/.test(file) && fs.existsSync(path.join(rootDir, file)));
	if (changedFiles.length && changedTestFiles.length === changedFiles.length) {
		return {
			mode: "targeted",
			changedFiles,
			reasons: ["changed-tests-only"],
			domains: inferDomains(graph, changedFiles),
			testFiles: changedTestFiles,
			commands: [targetedCommand(changedTestFiles, options.verbose)],
		};
	}

	const changedNodes = graph.nodes.filter(node => node.path && changedFiles.includes(node.path));
	const domains = inferDomains(graph, changedFiles);
	if (domains.length >= 3) {
		return {
			mode: "full",
			changedFiles,
			reasons: ["cross-domain-change"],
			domains,
			testFiles: [],
			commands: ["npm run test:unit -- --ci"],
		};
	}
	const unresolvedChanged = graph.unresolved.some(item => changedFiles.includes(item.path));
	if (unresolvedChanged) {
		return {
			mode: "full",
			changedFiles,
			reasons: ["unresolved-change"],
			domains,
			testFiles: [],
			commands: ["npm run test:unit -- --ci"],
		};
	}

	const startIds = changedNodes.map(node => node.id);
	const related = relatedNodes(graph, startIds);
	const graphTestFiles = uniqueSorted(graph.nodes
		.filter(node => node.type === "test" && related.has(node.id))
		.map(node => node.path));
	const standardTestFiles = uniqueSorted(options.standardTestFiles || []);
	const testFiles = uniqueSorted([...graphTestFiles, ...standardTestFiles]);
	const runtimeChanges = changedFiles.filter(isRuntimeFile);
	if (runtimeChanges.length && (!domains.length || !testFiles.length)) {
		return {
			mode: "full",
			changedFiles,
			reasons: ["runtime-change-without-tests"],
			domains,
			testFiles: [],
			commands: ["npm run test:unit -- --ci"],
		};
	}
	const directTests = changedTestFiles;
	const selectedTests = uniqueSorted([...testFiles, ...directTests]);
	return {
		mode: selectedTests.length ? "targeted" : "none",
		changedFiles,
		reasons: selectedTests.length ? ["related-tests-found"] : ["no-runtime-change"],
		domains,
		testFiles: selectedTests,
		commands: selectedTests.length ? [targetedCommand(selectedTests, options.verbose)] : [],
	};
}

module.exports = {
	planAffectedTests,
};