scan.mjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. // 目录扫描与文件比较:把两个项目目录按相对路径对齐,判断 新增/修改/删除/重命名/未变。
  2. // 全程只读,不写被比较的目录。
  3. import fs from "node:fs";
  4. import fsp from "node:fs/promises";
  5. import path from "node:path";
  6. import crypto from "node:crypto";
  7. import { buildRows, splitLinesForDiff } from "./diff.mjs";
  8. // 默认忽略:构建产物、依赖、IDE、版本库、以及明显不是源码的二进制。
  9. export const DEFAULT_IGNORE = [
  10. ".git/",
  11. ".idea/",
  12. ".codex_backup/",
  13. ".claude/",
  14. "node_modules/",
  15. "out/",
  16. "outputs/",
  17. "release/",
  18. "tmp/",
  19. "web/WEB-INF/classes/",
  20. "web/WEB-INF/lib/",
  21. "*.class",
  22. "*.jar",
  23. "*.war",
  24. "*.zip",
  25. "*.exe",
  26. "*.dll",
  27. "*.so",
  28. "*.log",
  29. "*.iml",
  30. ".DS_Store",
  31. "Thumbs.db",
  32. ];
  33. // 这些是“构建产物/依赖”类目录,用开关单独控制:默认忽略,勾选后参与比较。
  34. export const BUILD_IGNORE = [
  35. "out/",
  36. "outputs/",
  37. "release/",
  38. "tmp/",
  39. "node_modules/",
  40. "web/WEB-INF/classes/",
  41. "web/WEB-INF/lib/",
  42. "*.class",
  43. "*.jar",
  44. "*.war",
  45. "*.zip",
  46. ];
  47. const RENAME_SIMILARITY = 0.5;
  48. const STAT_MAX_BYTES = 1.5 * 1024 * 1024;
  49. export function toRel(root, abs) {
  50. return path.relative(root, abs).split(path.sep).join("/");
  51. }
  52. export function isIgnored(rel, isDir, rules) {
  53. for (const raw of rules) {
  54. const rule = raw.trim();
  55. if (!rule) continue;
  56. if (rule.endsWith("/")) {
  57. const seg = rule.slice(0, -1);
  58. if (rel === seg || rel.endsWith("/" + seg) || rel.includes("/" + seg + "/")) return true;
  59. } else if (rule.startsWith("*.")) {
  60. const ext = rule.slice(1).toLowerCase();
  61. if (rel.toLowerCase().endsWith(ext)) return true;
  62. } else if (rel === rule || rel.startsWith(rule + "/")) {
  63. return true;
  64. }
  65. }
  66. return false;
  67. }
  68. function effectiveIgnore(options = {}) {
  69. const rules = options.ignore ?? DEFAULT_IGNORE;
  70. if (!options.includeBuild) return rules;
  71. return rules.filter((r) => !BUILD_IGNORE.includes(r));
  72. }
  73. export function assertDirectory(dir) {
  74. if (!dir) throw new Error("目录为空");
  75. const resolved = path.resolve(dir);
  76. const st = fs.statSync(resolved, { throwIfNoEntry: false });
  77. if (!st || !st.isDirectory()) throw new Error("目录不存在或不是目录:" + resolved);
  78. return resolved;
  79. }
  80. export function walk(root, options = {}) {
  81. const rules = effectiveIgnore(options);
  82. const out = new Map();
  83. const stack = [root];
  84. while (stack.length > 0) {
  85. const dir = stack.pop();
  86. let entries;
  87. try {
  88. entries = fs.readdirSync(dir, { withFileTypes: true });
  89. } catch {
  90. continue;
  91. }
  92. for (const entry of entries) {
  93. const abs = path.join(dir, entry.name);
  94. const rel = toRel(root, abs);
  95. const isDir = entry.isDirectory();
  96. if (isIgnored(rel, isDir, rules)) continue;
  97. if (entry.isSymbolicLink()) continue;
  98. if (isDir) {
  99. stack.push(abs);
  100. continue;
  101. }
  102. if (!entry.isFile()) continue;
  103. let st;
  104. try {
  105. st = fs.statSync(abs);
  106. } catch {
  107. continue;
  108. }
  109. out.set(rel, { rel, abs, size: st.size, mtimeMs: Math.round(st.mtimeMs) });
  110. }
  111. }
  112. return out;
  113. }
  114. const gbkDecoder = new TextDecoder("gb18030");
  115. const utf8DecoderStrict = new TextDecoder("utf-8", { fatal: true });
  116. function hasBinaryByte(buf) {
  117. const limit = Math.min(buf.length, 8192);
  118. for (let i = 0; i < limit; i++) {
  119. if (buf[i] === 0) return true;
  120. }
  121. return false;
  122. }
  123. /**
  124. * 文本解码:优先 UTF-8,失败回退 GB18030(老 JSP/配置里有 GBK 内容)。
  125. * 二进制返回 null。
  126. */
  127. export function decodeBuffer(buf) {
  128. if (hasBinaryByte(buf)) return null;
  129. try {
  130. return { text: utf8DecoderStrict.decode(buf), encoding: "utf-8" };
  131. } catch {
  132. return { text: gbkDecoder.decode(buf), encoding: "gb18030" };
  133. }
  134. }
  135. export async function readText(abs, maxBytes = 8 * 1024 * 1024) {
  136. const st = await fsp.stat(abs);
  137. if (st.size > maxBytes) return { tooLarge: true, size: st.size };
  138. const buf = await fsp.readFile(abs);
  139. const decoded = decodeBuffer(buf);
  140. if (!decoded) return { binary: true, size: st.size };
  141. return { text: decoded.text, encoding: decoded.encoding, size: st.size };
  142. }
  143. function sha256(abs) {
  144. return new Promise((resolve, reject) => {
  145. const hash = crypto.createHash("sha256");
  146. const stream = fs.createReadStream(abs);
  147. stream.on("data", (chunk) => hash.update(chunk));
  148. stream.on("error", reject);
  149. stream.on("end", () => resolve(hash.digest("hex")));
  150. });
  151. }
  152. function lineSignature(text) {
  153. const set = new Set();
  154. for (const line of splitLinesForDiff(text).lines) {
  155. const trimmed = line.trim();
  156. if (trimmed.length === 0 || trimmed.length > 240) continue;
  157. set.add(trimmed);
  158. }
  159. return set;
  160. }
  161. function jaccard(a, b) {
  162. if (a.size === 0 || b.size === 0) return 0;
  163. let inter = 0;
  164. const [small, large] = a.size <= b.size ? [a, b] : [b, a];
  165. for (const item of small) {
  166. if (large.has(item)) inter++;
  167. }
  168. const union = a.size + b.size - inter;
  169. return union === 0 ? 0 : inter / union;
  170. }
  171. /**
  172. * 扫描两个目录,返回逐文件状态。
  173. * options: { ignore, includeBuild, withStats }
  174. */
  175. export async function scanProjects(baseRoot, targetRoot, options = {}) {
  176. const base = assertDirectory(baseRoot);
  177. const target = assertDirectory(targetRoot);
  178. const withStats = options.withStats !== false;
  179. const left = walk(base, options);
  180. const right = walk(target, options);
  181. const allPaths = new Set([...left.keys(), ...right.keys()]);
  182. const sorted = [...allPaths].sort((a, b) => a.localeCompare(b));
  183. const hashes = new Map();
  184. const texts = new Map();
  185. const hashOf = async (abs) => {
  186. if (!hashes.has(abs)) hashes.set(abs, await sha256(abs));
  187. return hashes.get(abs);
  188. };
  189. const textOf = async (abs) => {
  190. if (!texts.has(abs)) texts.set(abs, await readText(abs, STAT_MAX_BYTES));
  191. return texts.get(abs);
  192. };
  193. const entries = [];
  194. const added = [];
  195. const removed = [];
  196. for (const rel of sorted) {
  197. const l = left.get(rel);
  198. const r = right.get(rel);
  199. if (l && !r) {
  200. removed.push({ path: rel, status: "removed", basePath: l.abs, targetPath: null, baseSize: l.size, targetSize: null });
  201. continue;
  202. }
  203. if (!l && r) {
  204. added.push({ path: rel, status: "added", basePath: null, targetPath: r.abs, baseSize: null, targetSize: r.size });
  205. continue;
  206. }
  207. if (!l || !r) continue;
  208. let status;
  209. if (l.size === r.size && l.mtimeMs === r.mtimeMs) status = "same";
  210. else if (l.size === r.size) {
  211. const [hl, hr] = await Promise.all([hashOf(l.abs), hashOf(r.abs)]);
  212. status = hl === hr ? "same" : "modified";
  213. } else status = "modified";
  214. entries.push({ path: rel, status, basePath: l.abs, targetPath: r.abs, baseSize: l.size, targetSize: r.size });
  215. }
  216. const renamePairs = [];
  217. // 第一轮:内容完全一致的重命名(bjpj/ -> bjpb/ 这类整体改目录名)。
  218. const remainingAdded = [...added];
  219. const remainingRemoved = [];
  220. for (const victim of removed) {
  221. let match = null;
  222. for (const candidate of remainingAdded) {
  223. if (candidate.matched) continue;
  224. if (candidate.targetSize !== victim.baseSize) continue;
  225. if ((await hashOf(candidate.targetPath)) === (await hashOf(victim.basePath))) {
  226. match = candidate;
  227. break;
  228. }
  229. }
  230. if (match) {
  231. match.matched = true;
  232. victim.matched = true;
  233. renamePairs.push({ from: victim, to: match, exact: true });
  234. } else {
  235. remainingRemoved.push(victim);
  236. }
  237. }
  238. // 第二轮:同名不同目录、内容有大改动,用行集合相似度判断“改名 + 改内容”。
  239. const leftoverAdded = remainingAdded.filter((a) => !a.matched);
  240. const usedAdded = new Set();
  241. for (const victim of remainingRemoved) {
  242. const baseName = victim.path.split("/").pop();
  243. const candidates = leftoverAdded.filter((a) => !usedAdded.has(a) && a.path.split("/").pop() === baseName);
  244. if (candidates.length === 0) continue;
  245. const victimText = await textOf(victim.basePath);
  246. if (victimText.binary || victimText.tooLarge) continue;
  247. const victimSig = lineSignature(victimText.text);
  248. let best = null;
  249. for (const candidate of candidates) {
  250. const candidateText = await textOf(candidate.targetPath);
  251. if (candidateText.binary || candidateText.tooLarge) continue;
  252. const score = jaccard(victimSig, lineSignature(candidateText.text));
  253. if (score >= RENAME_SIMILARITY && (!best || score > best.score)) best = { candidate, score };
  254. }
  255. if (best) {
  256. usedAdded.add(best.candidate);
  257. victim.matched = true;
  258. best.candidate.matched = true;
  259. renamePairs.push({ from: victim, to: best.candidate, exact: false, score: best.score });
  260. }
  261. }
  262. for (const pair of renamePairs) {
  263. entries.push({
  264. path: pair.to.path,
  265. from: pair.from.path,
  266. status: "renamed",
  267. exactRename: pair.exact,
  268. similarity: pair.exact ? 1 : pair.score,
  269. basePath: pair.from.basePath,
  270. targetPath: pair.to.targetPath,
  271. baseSize: pair.from.baseSize,
  272. targetSize: pair.to.targetSize,
  273. });
  274. }
  275. for (const e of remainingAdded) {
  276. if (!e.matched) entries.push({ ...e, from: null });
  277. }
  278. for (const e of remainingRemoved) {
  279. if (!e.matched) entries.push({ ...e, from: null });
  280. }
  281. entries.sort((a, b) => a.path.localeCompare(b.path));
  282. const summary = {
  283. added: 0,
  284. modified: 0,
  285. removed: 0,
  286. renamed: 0,
  287. same: 0,
  288. binary: 0,
  289. changedFiles: 0,
  290. addedLines: 0,
  291. removedLines: 0,
  292. baseFiles: left.size,
  293. targetFiles: right.size,
  294. };
  295. for (const entry of entries) {
  296. if (entry.status === "same") summary.same++;
  297. else if (entry.status === "added") summary.added++;
  298. else if (entry.status === "removed") summary.removed++;
  299. else if (entry.status === "renamed") summary.renamed++;
  300. else summary.modified++;
  301. if (entry.status !== "same") summary.changedFiles++;
  302. if (entry.status === "same" || !withStats) continue;
  303. let stats;
  304. if (entry.status === "modified" || entry.status === "renamed") {
  305. stats = await diffStats(entry.basePath, entry.targetPath, textOf);
  306. } else if (entry.status === "added") {
  307. stats = await oneSideStats(entry.targetPath, textOf, "added");
  308. } else {
  309. stats = await oneSideStats(entry.basePath, textOf, "removed");
  310. }
  311. if (stats.binary) {
  312. entry.binary = true;
  313. summary.binary++;
  314. continue;
  315. }
  316. if (stats.tooLarge) {
  317. entry.tooLarge = true;
  318. continue;
  319. }
  320. entry.added = stats.added ?? 0;
  321. entry.removed = stats.removed ?? 0;
  322. entry.leftLines = stats.leftLines ?? null;
  323. entry.rightLines = stats.rightLines ?? null;
  324. entry.collapsed = stats.collapsed ?? false;
  325. summary.addedLines += entry.added;
  326. summary.removedLines += entry.removed;
  327. }
  328. return { base, target, files: entries, summary };
  329. }
  330. async function diffStats(leftAbs, rightAbs, textOf) {
  331. const [l, r] = await Promise.all([textOf(leftAbs), textOf(rightAbs)]);
  332. if (l.binary || r.binary) return { binary: true };
  333. if (l.tooLarge || r.tooLarge) return { tooLarge: true };
  334. const built = buildRows(l.text, r.text, { inline: false });
  335. return {
  336. added: built.stats.added + built.stats.changed,
  337. removed: built.stats.removed + built.stats.changed,
  338. changed: built.stats.changed,
  339. leftLines: splitLinesForDiff(l.text).lines.length,
  340. rightLines: splitLinesForDiff(r.text).lines.length,
  341. collapsed: built.collapsed,
  342. };
  343. }
  344. async function oneSideStats(abs, textOf, side) {
  345. const info = await textOf(abs);
  346. if (info.binary) return { binary: true };
  347. if (info.tooLarge) return { tooLarge: true };
  348. const lines = splitLinesForDiff(info.text).lines.length;
  349. return side === "added" ? { added: lines, rightLines: lines } : { removed: lines, leftLines: lines };
  350. }