ShtukbaseStandard
包文件→ .shtukbase/packages/std-conventional-commits/checks/cclib.ts

checks/cclib.ts

127 行, 6.1 KB.

文件按包中的原样显示:代码及其注释不做翻译。

  1. // Conventional Commits 1.0.0 (https://www.conventionalcommits.org/en/v1.0.0/): parsing a commit message and the
  2. // findings per norm. CC-R01 — the header; CC-R02 — body and footers; CC-R03 — short header (a common practice,
  3. // not the specification). Git is only read (git log).
  4. import { git, list, settings } from './lib/std.ts';
  5. export const PKG = 'std-conventional-commits';
  6. export const DEFAULTS = {
  7. types: ['feat', 'fix', 'build', 'chore', 'ci', 'docs', 'style', 'refactor', 'perf', 'test', 'revert'],
  8. scopes: [] as string[],
  9. since: '',
  10. last: 50,
  11. range: '',
  12. ignore: ['^Merge ', '^Revert "', '^(fixup|squash|amend)! ', '^Initial commit$'],
  13. maxHeader: 100,
  14. };
  15. export type Config = typeof DEFAULTS;
  16. export function config(): Config {
  17. const c = settings('conventional-commits', DEFAULTS);
  18. return { ...c, types: list(c.types).map((t) => t.toLowerCase()), scopes: list(c.scopes), ignore: list(c.ignore), last: Number(c.last) || 0, maxHeader: Number(c.maxHeader) || 0, since: day(c.since), range: String(c.range ?? '').trim() };
  19. }
  20. /** A day as YYYY-MM-DD (YAML may give a date object). */
  21. export function day(v: unknown): string {
  22. if (v instanceof Date) return v.toISOString().slice(0, 10);
  23. return String(v ?? '').trim();
  24. }
  25. export const HEADER = /^(?<type>[A-Za-z][A-Za-z0-9-]*)(?:\((?<scope>[^()\r\n]*)\))?(?<bang>!)?: (?<desc>.*)$/;
  26. export type Finding = { rule: 'CC-R01' | 'CC-R02' | 'CC-R03'; text: string };
  27. /** The message as git keeps it: comment lines and everything below the scissors line dropped, outer blank lines trimmed. */
  28. export function clean(raw: string): string {
  29. const lines: string[] = [];
  30. for (const l of raw.replace(/\r\n/g, '\n').split('\n')) {
  31. if (/^# -+ >8 -+$/.test(l)) break;
  32. if (l.startsWith('#')) continue;
  33. lines.push(l.trimEnd());
  34. }
  35. return lines.join('\n').replace(/^\n+|\n+$/g, '');
  36. }
  37. export function ignored(message: string, cfg: Config): boolean {
  38. const header = message.split('\n')[0] ?? '';
  39. return cfg.ignore.some((re) => {
  40. try {
  41. return new RegExp(re).test(header);
  42. } catch {
  43. return false;
  44. }
  45. });
  46. }
  47. /** Breaking change: `!` in the header or a BREAKING CHANGE / BREAKING-CHANGE footer. */
  48. export function isBreaking(message: string): boolean {
  49. const m = HEADER.exec(message.split('\n')[0] ?? '');
  50. return !!m?.groups?.bang || /^BREAKING[ -]CHANGE: /m.test(message);
  51. }
  52. export function lint(message: string, cfg: Config): Finding[] {
  53. const out: Finding[] = [];
  54. const lines = message.split('\n');
  55. const header = lines[0] ?? '';
  56. const m = HEADER.exec(header);
  57. if (!header.trim()) out.push({ rule: 'CC-R01', text: 'empty message' });
  58. else if (!m?.groups) out.push({ rule: 'CC-R01', text: 'the header is not in the form "type(scope)!: description"' });
  59. else {
  60. const g = m.groups;
  61. if (cfg.types.length && !cfg.types.includes(g.type.toLowerCase())) out.push({ rule: 'CC-R01', text: `type "${g.type}" is not in the list (${cfg.types.join(', ')})` });
  62. if (g.scope !== undefined) {
  63. if (!g.scope.trim()) out.push({ rule: 'CC-R01', text: 'empty scope in parentheses' });
  64. else if (cfg.scopes.length && !cfg.scopes.includes(g.scope.trim())) out.push({ rule: 'CC-R01', text: `scope "${g.scope}" is not in the list (${cfg.scopes.join(', ')})` });
  65. }
  66. if (!g.desc.trim() || /^\s/.test(g.desc)) out.push({ rule: 'CC-R01', text: 'no description right after ": "' });
  67. if (cfg.maxHeader && header.length > cfg.maxHeader) out.push({ rule: 'CC-R03', text: `the header is ${header.length} long > ${cfg.maxHeader}` });
  68. if (/\.$/.test(g.desc.trim())) out.push({ rule: 'CC-R03', text: 'the description ends with a period' });
  69. }
  70. if (lines.length > 1 && lines[1].trim() !== '') out.push({ rule: 'CC-R02', text: 'the body or footer is not separated from the header by an empty line' });
  71. for (const l of lines.slice(1)) {
  72. const b = /^(breaking[ -]change)\s*:(.*)$/i.exec(l);
  73. if (!b) continue;
  74. if (b[1] !== 'BREAKING CHANGE' && b[1] !== 'BREAKING-CHANGE') out.push({ rule: 'CC-R02', text: `the footer "${b[1]}" is written in capitals: BREAKING CHANGE` });
  75. else if (!/^ \S/.test(b[2])) out.push({ rule: 'CC-R02', text: `after "${b[1]}:" a space and a description are needed` });
  76. }
  77. return out;
  78. }
  79. export type Commit = { sha: string; message: string };
  80. /** The commits to check: `--range a..b`, else `--last N` / settings `range`, `last` and `since` (commits before the
  81. * adoption day are history and are not judged). Merge commits are skipped. A project inside a larger repository
  82. * sees only the commits that touch its folder. */
  83. export function commits(cfg: Config, f: Record<string, string | true>): Commit[] | null {
  84. const args = ['log', '--no-merges', '--format=%H%x1f%B%x1e'];
  85. const range = typeof f.range === 'string' ? f.range : f.all ? '' : cfg.range;
  86. const last = typeof f.last === 'string' ? Number(f.last) : f.all ? 0 : cfg.last;
  87. const since = typeof f.since === 'string' ? f.since : f.all ? '' : cfg.since;
  88. if (last > 0) args.push(`-n${last}`);
  89. if (since) args.push(`--since=${since} 00:00:00`);
  90. if (range) args.push(range);
  91. const prefix = git(['rev-parse', '--show-prefix'])?.trim();
  92. if (prefix === undefined) return null;
  93. if (prefix) args.push('--', '.');
  94. if (git(['rev-parse', '--verify', '-q', 'HEAD']) === null) return [];
  95. const out = git(args);
  96. if (out === null) return null;
  97. return out.split('\x1e').map((s) => s.replace(/^\n+/, '')).filter(Boolean).map((s) => {
  98. const [sha, message] = s.split('\x1f');
  99. return { sha: sha.trim(), message: clean(message ?? '') };
  100. });
  101. }
  102. /** Findings of one rule over the selected commits, one line each: short hash, header, what is wrong. */
  103. export function checkCommits(rule: Finding['rule'], f: Record<string, string | true>): string[] {
  104. const cfg = config();
  105. const cs = commits(cfg, f);
  106. if (cs === null) return []; // not a git repository: no commits, nothing to judge
  107. const out: string[] = [];
  108. for (const c of cs) {
  109. if (ignored(c.message, cfg)) continue;
  110. const header = (c.message.split('\n')[0] ?? '').slice(0, 80);
  111. for (const x of lint(c.message, cfg).filter((x) => x.rule === rule)) out.push(`commit ${c.sha.slice(0, 10)} "${header}": ${x.text}`);
  112. }
  113. return out;
  114. }