| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379 |
- // 目录扫描与文件比较:把两个项目目录按相对路径对齐,判断 新增/修改/删除/重命名/未变。
- // 全程只读,不写被比较的目录。
- import fs from "node:fs";
- import fsp from "node:fs/promises";
- import path from "node:path";
- import crypto from "node:crypto";
- import { buildRows, splitLinesForDiff } from "./diff.mjs";
- // 默认忽略:构建产物、依赖、IDE、版本库、以及明显不是源码的二进制。
- export const DEFAULT_IGNORE = [
- ".git/",
- ".idea/",
- ".codex_backup/",
- ".claude/",
- "node_modules/",
- "out/",
- "outputs/",
- "release/",
- "tmp/",
- "web/WEB-INF/classes/",
- "web/WEB-INF/lib/",
- "*.class",
- "*.jar",
- "*.war",
- "*.zip",
- "*.exe",
- "*.dll",
- "*.so",
- "*.log",
- "*.iml",
- ".DS_Store",
- "Thumbs.db",
- ];
- // 这些是“构建产物/依赖”类目录,用开关单独控制:默认忽略,勾选后参与比较。
- export const BUILD_IGNORE = [
- "out/",
- "outputs/",
- "release/",
- "tmp/",
- "node_modules/",
- "web/WEB-INF/classes/",
- "web/WEB-INF/lib/",
- "*.class",
- "*.jar",
- "*.war",
- "*.zip",
- ];
- const RENAME_SIMILARITY = 0.5;
- const STAT_MAX_BYTES = 1.5 * 1024 * 1024;
- export function toRel(root, abs) {
- return path.relative(root, abs).split(path.sep).join("/");
- }
- export function isIgnored(rel, isDir, rules) {
- for (const raw of rules) {
- const rule = raw.trim();
- if (!rule) continue;
- if (rule.endsWith("/")) {
- const seg = rule.slice(0, -1);
- if (rel === seg || rel.endsWith("/" + seg) || rel.includes("/" + seg + "/")) return true;
- } else if (rule.startsWith("*.")) {
- const ext = rule.slice(1).toLowerCase();
- if (rel.toLowerCase().endsWith(ext)) return true;
- } else if (rel === rule || rel.startsWith(rule + "/")) {
- return true;
- }
- }
- return false;
- }
- function effectiveIgnore(options = {}) {
- const rules = options.ignore ?? DEFAULT_IGNORE;
- if (!options.includeBuild) return rules;
- return rules.filter((r) => !BUILD_IGNORE.includes(r));
- }
- export function assertDirectory(dir) {
- if (!dir) throw new Error("目录为空");
- const resolved = path.resolve(dir);
- const st = fs.statSync(resolved, { throwIfNoEntry: false });
- if (!st || !st.isDirectory()) throw new Error("目录不存在或不是目录:" + resolved);
- return resolved;
- }
- export function walk(root, options = {}) {
- const rules = effectiveIgnore(options);
- const out = new Map();
- const stack = [root];
- while (stack.length > 0) {
- const dir = stack.pop();
- let entries;
- try {
- entries = fs.readdirSync(dir, { withFileTypes: true });
- } catch {
- continue;
- }
- for (const entry of entries) {
- const abs = path.join(dir, entry.name);
- const rel = toRel(root, abs);
- const isDir = entry.isDirectory();
- if (isIgnored(rel, isDir, rules)) continue;
- if (entry.isSymbolicLink()) continue;
- if (isDir) {
- stack.push(abs);
- continue;
- }
- if (!entry.isFile()) continue;
- let st;
- try {
- st = fs.statSync(abs);
- } catch {
- continue;
- }
- out.set(rel, { rel, abs, size: st.size, mtimeMs: Math.round(st.mtimeMs) });
- }
- }
- return out;
- }
- const gbkDecoder = new TextDecoder("gb18030");
- const utf8DecoderStrict = new TextDecoder("utf-8", { fatal: true });
- function hasBinaryByte(buf) {
- const limit = Math.min(buf.length, 8192);
- for (let i = 0; i < limit; i++) {
- if (buf[i] === 0) return true;
- }
- return false;
- }
- /**
- * 文本解码:优先 UTF-8,失败回退 GB18030(老 JSP/配置里有 GBK 内容)。
- * 二进制返回 null。
- */
- export function decodeBuffer(buf) {
- if (hasBinaryByte(buf)) return null;
- try {
- return { text: utf8DecoderStrict.decode(buf), encoding: "utf-8" };
- } catch {
- return { text: gbkDecoder.decode(buf), encoding: "gb18030" };
- }
- }
- export async function readText(abs, maxBytes = 8 * 1024 * 1024) {
- const st = await fsp.stat(abs);
- if (st.size > maxBytes) return { tooLarge: true, size: st.size };
- const buf = await fsp.readFile(abs);
- const decoded = decodeBuffer(buf);
- if (!decoded) return { binary: true, size: st.size };
- return { text: decoded.text, encoding: decoded.encoding, size: st.size };
- }
- function sha256(abs) {
- return new Promise((resolve, reject) => {
- const hash = crypto.createHash("sha256");
- const stream = fs.createReadStream(abs);
- stream.on("data", (chunk) => hash.update(chunk));
- stream.on("error", reject);
- stream.on("end", () => resolve(hash.digest("hex")));
- });
- }
- function lineSignature(text) {
- const set = new Set();
- for (const line of splitLinesForDiff(text).lines) {
- const trimmed = line.trim();
- if (trimmed.length === 0 || trimmed.length > 240) continue;
- set.add(trimmed);
- }
- return set;
- }
- function jaccard(a, b) {
- if (a.size === 0 || b.size === 0) return 0;
- let inter = 0;
- const [small, large] = a.size <= b.size ? [a, b] : [b, a];
- for (const item of small) {
- if (large.has(item)) inter++;
- }
- const union = a.size + b.size - inter;
- return union === 0 ? 0 : inter / union;
- }
- /**
- * 扫描两个目录,返回逐文件状态。
- * options: { ignore, includeBuild, withStats }
- */
- export async function scanProjects(baseRoot, targetRoot, options = {}) {
- const base = assertDirectory(baseRoot);
- const target = assertDirectory(targetRoot);
- const withStats = options.withStats !== false;
- const left = walk(base, options);
- const right = walk(target, options);
- const allPaths = new Set([...left.keys(), ...right.keys()]);
- const sorted = [...allPaths].sort((a, b) => a.localeCompare(b));
- const hashes = new Map();
- const texts = new Map();
- const hashOf = async (abs) => {
- if (!hashes.has(abs)) hashes.set(abs, await sha256(abs));
- return hashes.get(abs);
- };
- const textOf = async (abs) => {
- if (!texts.has(abs)) texts.set(abs, await readText(abs, STAT_MAX_BYTES));
- return texts.get(abs);
- };
- const entries = [];
- const added = [];
- const removed = [];
- for (const rel of sorted) {
- const l = left.get(rel);
- const r = right.get(rel);
- if (l && !r) {
- removed.push({ path: rel, status: "removed", basePath: l.abs, targetPath: null, baseSize: l.size, targetSize: null });
- continue;
- }
- if (!l && r) {
- added.push({ path: rel, status: "added", basePath: null, targetPath: r.abs, baseSize: null, targetSize: r.size });
- continue;
- }
- if (!l || !r) continue;
- let status;
- if (l.size === r.size && l.mtimeMs === r.mtimeMs) status = "same";
- else if (l.size === r.size) {
- const [hl, hr] = await Promise.all([hashOf(l.abs), hashOf(r.abs)]);
- status = hl === hr ? "same" : "modified";
- } else status = "modified";
- entries.push({ path: rel, status, basePath: l.abs, targetPath: r.abs, baseSize: l.size, targetSize: r.size });
- }
- const renamePairs = [];
- // 第一轮:内容完全一致的重命名(bjpj/ -> bjpb/ 这类整体改目录名)。
- const remainingAdded = [...added];
- const remainingRemoved = [];
- for (const victim of removed) {
- let match = null;
- for (const candidate of remainingAdded) {
- if (candidate.matched) continue;
- if (candidate.targetSize !== victim.baseSize) continue;
- if ((await hashOf(candidate.targetPath)) === (await hashOf(victim.basePath))) {
- match = candidate;
- break;
- }
- }
- if (match) {
- match.matched = true;
- victim.matched = true;
- renamePairs.push({ from: victim, to: match, exact: true });
- } else {
- remainingRemoved.push(victim);
- }
- }
- // 第二轮:同名不同目录、内容有大改动,用行集合相似度判断“改名 + 改内容”。
- const leftoverAdded = remainingAdded.filter((a) => !a.matched);
- const usedAdded = new Set();
- for (const victim of remainingRemoved) {
- const baseName = victim.path.split("/").pop();
- const candidates = leftoverAdded.filter((a) => !usedAdded.has(a) && a.path.split("/").pop() === baseName);
- if (candidates.length === 0) continue;
- const victimText = await textOf(victim.basePath);
- if (victimText.binary || victimText.tooLarge) continue;
- const victimSig = lineSignature(victimText.text);
- let best = null;
- for (const candidate of candidates) {
- const candidateText = await textOf(candidate.targetPath);
- if (candidateText.binary || candidateText.tooLarge) continue;
- const score = jaccard(victimSig, lineSignature(candidateText.text));
- if (score >= RENAME_SIMILARITY && (!best || score > best.score)) best = { candidate, score };
- }
- if (best) {
- usedAdded.add(best.candidate);
- victim.matched = true;
- best.candidate.matched = true;
- renamePairs.push({ from: victim, to: best.candidate, exact: false, score: best.score });
- }
- }
- for (const pair of renamePairs) {
- entries.push({
- path: pair.to.path,
- from: pair.from.path,
- status: "renamed",
- exactRename: pair.exact,
- similarity: pair.exact ? 1 : pair.score,
- basePath: pair.from.basePath,
- targetPath: pair.to.targetPath,
- baseSize: pair.from.baseSize,
- targetSize: pair.to.targetSize,
- });
- }
- for (const e of remainingAdded) {
- if (!e.matched) entries.push({ ...e, from: null });
- }
- for (const e of remainingRemoved) {
- if (!e.matched) entries.push({ ...e, from: null });
- }
- entries.sort((a, b) => a.path.localeCompare(b.path));
- const summary = {
- added: 0,
- modified: 0,
- removed: 0,
- renamed: 0,
- same: 0,
- binary: 0,
- changedFiles: 0,
- addedLines: 0,
- removedLines: 0,
- baseFiles: left.size,
- targetFiles: right.size,
- };
- for (const entry of entries) {
- if (entry.status === "same") summary.same++;
- else if (entry.status === "added") summary.added++;
- else if (entry.status === "removed") summary.removed++;
- else if (entry.status === "renamed") summary.renamed++;
- else summary.modified++;
- if (entry.status !== "same") summary.changedFiles++;
- if (entry.status === "same" || !withStats) continue;
- let stats;
- if (entry.status === "modified" || entry.status === "renamed") {
- stats = await diffStats(entry.basePath, entry.targetPath, textOf);
- } else if (entry.status === "added") {
- stats = await oneSideStats(entry.targetPath, textOf, "added");
- } else {
- stats = await oneSideStats(entry.basePath, textOf, "removed");
- }
- if (stats.binary) {
- entry.binary = true;
- summary.binary++;
- continue;
- }
- if (stats.tooLarge) {
- entry.tooLarge = true;
- continue;
- }
- entry.added = stats.added ?? 0;
- entry.removed = stats.removed ?? 0;
- entry.leftLines = stats.leftLines ?? null;
- entry.rightLines = stats.rightLines ?? null;
- entry.collapsed = stats.collapsed ?? false;
- summary.addedLines += entry.added;
- summary.removedLines += entry.removed;
- }
- return { base, target, files: entries, summary };
- }
- async function diffStats(leftAbs, rightAbs, textOf) {
- const [l, r] = await Promise.all([textOf(leftAbs), textOf(rightAbs)]);
- if (l.binary || r.binary) return { binary: true };
- if (l.tooLarge || r.tooLarge) return { tooLarge: true };
- const built = buildRows(l.text, r.text, { inline: false });
- return {
- added: built.stats.added + built.stats.changed,
- removed: built.stats.removed + built.stats.changed,
- changed: built.stats.changed,
- leftLines: splitLinesForDiff(l.text).lines.length,
- rightLines: splitLinesForDiff(r.text).lines.length,
- collapsed: built.collapsed,
- };
- }
- async function oneSideStats(abs, textOf, side) {
- const info = await textOf(abs);
- if (info.binary) return { binary: true };
- if (info.tooLarge) return { tooLarge: true };
- const lines = splitLinesForDiff(info.text).lines.length;
- return side === "added" ? { added: lines, rightLines: lines } : { removed: lines, leftLines: lines };
- }
|