| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428 |
- // 代码目录对比工具 —— 本地服务端。
- // 只监听 127.0.0.1,只读被比较的项目目录,唯一的写操作是保存 targets.json。
- import http from "node:http";
- import fs from "node:fs";
- import fsp from "node:fs/promises";
- import path from "node:path";
- import { fileURLToPath } from "node:url";
- import { DEFAULT_IGNORE, assertDirectory, readText, scanProjects, toRel } from "./lib/scan.mjs";
- import { buildRows, collapseRows, splitLinesForDiff } from "./lib/diff.mjs";
- const HERE = path.dirname(fileURLToPath(import.meta.url));
- const PUBLIC_DIR = path.join(HERE, "public");
- const CONFIG_PATH = path.join(HERE, "targets.json");
- const PORT = Number(process.env.PORT || process.argv[2] || 8099);
- const HOST = "127.0.0.1";
- const SCOPES = [
- { id: "all", label: "全部(按忽略规则)", prefixes: null },
- { id: "code", label: "源码+配置+页面", prefixes: ["src/", "web/cfg/", "web/page/", "web/WEB-INF/"] },
- { id: "src", label: "Java 源码 src/", prefixes: ["src/"] },
- { id: "cfg", label: "配置 web/cfg/", prefixes: ["web/cfg/"] },
- { id: "page", label: "页面 web/page/", prefixes: ["web/page/"] },
- { id: "web", label: "整个 web/", prefixes: ["web/"] },
- { id: "docs", label: "文档 docs/", prefixes: ["docs/"] },
- ];
- const DEFAULT_CONFIG = {
- baseline: "H:\\gaohp\\feifan\\backend\\PMS_20260827\\PMS",
- targets: [
- { name: "0904", path: "H:\\gaohp\\feifan\\backend\\PMS_20260904\\PMS" },
- { name: "0916", path: "H:\\gaohp\\feifan\\backend\\PMS_20260916\\PMS" },
- ],
- scanRoots: ["H:\\gaohp\\feifan\\backend"],
- ignore: DEFAULT_IGNORE,
- includeBuild: false,
- };
- let config = loadConfig();
- const scanCache = new Map();
- const diffCache = new Map();
- const SCAN_TTL_MS = 5 * 60 * 1000;
- function loadConfig() {
- try {
- const raw = fs.readFileSync(CONFIG_PATH, "utf8");
- const parsed = JSON.parse(raw);
- return {
- ...DEFAULT_CONFIG,
- ...parsed,
- ignore: Array.isArray(parsed.ignore) && parsed.ignore.length > 0 ? parsed.ignore : DEFAULT_IGNORE,
- targets: Array.isArray(parsed.targets) ? parsed.targets : DEFAULT_CONFIG.targets,
- scanRoots: Array.isArray(parsed.scanRoots) ? parsed.scanRoots : DEFAULT_CONFIG.scanRoots,
- };
- } catch {
- return { ...DEFAULT_CONFIG };
- }
- }
- async function saveConfig() {
- await fsp.writeFile(CONFIG_PATH, JSON.stringify(config, null, 2), "utf8");
- }
- function publicConfig() {
- return {
- baseline: config.baseline,
- targets: config.targets,
- scanRoots: config.scanRoots,
- ignore: config.ignore,
- includeBuild: !!config.includeBuild,
- scopes: SCOPES,
- defaultIgnore: DEFAULT_IGNORE,
- };
- }
- function scopePrefixes(scopeId) {
- const scope = SCOPES.find((s) => s.id === scopeId);
- return scope && scope.prefixes ? scope.prefixes : null;
- }
- function filterByScope(files, scopeId) {
- const prefixes = scopePrefixes(scopeId);
- if (!prefixes) return files;
- return files.filter((f) => prefixes.some((p) => f.path === p.replace(/\/$/, "") || f.path.startsWith(p)));
- }
- function resolveTarget(query) {
- const raw = query.get("target");
- if (!raw) throw new Error("缺少 target 参数");
- const byName = config.targets.find((t) => t.name === raw);
- const candidate = byName ? byName.path : raw;
- return assertDirectory(candidate);
- }
- function assertInside(root, absPath) {
- const rel = path.relative(root, absPath);
- if (rel.startsWith("..") || path.isAbsolute(rel)) throw new Error("路径越界");
- return rel.split(path.sep).join("/");
- }
- function cacheKey(...parts) {
- return parts.join("|");
- }
- async function getScan(targetRoot, scopeId, options) {
- const includeBuild = !!options.includeBuild;
- const withStats = options.withStats !== false;
- const key = cacheKey(config.baseline, targetRoot, scopeId, includeBuild, withStats);
- const hit = scanCache.get(key);
- if (hit && !options.refresh && Date.now() - hit.at < SCAN_TTL_MS) {
- return { ...hit.value, cached: true };
- }
- const scanned = await scanProjects(config.baseline, targetRoot, {
- ignore: config.ignore,
- includeBuild,
- withStats,
- });
- const files = filterByScope(scanned.files, scopeId);
- const value = {
- baseline: scanned.base,
- target: scanned.target,
- scope: scopeId,
- includeBuild,
- generatedAt: new Date().toISOString(),
- summary: summarize(files),
- files: files.map((f) => ({
- path: f.path,
- from: f.from ?? null,
- status: f.status,
- baseSize: f.baseSize,
- targetSize: f.targetSize,
- added: f.added ?? 0,
- removed: f.removed ?? 0,
- leftLines: f.leftLines ?? null,
- rightLines: f.rightLines ?? null,
- binary: !!f.binary,
- tooLarge: !!f.tooLarge,
- })),
- };
- scanCache.set(key, { at: Date.now(), value });
- return value;
- }
- function summarize(files) {
- const summary = {
- added: 0,
- modified: 0,
- removed: 0,
- renamed: 0,
- same: 0,
- binary: 0,
- addedLines: 0,
- removedLines: 0,
- files: files.length,
- };
- for (const f of files) {
- if (f.status === "added") summary.added++;
- else if (f.status === "modified") summary.modified++;
- else if (f.status === "removed") summary.removed++;
- else if (f.status === "renamed") summary.renamed++;
- else summary.same++;
- if (f.binary) summary.binary++;
- summary.addedLines += f.added ?? 0;
- summary.removedLines += f.removed ?? 0;
- }
- return summary;
- }
- async function getDiff(targetRoot, relPath, options) {
- const includeBuild = !!options.includeBuild;
- const fromPath = options.fromPath || relPath;
- const onlyDiff = options.onlyDiff === true;
- const context = Number.isFinite(options.context) ? options.context : 3;
- const ignoreWs = options.ignoreWs === true;
- const key = cacheKey(config.baseline, targetRoot, fromPath, relPath, includeBuild, onlyDiff, context, ignoreWs);
- const hit = diffCache.get(key);
- if (hit && Date.now() - hit.at < SCAN_TTL_MS) return hit.value;
- const baseAbs = path.resolve(config.baseline, fromPath);
- const targetAbs = path.resolve(targetRoot, relPath);
- assertInside(config.baseline, baseAbs);
- assertInside(targetRoot, targetAbs);
- const [left, right] = await Promise.all([readMaybe(baseAbs), readMaybe(targetAbs)]);
- if (left.binary || right.binary) {
- const value = { binary: true, path: relPath, leftSize: left.size ?? null, rightSize: right.size ?? null };
- diffCache.set(key, { at: Date.now(), value });
- return value;
- }
- if (left.tooLarge || right.tooLarge) {
- const value = { tooLarge: true, path: relPath, leftSize: left.size ?? null, rightSize: right.size ?? null };
- diffCache.set(key, { at: Date.now(), value });
- return value;
- }
- const built = buildRows(left.text ?? "", right.text ?? "");
- if (ignoreWs && !built.chunked) {
- // 忽略空白时用“压平空白”的副本做比较,但展示仍然回到原始行,避免把文件内容改花。
- const leftLines = splitLinesForDiff(left.text ?? "");
- const rightLines = splitLinesForDiff(right.text ?? "");
- const flatten = (lines) => lines.map((line) => line.replace(/[ \t]+/g, " ").trim());
- const normalized = buildRows(flatten(leftLines).join("\n"), flatten(rightLines).join("\n"));
- for (const row of normalized.rows) {
- if (row.type === "gap") continue;
- row.left = row.leftNo ? (leftLines[row.leftNo - 1] ?? null) : null;
- row.right = row.rightNo ? (rightLines[row.rightNo - 1] ?? null) : null;
- delete row.leftSeg;
- delete row.rightSeg;
- }
- built.rows = normalized.rows;
- built.stats = normalized.stats;
- built.totalRows = normalized.totalRows;
- }
- const rows = onlyDiff ? collapseRows(built.rows, context) : built.rows;
- const value = {
- path: relPath,
- from: fromPath,
- leftEncoding: left.encoding ?? null,
- rightEncoding: right.encoding ?? null,
- stats: built.stats,
- totalRows: built.totalRows,
- collapsed: built.collapsed,
- chunked: built.chunked,
- onlyDiff,
- context,
- ignoreWs,
- rows,
- };
- diffCache.set(key, { at: Date.now(), value });
- return value;
- }
- async function readMaybe(abs) {
- const st = await fsp.stat(abs).catch(() => null);
- if (!st) return {};
- if (!st.isFile()) return {};
- return readText(abs);
- }
- function sendJson(res, data, status = 200) {
- const body = JSON.stringify(data);
- res.writeHead(status, {
- "content-type": "application/json; charset=utf-8",
- "content-length": Buffer.byteLength(body),
- "cache-control": "no-store",
- });
- res.end(body);
- }
- function sendError(res, error, status = 400) {
- sendJson(res, { error: String(error && error.message ? error.message : error) }, status);
- }
- function readBody(req, limit = 1024 * 1024) {
- return new Promise((resolve, reject) => {
- let size = 0;
- const chunks = [];
- req.on("data", (chunk) => {
- size += chunk.length;
- if (size > limit) {
- reject(new Error("请求体过大"));
- req.destroy();
- return;
- }
- chunks.push(chunk);
- });
- req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
- req.on("error", reject);
- });
- }
- function discoverProjects() {
- const found = [];
- const seen = new Set();
- for (const root of config.scanRoots) {
- let entries;
- try {
- entries = fs.readdirSync(root, { withFileTypes: true });
- } catch {
- continue;
- }
- for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- const abs = path.join(root, entry.name);
- const candidates = [abs, path.join(abs, "PMS")];
- for (const candidate of candidates) {
- try {
- const st = fs.statSync(candidate);
- if (!st.isDirectory()) continue;
- } catch {
- continue;
- }
- if (!fs.existsSync(path.join(candidate, "web")) && !fs.existsSync(path.join(candidate, "src"))) continue;
- const normalized = path.resolve(candidate);
- if (seen.has(normalized)) continue;
- seen.add(normalized);
- found.push({
- name: path.basename(candidate) === "PMS" ? path.basename(path.dirname(candidate)) : path.basename(candidate),
- path: normalized,
- mtime: fs.statSync(normalized).mtime.toISOString(),
- });
- }
- }
- }
- return found.sort((a, b) => b.mtime.localeCompare(a.mtime));
- }
- function browseDirectory(dir) {
- const target = dir && dir.trim() ? path.resolve(dir) : config.scanRoots[0];
- const st = fs.statSync(target, { throwIfNoEntry: false });
- if (!st || !st.isDirectory()) throw new Error("目录不存在:" + target);
- const entries = fs
- .readdirSync(target, { withFileTypes: true })
- .filter((e) => e.isDirectory() && !e.name.startsWith(".") && e.name !== "node_modules")
- .map((e) => ({ name: e.name, path: path.join(target, e.name) }))
- .sort((a, b) => a.name.localeCompare(b.name));
- const parent = path.dirname(target);
- return { path: target, parent: parent === target ? null : parent, entries };
- }
- const MIME = {
- ".html": "text/html; charset=utf-8",
- ".js": "text/javascript; charset=utf-8",
- ".css": "text/css; charset=utf-8",
- ".svg": "image/svg+xml",
- ".json": "application/json; charset=utf-8",
- ".ico": "image/x-icon",
- };
- async function serveStatic(req, res, pathname) {
- const rel = pathname === "/" ? "index.html" : pathname.replace(/^\/+/, "");
- const abs = path.join(PUBLIC_DIR, rel);
- if (!abs.startsWith(PUBLIC_DIR)) {
- res.writeHead(403).end("forbidden");
- return;
- }
- const body = await fsp.readFile(abs).catch(() => null);
- if (!body) {
- res.writeHead(404, { "content-type": "text/plain; charset=utf-8" }).end("not found");
- return;
- }
- res.writeHead(200, {
- "content-type": MIME[path.extname(abs).toLowerCase()] || "application/octet-stream",
- "cache-control": "no-store",
- });
- res.end(body);
- }
- const server = http.createServer(async (req, res) => {
- const parsed = new URL(req.url, "http://" + HOST);
- const pathname = decodeURIComponent(parsed.pathname);
- const query = parsed.searchParams;
- try {
- if (pathname === "/api/state" && req.method === "GET") {
- sendJson(res, publicConfig());
- return;
- }
- if (pathname === "/api/state" && req.method === "POST") {
- const body = JSON.parse((await readBody(req)) || "{}");
- if (typeof body.baseline === "string") {
- config.baseline = assertDirectory(body.baseline);
- scanCache.clear();
- diffCache.clear();
- }
- if (Array.isArray(body.targets)) {
- config.targets = body.targets
- .filter((t) => t && typeof t.path === "string" && t.path.trim())
- .map((t) => ({ name: String(t.name || path.basename(t.path)), path: path.resolve(t.path) }));
- }
- if (Array.isArray(body.ignore)) config.ignore = body.ignore.filter((s) => typeof s === "string");
- if (typeof body.includeBuild === "boolean") config.includeBuild = body.includeBuild;
- if (Array.isArray(body.scanRoots)) config.scanRoots = body.scanRoots.filter((s) => typeof s === "string");
- await saveConfig();
- scanCache.clear();
- diffCache.clear();
- sendJson(res, publicConfig());
- return;
- }
- if (pathname === "/api/discover") {
- sendJson(res, { candidates: discoverProjects() });
- return;
- }
- if (pathname === "/api/browse") {
- sendJson(res, browseDirectory(query.get("path")));
- return;
- }
- if (pathname === "/api/scan") {
- const targetRoot = resolveTarget(query);
- const scope = query.get("scope") || "all";
- const includeBuild = query.get("includeBuild") === "1";
- const withStats = query.get("stats") !== "0";
- const data = await getScan(targetRoot, scope, {
- includeBuild,
- withStats,
- refresh: query.get("refresh") === "1",
- });
- sendJson(res, data);
- return;
- }
- if (pathname === "/api/diff") {
- const targetRoot = resolveTarget(query);
- const relPath = query.get("path");
- if (!relPath) throw new Error("缺少 path 参数");
- const data = await getDiff(targetRoot, relPath, {
- fromPath: query.get("from") || relPath,
- includeBuild: query.get("includeBuild") === "1",
- onlyDiff: query.get("onlyDiff") === "1",
- ignoreWs: query.get("ignoreWs") === "1",
- context: query.get("context") ? Number(query.get("context")) : 3,
- });
- sendJson(res, data);
- return;
- }
- if (req.method === "GET") {
- await serveStatic(req, res, pathname);
- return;
- }
- res.writeHead(405).end("method not allowed");
- } catch (error) {
- sendError(res, error);
- }
- });
- server.listen(PORT, HOST, () => {
- const targetCount = config.targets.length;
- console.log("代码对比工具已启动: http://" + HOST + ":" + PORT);
- console.log("基线目录: " + config.baseline);
- console.log("对比目录: " + targetCount + " 个");
- });
|