包文件→ .shtukbase/packages/std-conventional-commits/checks/cclib.ts
checks/cclib.ts
127 行, 6.1 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // Conventional Commits 1.0.0 (https://www.conventionalcommits.org/en/v1.0.0/): parsing a commit message and the
- // findings per norm. CC-R01 — the header; CC-R02 — body and footers; CC-R03 — short header (a common practice,
- // not the specification). Git is only read (git log).
- import { git, list, settings } from './lib/std.ts';
- export const PKG = 'std-conventional-commits';
- export const DEFAULTS = {
- types: ['feat', 'fix', 'build', 'chore', 'ci', 'docs', 'style', 'refactor', 'perf', 'test', 'revert'],
- scopes: [] as string[],
- since: '',
- last: 50,
- range: '',
- ignore: ['^Merge ', '^Revert "', '^(fixup|squash|amend)! ', '^Initial commit$'],
- maxHeader: 100,
- };
- export type Config = typeof DEFAULTS;
- export function config(): Config {
- const c = settings('conventional-commits', DEFAULTS);
- 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() };
- }
- /** A day as YYYY-MM-DD (YAML may give a date object). */
- export function day(v: unknown): string {
- if (v instanceof Date) return v.toISOString().slice(0, 10);
- return String(v ?? '').trim();
- }
- export const HEADER = /^(?<type>[A-Za-z][A-Za-z0-9-]*)(?:\((?<scope>[^()\r\n]*)\))?(?<bang>!)?: (?<desc>.*)$/;
- export type Finding = { rule: 'CC-R01' | 'CC-R02' | 'CC-R03'; text: string };
- /** The message as git keeps it: comment lines and everything below the scissors line dropped, outer blank lines trimmed. */
- export function clean(raw: string): string {
- const lines: string[] = [];
- for (const l of raw.replace(/\r\n/g, '\n').split('\n')) {
- if (/^# -+ >8 -+$/.test(l)) break;
- if (l.startsWith('#')) continue;
- lines.push(l.trimEnd());
- }
- return lines.join('\n').replace(/^\n+|\n+$/g, '');
- }
- export function ignored(message: string, cfg: Config): boolean {
- const header = message.split('\n')[0] ?? '';
- return cfg.ignore.some((re) => {
- try {
- return new RegExp(re).test(header);
- } catch {
- return false;
- }
- });
- }
- /** Breaking change: `!` in the header or a BREAKING CHANGE / BREAKING-CHANGE footer. */
- export function isBreaking(message: string): boolean {
- const m = HEADER.exec(message.split('\n')[0] ?? '');
- return !!m?.groups?.bang || /^BREAKING[ -]CHANGE: /m.test(message);
- }
- export function lint(message: string, cfg: Config): Finding[] {
- const out: Finding[] = [];
- const lines = message.split('\n');
- const header = lines[0] ?? '';
- const m = HEADER.exec(header);
- if (!header.trim()) out.push({ rule: 'CC-R01', text: 'empty message' });
- else if (!m?.groups) out.push({ rule: 'CC-R01', text: 'the header is not in the form "type(scope)!: description"' });
- else {
- const g = m.groups;
- 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(', ')})` });
- if (g.scope !== undefined) {
- if (!g.scope.trim()) out.push({ rule: 'CC-R01', text: 'empty scope in parentheses' });
- 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(', ')})` });
- }
- if (!g.desc.trim() || /^\s/.test(g.desc)) out.push({ rule: 'CC-R01', text: 'no description right after ": "' });
- if (cfg.maxHeader && header.length > cfg.maxHeader) out.push({ rule: 'CC-R03', text: `the header is ${header.length} long > ${cfg.maxHeader}` });
- if (/\.$/.test(g.desc.trim())) out.push({ rule: 'CC-R03', text: 'the description ends with a period' });
- }
- 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' });
- for (const l of lines.slice(1)) {
- const b = /^(breaking[ -]change)\s*:(.*)$/i.exec(l);
- if (!b) continue;
- 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` });
- else if (!/^ \S/.test(b[2])) out.push({ rule: 'CC-R02', text: `after "${b[1]}:" a space and a description are needed` });
- }
- return out;
- }
- export type Commit = { sha: string; message: string };
- /** The commits to check: `--range a..b`, else `--last N` / settings `range`, `last` and `since` (commits before the
- * adoption day are history and are not judged). Merge commits are skipped. A project inside a larger repository
- * sees only the commits that touch its folder. */
- export function commits(cfg: Config, f: Record<string, string | true>): Commit[] | null {
- const args = ['log', '--no-merges', '--format=%H%x1f%B%x1e'];
- const range = typeof f.range === 'string' ? f.range : f.all ? '' : cfg.range;
- const last = typeof f.last === 'string' ? Number(f.last) : f.all ? 0 : cfg.last;
- const since = typeof f.since === 'string' ? f.since : f.all ? '' : cfg.since;
- if (last > 0) args.push(`-n${last}`);
- if (since) args.push(`--since=${since} 00:00:00`);
- if (range) args.push(range);
- const prefix = git(['rev-parse', '--show-prefix'])?.trim();
- if (prefix === undefined) return null;
- if (prefix) args.push('--', '.');
- if (git(['rev-parse', '--verify', '-q', 'HEAD']) === null) return [];
- const out = git(args);
- if (out === null) return null;
- return out.split('\x1e').map((s) => s.replace(/^\n+/, '')).filter(Boolean).map((s) => {
- const [sha, message] = s.split('\x1f');
- return { sha: sha.trim(), message: clean(message ?? '') };
- });
- }
- /** Findings of one rule over the selected commits, one line each: short hash, header, what is wrong. */
- export function checkCommits(rule: Finding['rule'], f: Record<string, string | true>): string[] {
- const cfg = config();
- const cs = commits(cfg, f);
- if (cs === null) return []; // not a git repository: no commits, nothing to judge
- const out: string[] = [];
- for (const c of cs) {
- if (ignored(c.message, cfg)) continue;
- const header = (c.message.split('\n')[0] ?? '').slice(0, 80);
- for (const x of lint(c.message, cfg).filter((x) => x.rule === rule)) out.push(`commit ${c.sha.slice(0, 10)} "${header}": ${x.text}`);
- }
- return out;
- }