"""The shared lint rules for commit messages, PR titles, and PR bodies.""" from __future__ import annotations import re from dataclasses import dataclass ALLOWED_TYPES = { "feat", "fix", "docs", "refactor", "perf", "test", "build", "ci", "chore", "revert", } HEADER_RE = re.compile(r"^(?P[a-z]+)(?:\((?P[a-z0-9_*.-]+)\))?: (?P.+)$") @dataclass(frozen=True) class LintResult: errors: list[str] @property def ok(self) -> bool: return not self.errors def check_commit_message(message: str) -> LintResult: return _check_message(message) def check_pr_title(title: str) -> LintResult: return _check_message(title) def check_pr_body(body: str) -> LintResult: """The PR body becomes the squash commit body, so it must be ASCII-only. Only the ASCII rule applies (the body is free-form Markdown, not a Conventional-Commits header), so the header/subject checks are skipped. """ errors: list[str] = [] if not _is_ascii(body): errors.append("must be ASCII-only English") return LintResult(errors) def _check_message(message: str) -> LintResult: errors: list[str] = [] text = message.strip() header = text.splitlines()[0] if text else "" if header.startswith(("fixup!", "squash!")): errors.append("fixup/squash commits are not allowed") return LintResult(errors) if header.startswith("Merge "): errors.append("merge commits are not allowed in PR ranges") return LintResult(errors) if not _is_ascii(text): errors.append("must be ASCII-only English") match = HEADER_RE.match(header) if not match: errors.append("must match (): ") return LintResult(errors) commit_type = match.group("type") subject = match.group("subject") if commit_type not in ALLOWED_TYPES: errors.append(f"type must be one of: {', '.join(sorted(ALLOWED_TYPES))}") first_alpha = next((ch for ch in subject if ch.isalpha()), "") if first_alpha and not first_alpha.islower(): errors.append("subject must start lowercase") if subject.endswith((".", "!", "?")): errors.append("subject must not end with punctuation") return LintResult(errors) def _is_ascii(text: str) -> bool: try: text.encode("ascii") except UnicodeEncodeError: return False return True