server.mjs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. // 代码目录对比工具 —— 本地服务端。
  2. // 只监听 127.0.0.1,只读被比较的项目目录,唯一的写操作是保存 targets.json。
  3. import http from "node:http";
  4. import fs from "node:fs";
  5. import fsp from "node:fs/promises";
  6. import path from "node:path";
  7. import { fileURLToPath } from "node:url";
  8. import { DEFAULT_IGNORE, assertDirectory, readText, scanProjects, toRel } from "./lib/scan.mjs";
  9. import { buildRows, collapseRows, splitLinesForDiff } from "./lib/diff.mjs";
  10. const HERE = path.dirname(fileURLToPath(import.meta.url));
  11. const PUBLIC_DIR = path.join(HERE, "public");
  12. const CONFIG_PATH = path.join(HERE, "targets.json");
  13. const PORT = Number(process.env.PORT || process.argv[2] || 8099);
  14. const HOST = "127.0.0.1";
  15. const SCOPES = [
  16. { id: "all", label: "全部(按忽略规则)", prefixes: null },
  17. { id: "code", label: "源码+配置+页面", prefixes: ["src/", "web/cfg/", "web/page/", "web/WEB-INF/"] },
  18. { id: "src", label: "Java 源码 src/", prefixes: ["src/"] },
  19. { id: "cfg", label: "配置 web/cfg/", prefixes: ["web/cfg/"] },
  20. { id: "page", label: "页面 web/page/", prefixes: ["web/page/"] },
  21. { id: "web", label: "整个 web/", prefixes: ["web/"] },
  22. { id: "docs", label: "文档 docs/", prefixes: ["docs/"] },
  23. ];
  24. const DEFAULT_CONFIG = {
  25. baseline: "H:\\gaohp\\feifan\\backend\\PMS_20260827\\PMS",
  26. targets: [
  27. { name: "0904", path: "H:\\gaohp\\feifan\\backend\\PMS_20260904\\PMS" },
  28. { name: "0916", path: "H:\\gaohp\\feifan\\backend\\PMS_20260916\\PMS" },
  29. ],
  30. scanRoots: ["H:\\gaohp\\feifan\\backend"],
  31. ignore: DEFAULT_IGNORE,
  32. includeBuild: false,
  33. };
  34. let config = loadConfig();
  35. const scanCache = new Map();
  36. const diffCache = new Map();
  37. const SCAN_TTL_MS = 5 * 60 * 1000;
  38. function loadConfig() {
  39. try {
  40. const raw = fs.readFileSync(CONFIG_PATH, "utf8");
  41. const parsed = JSON.parse(raw);
  42. return {
  43. ...DEFAULT_CONFIG,
  44. ...parsed,
  45. ignore: Array.isArray(parsed.ignore) && parsed.ignore.length > 0 ? parsed.ignore : DEFAULT_IGNORE,
  46. targets: Array.isArray(parsed.targets) ? parsed.targets : DEFAULT_CONFIG.targets,
  47. scanRoots: Array.isArray(parsed.scanRoots) ? parsed.scanRoots : DEFAULT_CONFIG.scanRoots,
  48. };
  49. } catch {
  50. return { ...DEFAULT_CONFIG };
  51. }
  52. }
  53. async function saveConfig() {
  54. await fsp.writeFile(CONFIG_PATH, JSON.stringify(config, null, 2), "utf8");
  55. }
  56. function publicConfig() {
  57. return {
  58. baseline: config.baseline,
  59. targets: config.targets,
  60. scanRoots: config.scanRoots,
  61. ignore: config.ignore,
  62. includeBuild: !!config.includeBuild,
  63. scopes: SCOPES,
  64. defaultIgnore: DEFAULT_IGNORE,
  65. };
  66. }
  67. function scopePrefixes(scopeId) {
  68. const scope = SCOPES.find((s) => s.id === scopeId);
  69. return scope && scope.prefixes ? scope.prefixes : null;
  70. }
  71. function filterByScope(files, scopeId) {
  72. const prefixes = scopePrefixes(scopeId);
  73. if (!prefixes) return files;
  74. return files.filter((f) => prefixes.some((p) => f.path === p.replace(/\/$/, "") || f.path.startsWith(p)));
  75. }
  76. function resolveTarget(query) {
  77. const raw = query.get("target");
  78. if (!raw) throw new Error("缺少 target 参数");
  79. const byName = config.targets.find((t) => t.name === raw);
  80. const candidate = byName ? byName.path : raw;
  81. return assertDirectory(candidate);
  82. }
  83. function assertInside(root, absPath) {
  84. const rel = path.relative(root, absPath);
  85. if (rel.startsWith("..") || path.isAbsolute(rel)) throw new Error("路径越界");
  86. return rel.split(path.sep).join("/");
  87. }
  88. function cacheKey(...parts) {
  89. return parts.join("|");
  90. }
  91. async function getScan(targetRoot, scopeId, options) {
  92. const includeBuild = !!options.includeBuild;
  93. const withStats = options.withStats !== false;
  94. const key = cacheKey(config.baseline, targetRoot, scopeId, includeBuild, withStats);
  95. const hit = scanCache.get(key);
  96. if (hit && !options.refresh && Date.now() - hit.at < SCAN_TTL_MS) {
  97. return { ...hit.value, cached: true };
  98. }
  99. const scanned = await scanProjects(config.baseline, targetRoot, {
  100. ignore: config.ignore,
  101. includeBuild,
  102. withStats,
  103. });
  104. const files = filterByScope(scanned.files, scopeId);
  105. const value = {
  106. baseline: scanned.base,
  107. target: scanned.target,
  108. scope: scopeId,
  109. includeBuild,
  110. generatedAt: new Date().toISOString(),
  111. summary: summarize(files),
  112. files: files.map((f) => ({
  113. path: f.path,
  114. from: f.from ?? null,
  115. status: f.status,
  116. baseSize: f.baseSize,
  117. targetSize: f.targetSize,
  118. added: f.added ?? 0,
  119. removed: f.removed ?? 0,
  120. leftLines: f.leftLines ?? null,
  121. rightLines: f.rightLines ?? null,
  122. binary: !!f.binary,
  123. tooLarge: !!f.tooLarge,
  124. })),
  125. };
  126. scanCache.set(key, { at: Date.now(), value });
  127. return value;
  128. }
  129. function summarize(files) {
  130. const summary = {
  131. added: 0,
  132. modified: 0,
  133. removed: 0,
  134. renamed: 0,
  135. same: 0,
  136. binary: 0,
  137. addedLines: 0,
  138. removedLines: 0,
  139. files: files.length,
  140. };
  141. for (const f of files) {
  142. if (f.status === "added") summary.added++;
  143. else if (f.status === "modified") summary.modified++;
  144. else if (f.status === "removed") summary.removed++;
  145. else if (f.status === "renamed") summary.renamed++;
  146. else summary.same++;
  147. if (f.binary) summary.binary++;
  148. summary.addedLines += f.added ?? 0;
  149. summary.removedLines += f.removed ?? 0;
  150. }
  151. return summary;
  152. }
  153. async function getDiff(targetRoot, relPath, options) {
  154. const includeBuild = !!options.includeBuild;
  155. const fromPath = options.fromPath || relPath;
  156. const onlyDiff = options.onlyDiff === true;
  157. const context = Number.isFinite(options.context) ? options.context : 3;
  158. const ignoreWs = options.ignoreWs === true;
  159. const key = cacheKey(config.baseline, targetRoot, fromPath, relPath, includeBuild, onlyDiff, context, ignoreWs);
  160. const hit = diffCache.get(key);
  161. if (hit && Date.now() - hit.at < SCAN_TTL_MS) return hit.value;
  162. const baseAbs = path.resolve(config.baseline, fromPath);
  163. const targetAbs = path.resolve(targetRoot, relPath);
  164. assertInside(config.baseline, baseAbs);
  165. assertInside(targetRoot, targetAbs);
  166. const [left, right] = await Promise.all([readMaybe(baseAbs), readMaybe(targetAbs)]);
  167. if (left.binary || right.binary) {
  168. const value = { binary: true, path: relPath, leftSize: left.size ?? null, rightSize: right.size ?? null };
  169. diffCache.set(key, { at: Date.now(), value });
  170. return value;
  171. }
  172. if (left.tooLarge || right.tooLarge) {
  173. const value = { tooLarge: true, path: relPath, leftSize: left.size ?? null, rightSize: right.size ?? null };
  174. diffCache.set(key, { at: Date.now(), value });
  175. return value;
  176. }
  177. const built = buildRows(left.text ?? "", right.text ?? "");
  178. if (ignoreWs && !built.chunked) {
  179. // 忽略空白时用“压平空白”的副本做比较,但展示仍然回到原始行,避免把文件内容改花。
  180. const leftLines = splitLinesForDiff(left.text ?? "");
  181. const rightLines = splitLinesForDiff(right.text ?? "");
  182. const flatten = (lines) => lines.map((line) => line.replace(/[ \t]+/g, " ").trim());
  183. const normalized = buildRows(flatten(leftLines).join("\n"), flatten(rightLines).join("\n"));
  184. for (const row of normalized.rows) {
  185. if (row.type === "gap") continue;
  186. row.left = row.leftNo ? (leftLines[row.leftNo - 1] ?? null) : null;
  187. row.right = row.rightNo ? (rightLines[row.rightNo - 1] ?? null) : null;
  188. delete row.leftSeg;
  189. delete row.rightSeg;
  190. }
  191. built.rows = normalized.rows;
  192. built.stats = normalized.stats;
  193. built.totalRows = normalized.totalRows;
  194. }
  195. const rows = onlyDiff ? collapseRows(built.rows, context) : built.rows;
  196. const value = {
  197. path: relPath,
  198. from: fromPath,
  199. leftEncoding: left.encoding ?? null,
  200. rightEncoding: right.encoding ?? null,
  201. stats: built.stats,
  202. totalRows: built.totalRows,
  203. collapsed: built.collapsed,
  204. chunked: built.chunked,
  205. onlyDiff,
  206. context,
  207. ignoreWs,
  208. rows,
  209. };
  210. diffCache.set(key, { at: Date.now(), value });
  211. return value;
  212. }
  213. async function readMaybe(abs) {
  214. const st = await fsp.stat(abs).catch(() => null);
  215. if (!st) return {};
  216. if (!st.isFile()) return {};
  217. return readText(abs);
  218. }
  219. function sendJson(res, data, status = 200) {
  220. const body = JSON.stringify(data);
  221. res.writeHead(status, {
  222. "content-type": "application/json; charset=utf-8",
  223. "content-length": Buffer.byteLength(body),
  224. "cache-control": "no-store",
  225. });
  226. res.end(body);
  227. }
  228. function sendError(res, error, status = 400) {
  229. sendJson(res, { error: String(error && error.message ? error.message : error) }, status);
  230. }
  231. function readBody(req, limit = 1024 * 1024) {
  232. return new Promise((resolve, reject) => {
  233. let size = 0;
  234. const chunks = [];
  235. req.on("data", (chunk) => {
  236. size += chunk.length;
  237. if (size > limit) {
  238. reject(new Error("请求体过大"));
  239. req.destroy();
  240. return;
  241. }
  242. chunks.push(chunk);
  243. });
  244. req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
  245. req.on("error", reject);
  246. });
  247. }
  248. function discoverProjects() {
  249. const found = [];
  250. const seen = new Set();
  251. for (const root of config.scanRoots) {
  252. let entries;
  253. try {
  254. entries = fs.readdirSync(root, { withFileTypes: true });
  255. } catch {
  256. continue;
  257. }
  258. for (const entry of entries) {
  259. if (!entry.isDirectory()) continue;
  260. const abs = path.join(root, entry.name);
  261. const candidates = [abs, path.join(abs, "PMS")];
  262. for (const candidate of candidates) {
  263. try {
  264. const st = fs.statSync(candidate);
  265. if (!st.isDirectory()) continue;
  266. } catch {
  267. continue;
  268. }
  269. if (!fs.existsSync(path.join(candidate, "web")) && !fs.existsSync(path.join(candidate, "src"))) continue;
  270. const normalized = path.resolve(candidate);
  271. if (seen.has(normalized)) continue;
  272. seen.add(normalized);
  273. found.push({
  274. name: path.basename(candidate) === "PMS" ? path.basename(path.dirname(candidate)) : path.basename(candidate),
  275. path: normalized,
  276. mtime: fs.statSync(normalized).mtime.toISOString(),
  277. });
  278. }
  279. }
  280. }
  281. return found.sort((a, b) => b.mtime.localeCompare(a.mtime));
  282. }
  283. function browseDirectory(dir) {
  284. const target = dir && dir.trim() ? path.resolve(dir) : config.scanRoots[0];
  285. const st = fs.statSync(target, { throwIfNoEntry: false });
  286. if (!st || !st.isDirectory()) throw new Error("目录不存在:" + target);
  287. const entries = fs
  288. .readdirSync(target, { withFileTypes: true })
  289. .filter((e) => e.isDirectory() && !e.name.startsWith(".") && e.name !== "node_modules")
  290. .map((e) => ({ name: e.name, path: path.join(target, e.name) }))
  291. .sort((a, b) => a.name.localeCompare(b.name));
  292. const parent = path.dirname(target);
  293. return { path: target, parent: parent === target ? null : parent, entries };
  294. }
  295. const MIME = {
  296. ".html": "text/html; charset=utf-8",
  297. ".js": "text/javascript; charset=utf-8",
  298. ".css": "text/css; charset=utf-8",
  299. ".svg": "image/svg+xml",
  300. ".json": "application/json; charset=utf-8",
  301. ".ico": "image/x-icon",
  302. };
  303. async function serveStatic(req, res, pathname) {
  304. const rel = pathname === "/" ? "index.html" : pathname.replace(/^\/+/, "");
  305. const abs = path.join(PUBLIC_DIR, rel);
  306. if (!abs.startsWith(PUBLIC_DIR)) {
  307. res.writeHead(403).end("forbidden");
  308. return;
  309. }
  310. const body = await fsp.readFile(abs).catch(() => null);
  311. if (!body) {
  312. res.writeHead(404, { "content-type": "text/plain; charset=utf-8" }).end("not found");
  313. return;
  314. }
  315. res.writeHead(200, {
  316. "content-type": MIME[path.extname(abs).toLowerCase()] || "application/octet-stream",
  317. "cache-control": "no-store",
  318. });
  319. res.end(body);
  320. }
  321. const server = http.createServer(async (req, res) => {
  322. const parsed = new URL(req.url, "http://" + HOST);
  323. const pathname = decodeURIComponent(parsed.pathname);
  324. const query = parsed.searchParams;
  325. try {
  326. if (pathname === "/api/state" && req.method === "GET") {
  327. sendJson(res, publicConfig());
  328. return;
  329. }
  330. if (pathname === "/api/state" && req.method === "POST") {
  331. const body = JSON.parse((await readBody(req)) || "{}");
  332. if (typeof body.baseline === "string") {
  333. config.baseline = assertDirectory(body.baseline);
  334. scanCache.clear();
  335. diffCache.clear();
  336. }
  337. if (Array.isArray(body.targets)) {
  338. config.targets = body.targets
  339. .filter((t) => t && typeof t.path === "string" && t.path.trim())
  340. .map((t) => ({ name: String(t.name || path.basename(t.path)), path: path.resolve(t.path) }));
  341. }
  342. if (Array.isArray(body.ignore)) config.ignore = body.ignore.filter((s) => typeof s === "string");
  343. if (typeof body.includeBuild === "boolean") config.includeBuild = body.includeBuild;
  344. if (Array.isArray(body.scanRoots)) config.scanRoots = body.scanRoots.filter((s) => typeof s === "string");
  345. await saveConfig();
  346. scanCache.clear();
  347. diffCache.clear();
  348. sendJson(res, publicConfig());
  349. return;
  350. }
  351. if (pathname === "/api/discover") {
  352. sendJson(res, { candidates: discoverProjects() });
  353. return;
  354. }
  355. if (pathname === "/api/browse") {
  356. sendJson(res, browseDirectory(query.get("path")));
  357. return;
  358. }
  359. if (pathname === "/api/scan") {
  360. const targetRoot = resolveTarget(query);
  361. const scope = query.get("scope") || "all";
  362. const includeBuild = query.get("includeBuild") === "1";
  363. const withStats = query.get("stats") !== "0";
  364. const data = await getScan(targetRoot, scope, {
  365. includeBuild,
  366. withStats,
  367. refresh: query.get("refresh") === "1",
  368. });
  369. sendJson(res, data);
  370. return;
  371. }
  372. if (pathname === "/api/diff") {
  373. const targetRoot = resolveTarget(query);
  374. const relPath = query.get("path");
  375. if (!relPath) throw new Error("缺少 path 参数");
  376. const data = await getDiff(targetRoot, relPath, {
  377. fromPath: query.get("from") || relPath,
  378. includeBuild: query.get("includeBuild") === "1",
  379. onlyDiff: query.get("onlyDiff") === "1",
  380. ignoreWs: query.get("ignoreWs") === "1",
  381. context: query.get("context") ? Number(query.get("context")) : 3,
  382. });
  383. sendJson(res, data);
  384. return;
  385. }
  386. if (req.method === "GET") {
  387. await serveStatic(req, res, pathname);
  388. return;
  389. }
  390. res.writeHead(405).end("method not allowed");
  391. } catch (error) {
  392. sendError(res, error);
  393. }
  394. });
  395. server.listen(PORT, HOST, () => {
  396. const targetCount = config.targets.length;
  397. console.log("代码对比工具已启动: http://" + HOST + ":" + PORT);
  398. console.log("基线目录: " + config.baseline);
  399. console.log("对比目录: " + targetCount + " 个");
  400. });