Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

ci(changelog): fail loud on undeclared towncrier fragment categories (#5045)

LearningCircuitb964d3282904
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index cad3c1f56c..44934c76ef 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -383,6 +383,14 @@ repos:
always_run: true
verbose: true
description: "Remind contributors about subsystem fast tests and opt-in live tests"
+ - id: check-changelog-fragments
+ name: Check changelog fragment names
+ entry: .pre-commit-hooks/check-changelog-fragments.py
+ language: script
+ files: ^changelog\.d/
+ pass_filenames: false
+ description: "Fail on changelog.d/ fragments with undeclared towncrier categories -
+ towncrier silently drops them from the rendered release notes"
- id: recommend-release-notes
name: Release Notes Reminder
entry: .pre-commit-hooks/recommend-release-notes.py
diff --git a/.pre-commit-hooks/_changelog_fragments.py b/.pre-commit-hooks/_changelog_fragments.py
new file mode 100644
index 0000000000..a26bd06c60
--- /dev/null
+++ b/.pre-commit-hooks/_changelog_fragments.py
@@ -0,0 +1,56 @@
+"""Shared helpers for changelog.d/ fragment-name validation.
+
+Used by the blocking ``check-changelog-fragments`` hook and the advisory
+``recommend-release-notes`` hook so the fragment grammar and category
+list can't drift between them.
+"""
+
+import re
+import tomllib
+from pathlib import Path
+
+# changelog.d/<id>.<category>[.<n>].md or changelog.d/+<slug>.<category>[.<n>].md
+# - <id>: integer PR/issue number
+# - +<slug>: orphan fragment with no PR/issue, slug is [A-Za-z0-9_-]+
+# - .<n>: optional integer counter suffix for multiple fragments of the
+# same (id, category) — towncrier renders each as a separate bullet,
+# all linked back to the same PR/issue.
+FRAGMENT_RE = re.compile(
+ r"^(?:\d+|\+[A-Za-z0-9_-]+)\.(?P<category>[a-z]+)(?:\.\d+)?\.md$"
+)
+
+
+def load_categories(pyproject_path):
+ """Read ``[[tool.towncrier.type]].directory`` entries from pyproject.toml.
+
+ Raises on an unreadable file or a missing/empty type table. The
+ advisory hook catches and falls back to a default list; the blocking
+ hook lets the error propagate so a broken towncrier config fails
+ loud instead of validating against a guessed category list.
+ """
+ with Path(pyproject_path).open("rb") as fh:
+ cfg = tomllib.load(fh)
+ types = cfg["tool"]["towncrier"]["type"]
+ cats = tuple(t["directory"] for t in types if "directory" in t)
+ if not cats:
+ raise ValueError(
+ f"no [[tool.towncrier.type]] entries in {pyproject_path}"
+ )
+ return cats
+
+
+def classify_fragment(name, categories):
+ """Classify a fragment filename against the grammar and *categories*.
+
+ Returns ``("ok", category)`` for a valid fragment, ``("bad-category",
+ category)`` for a well-formed name whose category isn't declared, or
+ ``("bad-name", None)`` for a filename that doesn't match the fragment
+ pattern at all.
+ """
+ m = FRAGMENT_RE.match(name)
+ if not m:
+ return "bad-name", None
+ category = m.group("category")
+ if category not in categories:
+ return "bad-category", category
+ return "ok", category
diff --git a/.pre-commit-hooks/check-changelog-fragments.py b/.pre-commit-hooks/check-changelog-fragments.py
new file mode 100755
index 0000000000..866f0378f1
--- /dev/null
+++ b/.pre-commit-hooks/check-changelog-fragments.py
@@ -0,0 +1,81 @@
+#!/usr/bin/env python3
+"""Fail on invalid changelog.d/ fragment filenames.
+
+towncrier only renders fragments whose category is declared in
+``[[tool.towncrier.type]]``; anything else is silently dropped from the
+release notes (and ``towncrier check`` errors on it). #5023's fragment
+shipped as ``.refactor.md`` — an undeclared category — and would have
+vanished from the next release; the advisory reminder hook printed a
+warning but nothing failed. This hook is the blocking counterpart: it
+validates every file in changelog.d/ (not just staged ones, so CI's
+``pre-commit run --all-files`` enforces it on the whole tree) and exits
+non-zero on any problem.
+"""
+
+import argparse
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from _changelog_fragments import classify_fragment, load_categories
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+
+
+def validate_directory(changelog_dir, categories):
+ """Return one problem string per invalid file in *changelog_dir*.
+
+ Every regular file except README.md must be a valid fragment.
+ Dotfiles are skipped so local editor/OS droppings (e.g. .DS_Store)
+ don't fail commits that never stage them.
+ """
+ problems = []
+ for path in sorted(Path(changelog_dir).iterdir()):
+ if not path.is_file():
+ continue
+ if path.name == "README.md" or path.name.startswith("."):
+ continue
+ kind, category = classify_fragment(path.name, categories)
+ if kind == "bad-name":
+ problems.append(
+ f"{path.name} — does not match `<id>.<category>.md` or "
+ f"`+<slug>.<category>.md`"
+ )
+ elif kind == "bad-category":
+ problems.append(
+ f"{path.name} — unknown category `{category}`; towncrier "
+ f"silently drops it from the release notes. Use one of: "
+ f"{', '.join(categories)}"
+ )
+ return problems
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument(
+ "changelog_dir",
+ nargs="?",
+ default=str(REPO_ROOT / "changelog.d"),
+ help="Directory to validate (defaults to the repo's changelog.d/)",
+ )
+ parser.add_argument(
+ "--pyproject",
+ default=str(REPO_ROOT / "pyproject.toml"),
+ help="pyproject.toml declaring [[tool.towncrier.type]] categories",
+ )
+ args = parser.parse_args(argv)
+
+ categories = load_categories(args.pyproject)
+ problems = validate_directory(args.changelog_dir, categories)
+ if problems:
+ print("Invalid changelog.d/ fragment(s):")
+ for problem in problems:
+ print(f" - {problem}")
+ print("See changelog.d/README.md for the naming convention.")
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/.pre-commit-hooks/recommend-release-notes.py b/.pre-commit-hooks/recommend-release-notes.py
index f3d3c76015..b3876b56b4 100755
--- a/.pre-commit-hooks/recommend-release-notes.py
+++ b/.pre-commit-hooks/recommend-release-notes.py
@@ -12,7 +12,6 @@ Replaces the old shared docs/release_notes/<version>.md model — see
changelog.d/README.md for the rationale and conventions.
"""
-import re
import subprocess
import sys
import tomllib
@@ -20,6 +19,7 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
+from _changelog_fragments import classify_fragment, load_categories
from _commit_analysis import analyze_commit
# Minimum added source lines before the nudge fires
@@ -30,39 +30,25 @@ PYPROJECT = REPO_ROOT / "pyproject.toml"
def _load_categories():
- """Read [[tool.towncrier.type]].directory entries from pyproject.toml so
- the hook stays in sync with the canonical category list. Falls back to
- a sensible default if the file or section is missing — the hook is
- non-blocking so a degraded mode is preferable to a hard failure."""
+ """Load the canonical category list, falling back to a sensible
+ default if pyproject.toml or its towncrier section is unreadable —
+ this hook is non-blocking, so a degraded mode is preferable to a
+ hard failure here (the blocking check-changelog-fragments hook is
+ the one that fails loud on a broken config)."""
try:
- with PYPROJECT.open("rb") as fh:
- cfg = tomllib.load(fh)
- except (OSError, tomllib.TOMLDecodeError):
+ return load_categories(PYPROJECT)
+ except (
+ OSError,
+ tomllib.TOMLDecodeError,
+ KeyError,
+ TypeError,
+ ValueError,
+ ):
return ("breaking", "security", "feature", "bugfix", "removal", "misc")
- types = cfg.get("tool", {}).get("towncrier", {}).get("type", [])
- cats = tuple(t["directory"] for t in types if "directory" in t)
- return cats or (
- "breaking",
- "security",
- "feature",
- "bugfix",
- "removal",
- "misc",
- )
CATEGORIES = _load_categories()
-# changelog.d/<id>.<category>[.<n>].md or changelog.d/+<slug>.<category>[.<n>].md
-# - <id>: integer PR/issue number
-# - +<slug>: orphan fragment with no PR/issue, slug is [A-Za-z0-9_-]+
-# - .<n>: optional integer counter suffix for multiple fragments of the
-# same (id, category) — towncrier renders each as a separate bullet,
-# all linked back to the same PR/issue.
-FRAGMENT_RE = re.compile(
- r"^(?:\d+|\+[A-Za-z0-9_-]+)\.(?P<category>[a-z]+)(?:\.\d+)?\.md$"
-)
-
# Color helpers: only emit ANSI when stdout is a TTY. CI logs and Windows
# terminals without VT processing render the raw escape sequences as
# visible garbage.
@@ -86,20 +72,6 @@ def _fragments_staged():
]
-def _classify_fragment(path):
- """Return ("ok", category) for a valid fragment, ("bad-category", cat)
- for a fragment whose category isn't in CATEGORIES, or ("bad-name", None)
- for a filename that doesn't match the expected pattern at all."""
- name = Path(path).name
- m = FRAGMENT_RE.match(name)
- if not m:
- return "bad-name", None
- category = m.group("category")
- if category not in CATEGORIES:
- return "bad-category", category
- return "ok", category
-
-
def _print_staged_notice(staged):
"""Inform the committer that a news fragment was staged."""
print()
@@ -119,7 +91,7 @@ def _print_staged_notice(staged):
# contributor's note vanishes from the release.
issues = []
for f in staged:
- kind, value = _classify_fragment(f)
+ kind, value = classify_fragment(Path(f).name, CATEGORIES)
if kind != "ok":
issues.append((f, kind, value))
if issues:
diff --git a/tests/hooks/test_check_changelog_fragments.py b/tests/hooks/test_check_changelog_fragments.py
new file mode 100644
index 0000000000..9e26146a8b
--- /dev/null
+++ b/tests/hooks/test_check_changelog_fragments.py
@@ -0,0 +1,194 @@
+"""
+Tests for the check-changelog-fragments pre-commit hook.
+
+Covers the #5023 regression: a fragment named `<id>.refactor.md` used an
+undeclared towncrier category, every gate stayed green (the advisory
+reminder hook only warned), and towncrier would have silently dropped
+the entry from the rendered release notes. The blocking hook must exit
+non-zero for any fragment whose name doesn't match the grammar or whose
+category isn't declared in [[tool.towncrier.type]].
+"""
+
+import subprocess
+import sys
+from pathlib import Path
+
+
+# Add the pre-commit hooks directory to path for the shared module
+HOOKS_DIR = Path(__file__).parent.parent.parent / ".pre-commit-hooks"
+sys.path.insert(0, str(HOOKS_DIR))
+
+from _changelog_fragments import ( # noqa: E402
+ classify_fragment,
+ load_categories,
+)
+
+HOOK_SCRIPT = HOOKS_DIR / "check-changelog-fragments.py"
+REPO_PYPROJECT = HOOKS_DIR.parent / "pyproject.toml"
+
+DECLARED = ("breaking", "security", "feature", "bugfix", "removal", "misc")
+
+
+def _run_hook(tmp_path, filenames, pyproject=None):
+ """Create *filenames* in a changelog dir under tmp_path and run the
+ hook script against it."""
+ changelog = tmp_path / "changelog.d"
+ changelog.mkdir(exist_ok=True)
+ for name in filenames:
+ (changelog / name).write_text("A change.\n")
+ return subprocess.run(
+ [
+ sys.executable,
+ str(HOOK_SCRIPT),
+ str(changelog),
+ "--pyproject",
+ str(pyproject or REPO_PYPROJECT),
+ ],
+ capture_output=True,
+ text=True,
+ )
+
+
+# =========================================================================
+# load_categories
+# =========================================================================
+
+
+class TestLoadCategories:
+ def test_reads_declared_categories_from_repo_pyproject(self):
+ cats = load_categories(REPO_PYPROJECT)
+ assert set(DECLARED) <= set(cats)
+
+ def test_refactor_is_not_a_declared_category(self):
+ # The #5023 regression relied on exactly this: `refactor` looks
+ # plausible but is not declared, so towncrier drops it.
+ assert "refactor" not in load_categories(REPO_PYPROJECT)
+
+ def test_missing_pyproject_raises_instead_of_falling_back(self, tmp_path):
+ try:
+ load_categories(tmp_path / "nope.toml")
+ except OSError:
+ pass
+ else:
+ raise AssertionError("expected OSError for missing pyproject")
+
+
+# =========================================================================
+# classify_fragment
+# =========================================================================
+
+
+class TestClassifyFragment:
+ def test_numbered_fragment_ok(self):
+ assert classify_fragment("5023.bugfix.md", DECLARED) == (
+ "ok",
+ "bugfix",
+ )
+
+ def test_orphan_fragment_ok(self):
+ assert classify_fragment("+lazy-imports.misc.md", DECLARED) == (
+ "ok",
+ "misc",
+ )
+
+ def test_counter_suffix_ok(self):
+ assert classify_fragment("3094.security.2.md", DECLARED) == (
+ "ok",
+ "security",
+ )
+
+ def test_undeclared_category_flagged(self):
+ assert classify_fragment("5023.refactor.md", DECLARED) == (
+ "bad-category",
+ "refactor",
+ )
+
+ def test_uppercase_category_is_bad_name(self):
+ # Category grammar is [a-z]+; towncrier matches case-sensitively.
+ assert classify_fragment("5023.Bugfix.md", DECLARED) == (
+ "bad-name",
+ None,
+ )
+
+ def test_missing_category_is_bad_name(self):
+ assert classify_fragment("notes.md", DECLARED) == ("bad-name", None)
+
+
+# =========================================================================
+# Hook end-to-end (subprocess, like the other check-* hook tests)
+# =========================================================================
+
+
+class TestHookEndToEnd:
+ def test_valid_fragments_pass(self, tmp_path):
+ result = _run_hook(
+ tmp_path,
+ [
+ "5023.bugfix.md",
+ "+lazy-imports.misc.md",
+ "3094.security.2.md",
+ "README.md", # always exempt
+ ],
+ )
+ assert result.returncode == 0, (
+ f"stdout={result.stdout!r} stderr={result.stderr!r}"
+ )
+
+ def test_undeclared_category_fails(self, tmp_path):
+ # THE #5023 regression case.
+ result = _run_hook(tmp_path, ["5023.refactor.md"])
+ assert result.returncode == 1
+ assert "refactor" in result.stdout
+ assert "unknown category" in result.stdout
+
+ def test_orphan_with_undeclared_category_fails(self, tmp_path):
+ result = _run_hook(tmp_path, ["+some-slug.refactor.md"])
+ assert result.returncode == 1
+ assert "unknown category" in result.stdout
+
+ def test_unparseable_name_fails(self, tmp_path):
+ result = _run_hook(tmp_path, ["release-notes-draft.md"])
+ assert result.returncode == 1
+ assert "does not match" in result.stdout
+
+ def test_one_bad_fragment_among_valid_ones_fails(self, tmp_path):
+ result = _run_hook(
+ tmp_path, ["5023.bugfix.md", "5024.refactor.md", "5025.misc.md"]
+ )
+ assert result.returncode == 1
+ assert "5024.refactor.md" in result.stdout
+ assert "5023.bugfix.md" not in result.stdout
+
+ def test_dotfiles_are_ignored(self, tmp_path):
+ result = _run_hook(tmp_path, [".DS_Store", "5023.misc.md"])
+ assert result.returncode == 0, (
+ f"stdout={result.stdout!r} stderr={result.stderr!r}"
+ )
+
+ def test_empty_changelog_dir_passes(self, tmp_path):
+ result = _run_hook(tmp_path, ["README.md"])
+ assert result.returncode == 0
+
+ def test_broken_pyproject_fails_loud_not_silent(self, tmp_path):
+ # No category fallback in the blocking hook: a missing/broken
+ # towncrier config must fail the hook, not validate against a
+ # guessed list.
+ result = _run_hook(
+ tmp_path,
+ ["5023.bugfix.md"],
+ pyproject=tmp_path / "missing.toml",
+ )
+ assert result.returncode != 0
+
+ def test_current_repo_changelog_dir_is_valid(self):
+ # The real changelog.d/ must always pass — if this fails, an
+ # invalid fragment reached the tree and the next release build
+ # would silently drop it.
+ result = subprocess.run(
+ [sys.executable, str(HOOK_SCRIPT)],
+ capture_output=True,
+ text=True,
+ )
+ assert result.returncode == 0, (
+ f"stdout={result.stdout!r} stderr={result.stderr!r}"
+ )