review-trigger.mjs 2.18 KB
#!/usr/bin/env node

import childProcess from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import process from "node:process";

import { requireWorkspaceRoot } from "./workspace-root.mjs";

const repoRoot = requireWorkspaceRoot();
const config = JSON.parse(fs.readFileSync(path.join(repoRoot, "tools", "review-trigger", "config.json"), "utf8"));
const changedFiles = resolveChangedFiles();

if (changedFiles.length === 0) {
	console.log("[review-trigger] no changed files detected");
	process.exit(0);
}

const highRiskFiles = changedFiles.filter((file) => matchesAny(file, config.highRiskPaths));
if (highRiskFiles.length === 0) {
	console.log("[review-trigger] no high-risk files changed");
	process.exit(0);
}

const evidenceFiles = changedFiles.filter((file) => matchesAny(file, config.evidencePaths));
const payload = {
	status: evidenceFiles.length > 0 ? "passed" : "failed",
	changedFiles,
	highRiskFiles,
	evidenceFiles,
};

console.log(JSON.stringify(payload, null, 2));
process.exit(evidenceFiles.length > 0 ? 0 : 2);

function resolveChangedFiles() {
	const fromArgs = process.argv.slice(2).filter(Boolean);
	if (fromArgs.length > 0) {
		return normalize(fromArgs);
	}

	const combined = [
		...runGit("git diff --name-only"),
		...runGit("git diff --cached --name-only"),
		...runGit("git ls-files --others --exclude-standard"),
	];
	if (combined.length > 0) {
		return normalize(combined);
	}

	return normalize(runGit("git diff --name-only HEAD~1 HEAD"));
}

function runGit(command) {
	const result = childProcess.spawnSync(command, {
		cwd: repoRoot,
		shell: true,
		encoding: "utf8",
	});

	if (result.status !== 0 || !result.stdout) {
		return [];
	}

	return result.stdout.split(/\r?\n/).filter(Boolean);
}

function normalize(files) {
	return [...new Set(files.map((file) => file.replaceAll("\\", "/")))];
}

function matchesAny(file, patterns) {
	return patterns.some((pattern) => matchPattern(file, pattern));
}

function matchPattern(file, pattern) {
	const normalizedPattern = pattern.replaceAll("\\", "/");
	if (normalizedPattern.endsWith("/")) {
		return file.startsWith(normalizedPattern);
	}
	return file === normalizedPattern || file.startsWith(`${normalizedPattern}/`);
}