1
0

check-grammar.mjs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. #!/usr/bin/env node
  2. // 验证 README 附录「正式语法」:正反例断言、README 示例断言、项目历史提交检查
  3. // 用法:node scripts/check-grammar.mjs
  4. import assert from "node:assert/strict";
  5. import { execSync } from "node:child_process";
  6. import { readFileSync } from "node:fs";
  7. import { fileURLToPath } from "node:url";
  8. const REPO_DIR = fileURLToPath(new URL("..", import.meta.url));
  9. // 正则与 README 附录「正式语法」同步维护
  10. const TITLE_RE =
  11. /^【(?<type>初始|更改|新增|修复|格式|文档|测试|维护)(?:,(?<scope>[\p{Script=Han}A-Za-z0-9_-]{1,16}))?】(?<summary>[^\n]{1,60})$/u;
  12. const HAN_ONLY_RE = /^[\p{Script=Han}]+$/u;
  13. const ISSUE_RE = /#\d+/u;
  14. // 解析提交信息;结构违规时抛出带原因的错误
  15. function parse(message) {
  16. const text = message.replace(/\r\n/g, "\n").replace(/^\uFEFF/, "");
  17. const lines = text.split("\n");
  18. const titleLine = lines[0] ?? "";
  19. const m = TITLE_RE.exec(titleLine);
  20. if (!m) {
  21. throw new Error(titleLine === "" ? "标题缺失" : "标题不符合语法");
  22. }
  23. const rest = lines.slice(1);
  24. if (rest.length > 0 && rest[0] !== "") {
  25. throw new Error("描述必须以一个空行与标题相隔");
  26. }
  27. let description = null;
  28. if (rest.length > 1) {
  29. const body = rest.slice(1).join("\n").replace(/\n+$/, "");
  30. if (body !== "") description = body;
  31. }
  32. return {
  33. type: m.groups.type,
  34. scope: m.groups.scope ?? null,
  35. summary: m.groups.summary,
  36. description,
  37. };
  38. }
  39. // 警告项(解析器应接受并提示)
  40. function warnings(parsed) {
  41. const ws = [];
  42. if (HAN_ONLY_RE.test(parsed.summary) && [...parsed.summary].length > 30) {
  43. ws.push("摘要为纯汉字且超过 30 汉字(人工建议)");
  44. }
  45. if (ISSUE_RE.test(parsed.summary)) {
  46. ws.push("标题包含问题编号,应移至描述");
  47. }
  48. return ws;
  49. }
  50. // —— 命令行模式:检查提交信息文件(commit-msg 钩子)——
  51. // simp: 只过滤 git 注释行(# 开头);正文中顶格的 #568 行同样被过滤,
  52. // 与 git 默认 cleanup 行为一致,故钩子不单独校验描述中的问题编号。
  53. const [mode, filePath] = process.argv.slice(2);
  54. if (mode === "--file") {
  55. if (!filePath) {
  56. console.error("用法:node scripts/check-grammar.mjs --file <路径>");
  57. process.exit(2);
  58. }
  59. const cleaned = readFileSync(filePath, "utf8")
  60. .split("\n")
  61. .filter((line) => !line.startsWith("#"))
  62. .join("\n")
  63. .trim();
  64. if (cleaned === "") {
  65. console.error("错误:提交信息为空");
  66. process.exit(1);
  67. }
  68. try {
  69. const parsed = parse(cleaned);
  70. const ws = warnings(parsed);
  71. if (ws.length > 0) {
  72. console.warn("警告:\n" + ws.map((w) => `- ${w}`).join("\n"));
  73. }
  74. } catch (e) {
  75. console.error(`错误:${e.message}`);
  76. process.exit(1);
  77. }
  78. process.exit(0);
  79. }
  80. // 正例与反例(与 README 附录表格一致)
  81. const positives = [
  82. ["最小提交", "【修复】解决登录界面的输入验证问题"],
  83. ["带范围", "【修复,认证】解决登录界面的输入验证问题"],
  84. ["摘要 60 码点上限", "【新增】" + "a".repeat(60)],
  85. [
  86. "带描述",
  87. "【修复,认证】解决登录界面的输入验证问题\n\n修复了登录界面中输入验证逻辑的问题。\n\n相关问题编号:\n\n#568",
  88. ],
  89. ];
  90. const negatives = [
  91. ["摘要为空", "【初始】"],
  92. ["类型不在枚举内", "【验证】执行检查"],
  93. ["缺少左括号", "修复】解决登录界面的输入验证问题"],
  94. ["半角逗号", "【修复,认证】解决登录界面的输入验证问题"],
  95. ["范围含空格", "【修复, 认证】解决登录界面的输入验证问题"],
  96. ["摘要超过 60 码点", "【新增】" + "a".repeat(61)],
  97. ["描述未以空行相隔", "【修复】解决登录界面的输入验证问题\n第二行直接开始"],
  98. ["空消息", ""],
  99. ];
  100. let checked = 0;
  101. for (const [name, msg] of positives) {
  102. assert.doesNotThrow(() => parse(msg), `正例应合法:${name}`);
  103. checked++;
  104. }
  105. for (const [name, msg] of negatives) {
  106. assert.throws(() => parse(msg), `反例应非法:${name}`);
  107. checked++;
  108. }
  109. // 警告项断言
  110. assert.equal(
  111. warnings(parse("【新增】" + "功".repeat(31))).length,
  112. 1,
  113. "纯汉字摘要超过 30 汉字应发出警告",
  114. );
  115. assert.equal(
  116. warnings(parse("【修复】解决 #568 问题")).length,
  117. 1,
  118. "标题包含问题编号应发出警告",
  119. );
  120. checked += 2;
  121. // README 正文(附录之前)中所有标题示例必须合法
  122. // simp: 只提取附录之前的部分;附录表格示例与下方 positives/negatives 同步维护,
  123. // 避免把反例行也当作必须合法的示例(天花板:附录表格新增示例需同步脚本)。
  124. const readme = readFileSync(`${REPO_DIR}README.md`, "utf8");
  125. const examples = [
  126. ...readme.split("## 附录")[0].matchAll(/^[ \t]*【[^\n]+$/gm),
  127. ].map((m) => m[0].trim());
  128. for (const line of examples) {
  129. assert.doesNotThrow(() => parse(line), `README 示例应合法:${line}`);
  130. }
  131. // 项目历史提交检查(报告,不阻塞)
  132. // simp: 历史提交本身存在违规(如【初始】),故只报告不断言,避免脚本永远失败。
  133. let history = [];
  134. try {
  135. const log = execSync("git log --format=%s%x00", { cwd: REPO_DIR }).toString();
  136. // git 每条记录后附加换行,NUL 分割后需去除首尾空白
  137. history = log
  138. .split("\0")
  139. .map((m) => m.trim())
  140. .filter((m) => m !== "");
  141. } catch {
  142. console.log("(跳过历史检查:非 git 环境)");
  143. }
  144. const report = [];
  145. for (const msg of history) {
  146. try {
  147. const ws = warnings(parse(msg));
  148. if (ws.length > 0) report.push(`${msg}:${ws.join(";")}`);
  149. } catch (e) {
  150. report.push(`${msg}:${e.message}`);
  151. }
  152. }
  153. console.log(
  154. `断言通过:${checked} 个正反例与警告断言、${examples.length} 个 README 示例、${history.length} 条历史提交`,
  155. );
  156. if (report.length > 0) {
  157. console.log("历史提交检查报告(不阻塞):");
  158. for (const r of report) console.log(`- ${r}`);
  159. } else {
  160. console.log("历史提交检查报告:全部合规");
  161. }