check-grammar.mjs 5.6 KB

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