55 lines
2.5 KiB
JavaScript
55 lines
2.5 KiB
JavaScript
|
|
/* 修复模板字面量导致的两类静默损坏(只作用于正文区,即第一个反引号之后):
|
|||
|
|
① 单反斜杠 + 引号 `\"` → `\\"` (本该显示的 \" 被退化成 ")
|
|||
|
|
② 行尾单反斜杠 `\` → `\\` (本该显示的 bash 续行符吞掉了换行,命令被粘成一行)
|
|||
|
|
用法:
|
|||
|
|
node .sre-s23/fix-esc.js <dir> 只报告(dry run)
|
|||
|
|
node .sre-s23/fix-esc.js <dir> --write 实际写回
|
|||
|
|
*/
|
|||
|
|
const fs = require("fs");
|
|||
|
|
const path = require("path");
|
|||
|
|
const DIR = path.resolve(__dirname, "content");
|
|||
|
|
|
|||
|
|
const dir = process.argv[2];
|
|||
|
|
const write = process.argv.includes("--write");
|
|||
|
|
if (!dir) { console.error("用法:node .sre-s23/fix-esc.js <dir> [--write]"); process.exit(1); }
|
|||
|
|
|
|||
|
|
const p = path.join(DIR, dir + ".js");
|
|||
|
|
const src = fs.readFileSync(p, "utf8");
|
|||
|
|
const firstTick = src.indexOf("`");
|
|||
|
|
if (firstTick < 0) { console.error("找不到模板字面量起点"); process.exit(1); }
|
|||
|
|
const head = src.slice(0, firstTick);
|
|||
|
|
const body = src.slice(firstTick);
|
|||
|
|
|
|||
|
|
const headBad = (head.match(/(?<!\\)\\"/g) || []).length;
|
|||
|
|
if (headBad) console.error(`⚠ JS 字段区有 ${headBad} 处 \\",脚本不会碰,请人工确认`);
|
|||
|
|
|
|||
|
|
/* 统计与定位 */
|
|||
|
|
let quoteHits = 0, contHits = 0;
|
|||
|
|
const qLines = [], cLines = [];
|
|||
|
|
body.split("\n").forEach((ln, i) => {
|
|||
|
|
const q = (ln.match(/(?<!\\)\\"/g) || []).length;
|
|||
|
|
if (q) { quoteHits += q; qLines.push(`${i + 1} ×${q} ${ln.trim().slice(0, 100)}`); }
|
|||
|
|
// 行尾单个反斜杠(前面不是反斜杠)
|
|||
|
|
if (/(?<!\\)\\$/.test(ln)) { contHits++; cLines.push(`${i + 1} ${ln.trim().slice(0, 100)}`); }
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
console.log(`${dir}:`);
|
|||
|
|
console.log(` ① 单反斜杠 \\" ${quoteHits} 处`);
|
|||
|
|
qLines.slice(0, 8).forEach(l => console.log(" L" + l));
|
|||
|
|
if (qLines.length > 8) console.log(` … 另 ${qLines.length - 8} 行`);
|
|||
|
|
console.log(` ② 行尾单反斜杠 \\ ${contHits} 处`);
|
|||
|
|
cLines.slice(0, 8).forEach(l => console.log(" L" + l));
|
|||
|
|
if (cLines.length > 8) console.log(` … 另 ${cLines.length - 8} 行`);
|
|||
|
|
|
|||
|
|
if (write && (quoteHits || contHits)) {
|
|||
|
|
const fixed = head + body
|
|||
|
|
.replace(/(?<!\\)\\"/g, '\\\\"')
|
|||
|
|
.replace(/(?<!\\)\\$/gm, "\\\\");
|
|||
|
|
fs.writeFileSync(p, fixed, "utf8");
|
|||
|
|
const nb = fs.readFileSync(p, "utf8").slice(firstTick);
|
|||
|
|
console.log(`\n已写回;复查:单反斜杠 \\" = ${(nb.match(/(?<!\\)\\"/g) || []).length} 处,` +
|
|||
|
|
`行尾单反斜杠 = ${(nb.split("\n").filter(l => /(?<!\\)\\$/.test(l))).length} 处`);
|
|||
|
|
} else if (!write) {
|
|||
|
|
console.log("\n(dry run,未写盘;加 --write 实际写入)");
|
|||
|
|
}
|