54 lines
2.6 KiB
JavaScript
54 lines
2.6 KiB
JavaScript
|
|
/* 扫描模板字面量导致的第三类静默损坏:
|
|||
|
|
JS 在模板字面量里会解释 `\X`(X 为任意字符),因此源码里写 `\n` `\t` `\+` `\.` `\b` 等
|
|||
|
|
会被转成真实换行 / TAB / 丢反斜杠,而 fix-esc.js 只覆盖 `\"` 与行尾 `\`。
|
|||
|
|
|
|||
|
|
本脚本只报告,不修改。判读原则:
|
|||
|
|
- `<pre>` / `<code>` 内出现的这些序列,**几乎都是损坏**(命令/regex/awk 需要字面反斜杠)
|
|||
|
|
- 正文散文里出现的,通常无害(作者本意可能就是换行)
|
|||
|
|
用法:node .sre-s23/scan-escapes.js [dir ...]
|
|||
|
|
*/
|
|||
|
|
const fs = require("fs");
|
|||
|
|
const path = require("path");
|
|||
|
|
const DIR = path.resolve(__dirname, "content");
|
|||
|
|
|
|||
|
|
/* JS 会解释的转义;其余 `\X` 会退化成 X(丢反斜杠) */
|
|||
|
|
const NAMED = { n: "换行", t: "TAB", r: "回车", b: "退格(\\b 常见于正则单词边界)", f: "换页", v: "垂直制表", "0": "NUL" };
|
|||
|
|
/* 这些在 shell / regex / awk 里几乎总是想要字面反斜杠 */
|
|||
|
|
const DEGRADE = "+.*?$^[](){}|/dswSDW";
|
|||
|
|
|
|||
|
|
const targets = process.argv.slice(2).length
|
|||
|
|
? process.argv.slice(2)
|
|||
|
|
: fs.readdirSync(DIR).filter(f => f.endsWith(".js")).map(f => f.replace(/\.js$/, "")).sort();
|
|||
|
|
|
|||
|
|
let grand = 0;
|
|||
|
|
for (const name of targets) {
|
|||
|
|
const p = path.join(DIR, name + ".js");
|
|||
|
|
if (!fs.existsSync(p)) { console.log(`… ${name}:无此文件`); continue; }
|
|||
|
|
const src = fs.readFileSync(p, "utf8");
|
|||
|
|
const tick = src.indexOf("`");
|
|||
|
|
const body = tick < 0 ? "" : src.slice(tick);
|
|||
|
|
|
|||
|
|
/* 只关心代码块内的:把 <pre>...</pre> 与 <code>...</code> 内容抽出来 */
|
|||
|
|
const regions = [];
|
|||
|
|
for (const m of body.matchAll(/<pre[\s\S]*?<\/pre>/g)) regions.push(m[0]);
|
|||
|
|
for (const m of body.matchAll(/<code>[\s\S]*?<\/code>/g)) regions.push(m[0]);
|
|||
|
|
|
|||
|
|
const hits = [];
|
|||
|
|
for (const r of regions) {
|
|||
|
|
for (const m of r.matchAll(/(?<!\\)\\(.)/g)) {
|
|||
|
|
const ch = m[1];
|
|||
|
|
if (ch === "\\" || ch === '"' || ch === "`" || ch === "$" || ch === "\n") continue; // 有意转义
|
|||
|
|
hits.push({ ch, label: NAMED[ch] || (DEGRADE.includes(ch) ? "丢反斜杠" : "其它") });
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
if (!hits.length) { console.log(`✓ ${name}:代码块内无风险转义`); continue; }
|
|||
|
|
const by = {};
|
|||
|
|
hits.forEach(h => { const k = "\\" + h.ch + " (" + h.label + ")"; by[k] = (by[k] || 0) + 1; });
|
|||
|
|
const total = hits.length;
|
|||
|
|
grand += total;
|
|||
|
|
console.log(`✗ ${name}:代码块内 ${total} 处风险转义`);
|
|||
|
|
Object.entries(by).sort((a, b) => b[1] - a[1]).slice(0, 10)
|
|||
|
|
.forEach(([k, v]) => console.log(` ${k} × ${v}`));
|
|||
|
|
}
|
|||
|
|
console.log(grand ? `\n共 ${grand} 处(需人工判断:代码块内的基本都是损坏)` : "\nOK 代码块内没有会退化的转义");
|