diff --git a/README.md b/README.md index 715e982..25a00c3 100644 --- a/README.md +++ b/README.md @@ -412,7 +412,7 @@ uvx repoplone settings sanity-check See [Migrating from specification 1](#migrating-from-specification-1) for everything the command changes. Before committing the result, review the following: - **Release step ids.** A specification 2 file accepts only `release_python` and `release_node`. The command renames them in `[repository.release]`. Update any script or CI job that passes `--start-step release_backend` or `release_frontend` too. `--start-step` still accepts the old ids, but the new ones are the names to use from now on. -- **Changelog headings.** Package sections in the repository changelog are titled with the package name instead of `Backend` / `Frontend`. Add `section = "Backend"` or `section = "Frontend"` to a `[[package]]` entry to keep the old heading. +- **Changelog headings.** Package sections in the repository changelog are titled with the package name instead of `Backend` / `Frontend`. Add `towncrier.section = "Backend"` or `towncrier.section = "Frontend"` to a `[[package]]` entry to keep the old heading. - **Comments.** A comment placed between the end of `[frontend.package]` and the next table may be dropped. The command reports each one so you can restore it. - **Project release hooks.** `settings.backend` and `settings.frontend` still return the primary package of the `python` and `node` families, so existing `local_step` hooks keep working. @@ -489,7 +489,7 @@ primary = true name = "acme.core" path = "backend" changelog = "backend/CHANGELOG.md" -towncrier_settings = "backend/pyproject.toml" +towncrier.section = "Backend" base_package = "Products.CMFPlone" publish = true @@ -498,7 +498,6 @@ type = "python-plone" name = "acme.theme" path = "backend/sources/acme.theme" changelog = "backend/sources/acme.theme/CHANGELOG.md" -towncrier_settings = "backend/sources/acme.theme/pyproject.toml" publish = true [[package]] @@ -507,7 +506,7 @@ primary = true name = "@acme/volto-core" path = "frontend/packages/volto-core" changelog = "frontend/packages/volto-core/CHANGELOG.md" -towncrier_settings = "frontend/packages/volto-core/towncrier.toml" +towncrier.settings = "frontend/packages/volto-core/towncrier.toml" publish = true [[package]] @@ -515,10 +514,11 @@ type = "node-volto" name = "@acme/volto-theme" path = "frontend/packages/volto-theme" changelog = "frontend/packages/volto-theme/CHANGELOG.md" -towncrier_settings = "frontend/packages/volto-theme/towncrier.toml" publish = true ``` +Here `acme.theme` and `@acme/volto-theme` rely on the [`towncrier` defaults](#the-towncrier-table): their settings file is found in their `path`, and their changelog heading is their name. + A repository that releases a single Python package living at its own root needs no frontend at all: ```toml @@ -535,7 +535,7 @@ name = "acme-tool" path = "." code_path = "src/acme_tool" changelog = "CHANGELOG.md" -towncrier_settings = "pyproject.toml" +towncrier.settings = "pyproject.toml" publish = true ``` @@ -569,13 +569,66 @@ Mark it with `primary = true`. When a family marks none, the first one in the fi | `name` | Package name, as published to PyPI or npm. | | `path` | Path to the package, relative to the repository root. Use `"."` for a package that *is* the repository. | | `changelog` | Path to the package changelog. | -| `towncrier_settings` | Path to the package Towncrier settings. | +| `towncrier` | News fragment settings: `settings` and `section`. See [The `towncrier` table](#the-towncrier-table). | | `code_path` | Path to the source code, relative to `path`. | | `publish` | Whether to publish this package to its registry. | | `primary` | Marks the primary package of its family. | -| `section` | Heading for this package in the repository changelog. Defaults to its name. | | `base_package` | Package this one builds on. Only meaningful on a family's primary package. | +### The `towncrier` table + +The news fragments of a repository are configured with a `towncrier` table. The same table is used in two places, with the same two keys: + +| Key | Description | +|------------|-----------------------------------------------------------------------------| +| `settings` | Path to the Towncrier settings file, relative to the repository root. | +| `section` | Heading for these news fragments in the repository changelog. | + +What changes between the two places is the defaults. + +**In a `[[package]]` entry**, the table is optional: + +- `settings` defaults to the file Towncrier itself would use in the package `path`: `towncrier.toml` if it exists, otherwise `pyproject.toml`. +- `section` defaults to the package `name`. + +A package that follows the usual layout needs no Towncrier lines at all. Set only what differs: + +```toml +[[package]] +type = "python-plone" +name = "acme.core" +path = "backend" +changelog = "backend/CHANGELOG.md" +towncrier.section = "Backend" +``` + +**In `[repository]`**, the table is opt-in: a `[repository.towncrier]` table turns the repository-level news fragments on, and leaving it out turns them off. + +- `settings` defaults to `towncrier.toml`. +- `section` defaults to `"Project"`. + +```toml +[repository.towncrier] +``` + +TOML offers three spellings of the same table, and all of them work: + +```toml +# Dotted keys +towncrier.settings = "backend/pyproject.toml" +towncrier.section = "Backend" + +# An inline table +towncrier = { settings = "backend/pyproject.toml", section = "Backend" } + +# A sub-table, after the package's other keys +[package.towncrier] +settings = "backend/pyproject.toml" +section = "Backend" +``` + +A misspelled key, an empty value, or `enabled` in `[repository.towncrier]` is an error rather than a silent fall back to the default. + ### What changed from specification 1 | Specification 1 | Specification 2 | @@ -584,7 +637,9 @@ Mark it with `primary = true`. When a family marks none, the first one in the fi | `compose` as a string or a list | a list | | `repository.managed_by_uv`, `backend.path`, `frontend.path` | removed | | release steps `release_backend`, `release_frontend`| `release_python`, `release_node` | -| changelog sections titled `Backend` / `Frontend` | titled with the package name, unless `section` says otherwise | +| `towncrier_settings` and `section` on a package | `towncrier.settings` and `towncrier.section`, both optional | +| `repository.towncrier.enabled` | removed: the table being present turns it on | +| changelog sections titled `Backend` / `Frontend` | titled with the package name, unless `towncrier.section` says otherwise | The release step ids are user-facing, so the rename is gradual: a specification 1 file accepts either spelling, a specification 2 file accepts only the new ones, and `--start-step` always accepts both. @@ -606,12 +661,14 @@ The command rewrites `repository.toml` in place, preserving comments and formatt - turns each component's package table into a `[[package]]` entry, with its `type` and `primary = true` - normalizes `compose` to a list - removes the deprecated `repository.managed_by_uv`, `backend.path` and `frontend.path` +- moves each package's `towncrier_settings` and `section` into its `towncrier` table, written as `towncrier.settings` and `towncrier.section` +- removes `repository.towncrier.enabled`, and removes a `[repository.towncrier]` table that names no `settings` file, since specification 1 treated it as off - renames the release step ids - leaves tables it does not own, such as `[cookieplone]`, alone Every change is reported. Use `--dry-run` to print the result without writing it, and `--path` to migrate a file other than the detected one. -The command does **not** add `section` options to keep the old `Backend` / `Frontend` changelog headings — migrating is the deliberate moment those become package names. It says so, and adding `section = "Backend"` to a package restores the old heading. +The command does **not** add `towncrier.section` options to keep the old `Backend` / `Frontend` changelog headings — migrating is the deliberate moment those become package names. It says so, and adding `towncrier.section = "Backend"` to a package restores the old heading. ## Contribute 🤝 diff --git a/news/112.breaking b/news/112.breaking new file mode 100644 index 0000000..2ea37ae --- /dev/null +++ b/news/112.breaking @@ -0,0 +1 @@ +In a specification 2 `repository.toml`, a package's Towncrier options move into a `towncrier` table, the same one `[repository.towncrier]` uses: write `towncrier.settings` and `towncrier.section` instead of `towncrier_settings` and `section`. Both are optional in a package: the settings file defaults to the `towncrier.toml` or `pyproject.toml` found in the package path, and the heading to the package name. A `[repository.towncrier]` table now turns the repository-level news fragments on by being present, with `towncrier.toml` and `Project` as defaults, and no longer accepts `enabled`. `repoplone settings migrate` writes the new form. @ericof diff --git a/repository.toml b/repository.toml index ed08ad7..a61742c 100644 --- a/repository.toml +++ b/repository.toml @@ -13,6 +13,6 @@ name = "repoplone" path = "." code_path = "src/repoplone" changelog = "CHANGELOG.md" -towncrier_settings = "pyproject.toml" +towncrier.settings = "pyproject.toml" # Published by .github/workflows/release.yml (trusted publishing). publish = false diff --git a/src/repoplone/schemas/repository-v2.json b/src/repoplone/schemas/repository-v2.json index 18f6008..a7f70c4 100644 --- a/src/repoplone/schemas/repository-v2.json +++ b/src/repoplone/schemas/repository-v2.json @@ -57,29 +57,30 @@ "type": "string" }, "managed_by_uv": false, - "towncrier": { "$ref": "#/$defs/repositoryTowncrier" }, + "towncrier": { + "$ref": "#/$defs/towncrier", + "description": "Repository-level news fragments. Present means enabled: settings defaults to towncrier.toml and section to \"Project\"." + }, "release": { "$ref": "#/$defs/release" } }, "additionalProperties": true }, - "repositoryTowncrier": { + "towncrier": { "type": "object", - "description": "Repository-level towncrier settings.", + "description": "Towncrier settings, used by [repository.towncrier] and by each [[package]].", "properties": { - "enabled": { - "description": "Whether the repository-level towncrier is enabled. Derived from the presence of this table.", - "type": "boolean" + "settings": { + "description": "Path to the towncrier settings file, relative to the repository root.", + "type": "string", + "minLength": 1 }, "section": { "description": "Heading used for this section in the repository changelog.", - "type": "string" - }, - "settings": { - "description": "Path to the towncrier settings file.", - "type": "string" + "type": "string", + "minLength": 1 } }, - "additionalProperties": true + "additionalProperties": false }, "release": { "type": "object", @@ -159,7 +160,7 @@ "package": { "type": "object", "description": "One package released from this repository. The language prefix of `type` decides how the package is built and published; the ecosystem suffix decides which extra keys apply.", - "required": ["type", "name", "path", "changelog", "towncrier_settings"], + "required": ["type", "name", "path", "changelog"], "properties": { "type": { "description": "Kind of package. `backend` and `frontend` are deprecated aliases for python-plone and node-volto, accepted so a hand-migrated file still loads; `repoplone settings migrate` writes the canonical names.", @@ -188,10 +189,9 @@ "type": "string", "minLength": 1 }, - "towncrier_settings": { - "description": "Path to the package towncrier settings, relative to the repository root.", - "type": "string", - "minLength": 1 + "towncrier": { + "$ref": "#/$defs/towncrier", + "description": "News fragments of this package. Optional: settings defaults to the first of towncrier.toml and pyproject.toml found in the package path, as towncrier itself looks them up, and section to the package name." }, "code_path": { "description": "Path to the source code, relative to the package path.", @@ -205,11 +205,6 @@ "description": "Marks this package as the primary one of its family. At most one per family; the first in document order is primary when none is marked.", "type": "boolean" }, - "section": { - "description": "Heading used for this package in the repository changelog. Defaults to the package name.", - "type": "string", - "minLength": 1 - }, "base_package": { "description": "Package this one builds on, whose version repoplone tracks. Only meaningful on the primary package of a family.", "type": "string", diff --git a/src/repoplone/settings/__init__.py b/src/repoplone/settings/__init__.py index cc09d5e..4ab784b 100644 --- a/src/repoplone/settings/__init__.py +++ b/src/repoplone/settings/__init__.py @@ -158,7 +158,7 @@ def _get_settings(cwd_path: Path) -> t.RepositorySettings: version: str = version_path.read_text().strip() version_format: str = repository.get("version_format", "semver") compose_path: list[Path] = _get_compose_path(root_path, raw_settings) - repository_towncrier: dict = repository.get("towncrier", {}) + repository_towncrier: dict | None = repository.get("towncrier", None) packages = _get_packages(root_path, raw_settings, spec_version) backend = _family_primary(root_path, raw_settings, packages, t.FAMILY_PYTHON) managed_by_uv = backend.managed_by_uv diff --git a/src/repoplone/settings/migrate.py b/src/repoplone/settings/migrate.py index 0d17387..457a82b 100644 --- a/src/repoplone/settings/migrate.py +++ b/src/repoplone/settings/migrate.py @@ -32,6 +32,12 @@ #: Keys that never belonged on a package table. DROPPED_PACKAGE_KEYS: tuple[str, ...] = ("enabled",) +#: Flat spec 1 package keys, mapped to their key in the ``towncrier`` table. +TOWNCRIER_PACKAGE_KEYS: dict[str, str] = { + "towncrier_settings": "settings", + "section": "section", +} + class MigrationError(RepoPloneException): """Raised when a ``repository.toml`` cannot be migrated.""" @@ -57,11 +63,63 @@ def _package_entries(document: tomlkit.TOMLDocument) -> list[tomlkit.items.Table for key, value in package.items(): if key in DROPPED_PACKAGE_KEYS: continue + if key in TOWNCRIER_PACKAGE_KEYS: + _add_towncrier_key(entry, TOWNCRIER_PACKAGE_KEYS[key], value) + continue entry[key] = value entries.append(entry) return entries +def _add_towncrier_key(entry: tomlkit.items.Table, key: str, value: object) -> None: + """Write one key of a package's ``towncrier`` table, as a dotted key. + + ``towncrier.settings = ...`` keeps the setting next to the package's other + keys, where a ``[package.towncrier]`` sub-table would move it below them. + An empty value is left out, so the spec 2 default applies. + + :param entry: The ``[[package]]`` entry being built. + :param key: Key inside the ``towncrier`` table. + :param value: The spec 1 value. + """ + if not str(value or "").strip(): + return + entry.append(tomlkit.key(["towncrier", key]), value) + + +def _migrate_repository_towncrier(document: tomlkit.TOMLDocument) -> list[str]: + """Rewrite ``[repository.towncrier]`` for spec 2. + + Spec 1 turned the table on only when it named a settings file; spec 2 + turns it on by being present. A spec 1 table without ``settings`` was + therefore off, and is removed so it stays off. ``enabled`` is no longer + part of the table. + + :param document: Parsed ``repository.toml``. + :returns: One note per change. + """ + repository = document.get("repository", None) + if repository is None or "towncrier" not in repository: + return [] + table = repository["towncrier"] + if not str(table.get("settings", "") or "").strip(): + notes = [ + "Removed [repository.towncrier]: it named no settings file, so it " + "was off. In spec 2 the table being present turns it on." + ] + if isinstance(table, tomlkit.items.Table): + notes.extend( + f"Dropped a comment that followed [repository.towncrier]: {comment}" + for comment in _trailing_comments(table) + ) + del repository["towncrier"] + return notes + if "enabled" in table: + del table["enabled"] + return ["Removed repository.towncrier.enabled"] + return [] + + def _normalize_compose(document: tomlkit.TOMLDocument) -> bool: """Turn a bare ``compose`` string into a list. @@ -205,6 +263,7 @@ def migrate_document(document: tomlkit.TOMLDocument) -> list[str]: if _normalize_compose(document): notes.append("Turned repository.compose into a list") notes.extend(_rename_steps(document)) + notes.extend(_migrate_repository_towncrier(document)) notes.extend(_remove_components(document)) @@ -236,8 +295,9 @@ def changelog_heading_note(document: tomlkit.TOMLDocument) -> str: """Return the warning about changelog headings changing, if it applies. Migrating is the deliberate moment section titles become package names. - Writing ``section`` keys to preserve the old headings would pin spec 1 - behaviour into every migrated file, so the change is reported instead. + Writing ``towncrier.section`` keys to preserve the old headings would pin + spec 1 behaviour into every migrated file, so the change is reported + instead. :param document: Migrated ``repository.toml``. :returns: The note, or an empty string when no package would change. @@ -245,15 +305,15 @@ def changelog_heading_note(document: tomlkit.TOMLDocument) -> str: names = [ str(entry["name"]) for entry in document.get("package", []) - if not entry.get("section", "") + if not (entry.get("towncrier", None) or {}).get("section", "") ] if not names: return "" listed = ", ".join(names) return ( f"Changelog sections will now be titled {listed}, rather than " - f'Backend / Frontend. Add `section = "Backend"` to a package to keep ' - f"the old heading." + f'Backend / Frontend. Add `towncrier.section = "Backend"` to a package ' + f"to keep the old heading." ) diff --git a/src/repoplone/settings/spec.py b/src/repoplone/settings/spec.py index f1f007e..cf5d908 100644 --- a/src/repoplone/settings/spec.py +++ b/src/repoplone/settings/spec.py @@ -13,6 +13,7 @@ from dynaconf.base import LazySettings from repoplone import _types as t from repoplone.exceptions import RepoPloneException +from repoplone.utils import _towncrier as towncrier_utils from typing import Any @@ -152,6 +153,50 @@ def _raw_tables(raw_settings: LazySettings) -> list: return list(raw) +def _package_label(table: Any, position: int) -> str: + """Return how a ``[[package]]`` entry is named in error messages. + + :param table: Raw ``[[package]]`` entry. + :param position: Zero-based position of the entry in the file. + :returns: The label, naming the package when it has a name. + """ + name = table.get("name", "") if isinstance(table, dict) else "" + label = f"[[package]] #{position + 1}" + return f"{label} ({name})" if name else label + + +def check_towncrier_tables(raw_settings: LazySettings, tables: list) -> None: + """Validate every ``towncrier`` table of a spec 2 file. + + A typo in a ``towncrier`` table would otherwise fall back to a default + silently, so unknown keys are errors here as well as in the schema. The + flat spec 1 keys get a message naming their replacement. + + :param raw_settings: Parsed settings. + :param tables: The raw ``[[package]]`` entries. + :raises RepositorySpecError: On the first problem found. + """ + repository = raw_settings.get("repository", {}) or {} + raw_repository = repository.get("towncrier", None) + if raw_repository is not None: + errors = towncrier_utils.table_errors(raw_repository, "[repository]") + if errors: + _fail(errors[0]) + for position, table in enumerate(tables): + label = _package_label(table, position) + for key, replacement in towncrier_utils.LEGACY_PACKAGE_KEYS.items(): + if key in table: + _fail( + f"{label} {key} is not part of spec 2. " + f"Write {replacement} = {table[key]!r} instead." + ) + raw = table.get("towncrier", None) + if raw is not None: + errors = towncrier_utils.table_errors(raw, label) + if errors: + _fail(errors[0]) + + def package_tables(raw_settings: LazySettings, spec_version: int) -> list: """Return the raw package tables of a file, validated against its spec. @@ -169,6 +214,7 @@ def package_tables(raw_settings: LazySettings, spec_version: int) -> list: ) return [] _reject_legacy_keys(raw_settings) + check_towncrier_tables(raw_settings, tables) return tables diff --git a/src/repoplone/utils/__init__.py b/src/repoplone/utils/__init__.py index 36f2c9f..907a156 100644 --- a/src/repoplone/utils/__init__.py +++ b/src/repoplone/utils/__init__.py @@ -4,6 +4,7 @@ from pathlib import Path from repoplone import _types as t from repoplone import defaults +from repoplone.utils import _towncrier as towncrier_utils from repoplone.utils import versions from repoplone.utils._path import frontend_root from repoplone.utils.dependencies import frontend as frontend_utils @@ -66,14 +67,15 @@ def _section_name(package: t.Package, spec_version: int) -> str: def get_towncrier_settings( root_path: Path, packages: list[t.Package], - repository: dict, + repository: dict | None, spec_version: int = 1, ) -> t.TowncrierSettings: """Return the towncrier sections of a repository, in document order. :param root_path: Repository root. :param packages: Every package declared in the file. - :param repository: The ``[repository.towncrier]`` table. + :param repository: The ``[repository.towncrier]`` table, or ``None`` when + the file has none. :param spec_version: Spec version of the file. :returns: The towncrier settings. """ @@ -87,11 +89,15 @@ def get_towncrier_settings( for package in packages if package.enabled ] - if repository and (towncrier := repository.get("settings", "")): - path: Path = root_path / towncrier - sections.append( - t.TowncrierSection("repository", repository["section"], path.resolve()) - ) + if spec_version == 1: + if repository and (towncrier := repository.get("settings", "")): + path: Path = root_path / towncrier + sections.append( + t.TowncrierSection("repository", repository["section"], path.resolve()) + ) + elif resolved := towncrier_utils.repository_section(root_path, repository): + settings_path, section = resolved + sections.append(t.TowncrierSection("repository", section, settings_path)) return t.TowncrierSettings(sections=sections) @@ -120,6 +126,7 @@ def _get_package_info( package_settings: DynaBox, package_type: str, version_func: Callable, + spec_version: int = 1, ) -> dict: """Return the fields shared by every package, whatever its type. @@ -127,11 +134,20 @@ def _get_package_info( :param package_settings: Raw package table read from ``repository.toml``. :param package_type: Canonical package type. :param version_func: Callable reading the current version from the package. + :param spec_version: Spec version of the file. Spec 2 reads the towncrier + settings from the package's ``towncrier`` table; spec 1 from its flat + ``towncrier_settings`` and ``section`` keys. :returns: Keyword arguments for the package dataclass. """ path = (root_path / str(package_settings.path)).resolve() changelog = (root_path / str(package_settings.changelog)).resolve() - towncrier = (root_path / str(package_settings.towncrier_settings)).resolve() + if spec_version == 1: + towncrier = (root_path / str(package_settings.towncrier_settings)).resolve() + section = str(package_settings.get("section", "") or "") + else: + raw_towncrier = package_settings.get("towncrier", None) + towncrier = towncrier_utils.package_settings(root_path, path, raw_towncrier) + section = towncrier_utils.package_section(raw_towncrier) raw_code_path = package_settings.get("code_path", "src") code_path = (path / str(raw_code_path)).resolve() package_name = package_settings.name @@ -152,7 +168,7 @@ def _get_package_info( "towncrier": towncrier, "type": package_type, "primary": bool(package_settings.get("primary", False)), - "section": str(package_settings.get("section", "") or ""), + "section": section, } return payload @@ -190,17 +206,19 @@ def _build_backend_package( root_path: Path, package_settings: DynaBox, package_type: str = "python-plone", + spec_version: int = 1, ) -> t.BackendPackage: """Build a package of the python family from one raw package table. :param root_path: Repository root. :param package_settings: Raw ``package`` table read from ``repository.toml``. :param package_type: Canonical package type. + :param spec_version: Spec version of the file. :returns: The package. """ version_func = versions.get_backend_version package_info = _get_package_info( - root_path, package_settings, package_type, version_func + root_path, package_settings, package_type, version_func, spec_version ) if package_info["enabled"]: package_path = package_info["path"] @@ -245,17 +263,19 @@ def _build_frontend_package( root_path: Path, package_settings: DynaBox, package_type: str = "node-volto", + spec_version: int = 1, ) -> t.FrontendPackage: """Build a package of the node family from one raw package table. :param root_path: Repository root. :param package_settings: Raw ``package`` table read from ``repository.toml``. :param package_type: Canonical package type. + :param spec_version: Spec version of the file. :returns: The package. """ version_func = versions.get_frontend_version package_info = _get_package_info( - root_path, package_settings, package_type, version_func + root_path, package_settings, package_type, version_func, spec_version ) if package_info["enabled"]: path = frontend_root(root_path, package_info["path"]) @@ -292,6 +312,8 @@ def build_package( ) -> t.Package: """Build a package of any type from one raw ``[[package]]`` table. + Only specification 2 declares ``[[package]]`` tables. + :param root_path: Repository root. :param package_settings: Raw ``[[package]]`` entry. :param package_type: Canonical package type. @@ -299,4 +321,4 @@ def build_package( """ family = t.PACKAGE_FAMILIES[package_type] builder = PACKAGE_BUILDERS[family] - return builder(root_path, package_settings, package_type) + return builder(root_path, package_settings, package_type, spec_version=2) diff --git a/src/repoplone/utils/_towncrier.py b/src/repoplone/utils/_towncrier.py new file mode 100644 index 0000000..f373b91 --- /dev/null +++ b/src/repoplone/utils/_towncrier.py @@ -0,0 +1,126 @@ +"""Resolve the ``towncrier`` table of a specification 2 ``repository.toml``. + +The same table is accepted in two places: ``[repository.towncrier]``, for the +news fragments of the repository as a whole, and inside each ``[[package]]``. +Both take ``settings`` and ``section``. Only the defaults differ: + +- In a package, the whole table is optional. ``settings`` defaults to the + file towncrier itself would pick in the package path, and ``section`` to the + package name. +- In the repository, the table is opt-in: present means enabled. Its + ``settings`` defaults to ``towncrier.toml`` and its ``section`` to + ``Project``, the values every generated repository writes. +""" + +from collections.abc import Mapping +from pathlib import Path +from typing import Any + + +#: Keys a ``towncrier`` table accepts, in either location. +KEYS: tuple[str, ...] = ("settings", "section") + +#: Files towncrier looks for in a directory, in the order it tries them. +CONFIG_FILENAMES: tuple[str, ...] = ("towncrier.toml", "pyproject.toml") + +#: Default settings file of ``[repository.towncrier]``. +REPOSITORY_SETTINGS = "towncrier.toml" + +#: Default changelog heading of ``[repository.towncrier]``. +REPOSITORY_SECTION = "Project" + +#: Spec 1 keys that the ``towncrier`` table replaces, with their new spelling. +LEGACY_PACKAGE_KEYS: dict[str, str] = { + "towncrier_settings": "towncrier.settings", + "section": "towncrier.section", +} + + +def table_errors(raw: Any, location: str) -> list[str]: + """Return what is wrong with a ``towncrier`` table, if anything. + + :param raw: The value found under the ``towncrier`` key. + :param location: Where the table was found, for the messages. + :returns: One message per problem; empty when the table is valid. + """ + if not isinstance(raw, Mapping): + return [ + f"{location} towncrier must be a table, with the keys {' and '.join(KEYS)}." + ] + errors: list[str] = [] + for key in raw: + if key == "enabled": + errors.append( + f"{location} towncrier.enabled is not part of spec 2: the " + "table being present turns it on. Remove the key, or the " + "whole table to turn it off." + ) + elif key not in KEYS: + errors.append( + f"{location} towncrier has an unknown key {key!r}. " + f"Use {' or '.join(KEYS)}." + ) + for key in KEYS: + if key not in raw: + continue + value = raw[key] + if not isinstance(value, str) or not value.strip(): + errors.append( + f"{location} towncrier.{key} must be a non-empty string, not {value!r}." + ) + return errors + + +def default_package_settings(package_path: Path) -> Path: + """Return the towncrier settings file of a package without an explicit one. + + Mirrors towncrier's own lookup: ``towncrier.toml`` wins over + ``pyproject.toml``. When neither exists, ``towncrier.toml`` is returned, so + the sanity check names the file it expected. + + :param package_path: Absolute path of the package. + :returns: The settings file. + """ + for filename in CONFIG_FILENAMES: + candidate = package_path / filename + if candidate.exists(): + return candidate.resolve() + return (package_path / CONFIG_FILENAMES[0]).resolve() + + +def package_settings(root_path: Path, package_path: Path, raw: Any) -> Path: + """Return the towncrier settings file of a package. + + :param root_path: Repository root, which ``settings`` is relative to. + :param package_path: Absolute path of the package. + :param raw: The package's ``towncrier`` table, or ``None``. + :returns: The settings file. + """ + settings = (raw or {}).get("settings", "") + if settings: + return (root_path / str(settings)).resolve() + return default_package_settings(package_path) + + +def package_section(raw: Any) -> str: + """Return the explicit changelog heading of a package. + + :param raw: The package's ``towncrier`` table, or ``None``. + :returns: The heading, or an empty string so the package name applies. + """ + return str((raw or {}).get("section", "") or "") + + +def repository_section(root_path: Path, raw: Any) -> tuple[Path, str] | None: + """Return the repository-level towncrier settings file and heading. + + :param root_path: Repository root. + :param raw: The ``[repository.towncrier]`` table, or ``None`` when absent. + :returns: The settings file and heading, or ``None`` when the table is + absent. + """ + if raw is None: + return None + settings = str(raw.get("settings", "") or REPOSITORY_SETTINGS) + section = str(raw.get("section", "") or REPOSITORY_SECTION) + return (root_path / settings).resolve(), section diff --git a/tests/_resources/fake-multi-package/repository.toml b/tests/_resources/fake-multi-package/repository.toml index 3cded0b..0a89729 100644 --- a/tests/_resources/fake-multi-package/repository.toml +++ b/tests/_resources/fake-multi-package/repository.toml @@ -18,7 +18,7 @@ name = "acme.core" path = "backend" code_path = "src/acme/core" changelog = "backend/CHANGELOG.md" -towncrier_settings = "backend/pyproject.toml" +towncrier.settings = "backend/pyproject.toml" publish = true [[package]] @@ -26,7 +26,7 @@ type = "python-plone" name = "acme.theme" path = "backend/sources/acme.theme" changelog = "backend/sources/acme.theme/CHANGELOG.md" -towncrier_settings = "backend/sources/acme.theme/pyproject.toml" +towncrier.settings = "backend/sources/acme.theme/pyproject.toml" publish = true [[package]] @@ -35,7 +35,7 @@ primary = true name = "@acme/volto-core" path = "frontend/packages/volto-core" changelog = "frontend/packages/volto-core/CHANGELOG.md" -towncrier_settings = "frontend/packages/volto-core/towncrier.toml" +towncrier.settings = "frontend/packages/volto-core/towncrier.toml" publish = true [[package]] @@ -43,5 +43,5 @@ type = "node-volto" name = "@acme/volto-theme" path = "frontend/packages/volto-theme" changelog = "frontend/packages/volto-theme/CHANGELOG.md" -towncrier_settings = "frontend/packages/volto-theme/towncrier.toml" +towncrier.settings = "frontend/packages/volto-theme/towncrier.toml" publish = true diff --git a/tests/_resources/fake-root-package/repository.toml b/tests/_resources/fake-root-package/repository.toml index 0f83a51..f3af9f8 100644 --- a/tests/_resources/fake-root-package/repository.toml +++ b/tests/_resources/fake-root-package/repository.toml @@ -12,5 +12,5 @@ name = "acme-tool" path = "." code_path = "src/acme_tool" changelog = "CHANGELOG.md" -towncrier_settings = "pyproject.toml" +towncrier.settings = "pyproject.toml" publish = true diff --git a/tests/_resources/repository_toml/spec2_cookieplone.toml b/tests/_resources/repository_toml/spec2_cookieplone.toml index 3064162..9082462 100644 --- a/tests/_resources/repository_toml/spec2_cookieplone.toml +++ b/tests/_resources/repository_toml/spec2_cookieplone.toml @@ -10,7 +10,7 @@ type = "python-plone" name = "acme.core" path = "backend" changelog = "backend/CHANGELOG.md" -towncrier_settings = "backend/pyproject.toml" +towncrier.settings = "backend/pyproject.toml" # Written by cookieplone; repoplone never reads it. [cookieplone] diff --git a/tests/_resources/repository_toml/spec2_invalid_base_package_on_generic.toml b/tests/_resources/repository_toml/spec2_invalid_base_package_on_generic.toml index 955d59e..051e2a5 100644 --- a/tests/_resources/repository_toml/spec2_invalid_base_package_on_generic.toml +++ b/tests/_resources/repository_toml/spec2_invalid_base_package_on_generic.toml @@ -11,5 +11,5 @@ type = "python" name = "acme.tooling" path = "backend" changelog = "backend/CHANGELOG.md" -towncrier_settings = "backend/pyproject.toml" +towncrier.settings = "backend/pyproject.toml" base_package = "Products.CMFPlone" diff --git a/tests/_resources/repository_toml/spec2_invalid_missing_changelog.toml b/tests/_resources/repository_toml/spec2_invalid_missing_changelog.toml index 8a2fb7d..341cae3 100644 --- a/tests/_resources/repository_toml/spec2_invalid_missing_changelog.toml +++ b/tests/_resources/repository_toml/spec2_invalid_missing_changelog.toml @@ -10,4 +10,4 @@ version = "version.txt" type = "python-plone" name = "acme.core" path = "backend" -towncrier_settings = "backend/pyproject.toml" +towncrier.settings = "backend/pyproject.toml" diff --git a/tests/_resources/repository_toml/spec2_invalid_missing_type.toml b/tests/_resources/repository_toml/spec2_invalid_missing_type.toml index b66d5a7..635ecc6 100644 --- a/tests/_resources/repository_toml/spec2_invalid_missing_type.toml +++ b/tests/_resources/repository_toml/spec2_invalid_missing_type.toml @@ -10,4 +10,4 @@ version = "version.txt" name = "acme.core" path = "backend" changelog = "backend/CHANGELOG.md" -towncrier_settings = "backend/pyproject.toml" +towncrier.settings = "backend/pyproject.toml" diff --git a/tests/_resources/repository_toml/spec2_invalid_plone_versions_on_node.toml b/tests/_resources/repository_toml/spec2_invalid_plone_versions_on_node.toml index a67a1f1..223789c 100644 --- a/tests/_resources/repository_toml/spec2_invalid_plone_versions_on_node.toml +++ b/tests/_resources/repository_toml/spec2_invalid_plone_versions_on_node.toml @@ -11,5 +11,5 @@ type = "node-volto" name = "@acme/volto-core" path = "frontend/packages/volto-core" changelog = "frontend/packages/volto-core/CHANGELOG.md" -towncrier_settings = "frontend/packages/volto-core/towncrier.toml" +towncrier.settings = "frontend/packages/volto-core/towncrier.toml" plone_versions = ["6.1"] diff --git a/tests/_resources/repository_toml/spec2_invalid_python_versions_on_node.toml b/tests/_resources/repository_toml/spec2_invalid_python_versions_on_node.toml index 4843e14..ef81167 100644 --- a/tests/_resources/repository_toml/spec2_invalid_python_versions_on_node.toml +++ b/tests/_resources/repository_toml/spec2_invalid_python_versions_on_node.toml @@ -11,5 +11,5 @@ type = "node" name = "@acme/tooling" path = "frontend/packages/tooling" changelog = "frontend/packages/tooling/CHANGELOG.md" -towncrier_settings = "frontend/packages/tooling/towncrier.toml" +towncrier.settings = "frontend/packages/tooling/towncrier.toml" python_version = "3.13" diff --git a/tests/_resources/repository_toml/spec2_invalid_towncrier_empty_section.toml b/tests/_resources/repository_toml/spec2_invalid_towncrier_empty_section.toml new file mode 100644 index 0000000..1bb5c9c --- /dev/null +++ b/tests/_resources/repository_toml/spec2_invalid_towncrier_empty_section.toml @@ -0,0 +1,14 @@ +# An empty heading is a mistake, not a request for the default. +spec_version = "2" + +[repository] +name = "acme-site" +changelog = "CHANGELOG.md" +version = "version.txt" + +[[package]] +type = "python-plone" +name = "acme.core" +path = "backend" +changelog = "backend/CHANGELOG.md" +towncrier.section = "" diff --git a/tests/_resources/repository_toml/spec2_invalid_towncrier_empty_settings.toml b/tests/_resources/repository_toml/spec2_invalid_towncrier_empty_settings.toml new file mode 100644 index 0000000..fd160c2 --- /dev/null +++ b/tests/_resources/repository_toml/spec2_invalid_towncrier_empty_settings.toml @@ -0,0 +1,14 @@ +# An empty settings path is a mistake, not a request for the default. +spec_version = "2" + +[repository] +name = "acme-site" +changelog = "CHANGELOG.md" +version = "version.txt" + +[[package]] +type = "python-plone" +name = "acme.core" +path = "backend" +changelog = "backend/CHANGELOG.md" +towncrier.settings = "" diff --git a/tests/_resources/repository_toml/spec2_invalid_towncrier_flat_section.toml b/tests/_resources/repository_toml/spec2_invalid_towncrier_flat_section.toml new file mode 100644 index 0000000..e866443 --- /dev/null +++ b/tests/_resources/repository_toml/spec2_invalid_towncrier_flat_section.toml @@ -0,0 +1,14 @@ +# The flat spec 1 key is not part of spec 2. +spec_version = "2" + +[repository] +name = "acme-site" +changelog = "CHANGELOG.md" +version = "version.txt" + +[[package]] +type = "python-plone" +name = "acme.core" +path = "backend" +changelog = "backend/CHANGELOG.md" +section = "Backend" diff --git a/tests/_resources/repository_toml/spec2_invalid_towncrier_flat_settings.toml b/tests/_resources/repository_toml/spec2_invalid_towncrier_flat_settings.toml new file mode 100644 index 0000000..52a5d7a --- /dev/null +++ b/tests/_resources/repository_toml/spec2_invalid_towncrier_flat_settings.toml @@ -0,0 +1,14 @@ +# The flat spec 1 key is not part of spec 2. +spec_version = "2" + +[repository] +name = "acme-site" +changelog = "CHANGELOG.md" +version = "version.txt" + +[[package]] +type = "python-plone" +name = "acme.core" +path = "backend" +changelog = "backend/CHANGELOG.md" +towncrier_settings = "backend/pyproject.toml" diff --git a/tests/_resources/repository_toml/spec2_invalid_towncrier_not_a_table.toml b/tests/_resources/repository_toml/spec2_invalid_towncrier_not_a_table.toml new file mode 100644 index 0000000..b98e3af --- /dev/null +++ b/tests/_resources/repository_toml/spec2_invalid_towncrier_not_a_table.toml @@ -0,0 +1,14 @@ +# towncrier is a table, not the path of the settings file. +spec_version = "2" + +[repository] +name = "acme-site" +changelog = "CHANGELOG.md" +version = "version.txt" + +[[package]] +type = "python-plone" +name = "acme.core" +path = "backend" +changelog = "backend/CHANGELOG.md" +towncrier = "backend/pyproject.toml" diff --git a/tests/_resources/repository_toml/spec2_invalid_towncrier_package_unknown_key.toml b/tests/_resources/repository_toml/spec2_invalid_towncrier_package_unknown_key.toml new file mode 100644 index 0000000..909ed71 --- /dev/null +++ b/tests/_resources/repository_toml/spec2_invalid_towncrier_package_unknown_key.toml @@ -0,0 +1,14 @@ +# A typo would otherwise fall back to the default silently. +spec_version = "2" + +[repository] +name = "acme-site" +changelog = "CHANGELOG.md" +version = "version.txt" + +[[package]] +type = "python-plone" +name = "acme.core" +path = "backend" +changelog = "backend/CHANGELOG.md" +towncrier.setings = "backend/pyproject.toml" diff --git a/tests/_resources/repository_toml/spec2_invalid_towncrier_repository_enabled.toml b/tests/_resources/repository_toml/spec2_invalid_towncrier_repository_enabled.toml new file mode 100644 index 0000000..55de1e7 --- /dev/null +++ b/tests/_resources/repository_toml/spec2_invalid_towncrier_repository_enabled.toml @@ -0,0 +1,16 @@ +# In spec 2 the table being present turns it on. +spec_version = "2" + +[repository] +name = "acme-site" +changelog = "CHANGELOG.md" +version = "version.txt" + +[repository.towncrier] +enabled = true + +[[package]] +type = "python-plone" +name = "acme.core" +path = "backend" +changelog = "backend/CHANGELOG.md" diff --git a/tests/_resources/repository_toml/spec2_invalid_towncrier_repository_unknown_key.toml b/tests/_resources/repository_toml/spec2_invalid_towncrier_repository_unknown_key.toml new file mode 100644 index 0000000..ffa615e --- /dev/null +++ b/tests/_resources/repository_toml/spec2_invalid_towncrier_repository_unknown_key.toml @@ -0,0 +1,17 @@ +# A typo would otherwise fall back to the default silently. +spec_version = "2" + +[repository] +name = "acme-site" +changelog = "CHANGELOG.md" +version = "version.txt" + +[repository.towncrier] +section = "Project" +setting = "towncrier.toml" + +[[package]] +type = "python-plone" +name = "acme.core" +path = "backend" +changelog = "backend/CHANGELOG.md" diff --git a/tests/_resources/repository_toml/spec2_invalid_unknown_package_key.toml b/tests/_resources/repository_toml/spec2_invalid_unknown_package_key.toml index b47024e..081c2cc 100644 --- a/tests/_resources/repository_toml/spec2_invalid_unknown_package_key.toml +++ b/tests/_resources/repository_toml/spec2_invalid_unknown_package_key.toml @@ -11,5 +11,5 @@ type = "python-plone" name = "acme.core" path = "backend" changelog = "backend/CHANGELOG.md" -towncrier_settings = "backend/pyproject.toml" +towncrier.settings = "backend/pyproject.toml" publsh = true diff --git a/tests/_resources/repository_toml/spec2_invalid_unknown_type.toml b/tests/_resources/repository_toml/spec2_invalid_unknown_type.toml index 7e152c0..377750c 100644 --- a/tests/_resources/repository_toml/spec2_invalid_unknown_type.toml +++ b/tests/_resources/repository_toml/spec2_invalid_unknown_type.toml @@ -11,4 +11,4 @@ type = "ruby" name = "acme" path = "backend" changelog = "backend/CHANGELOG.md" -towncrier_settings = "backend/pyproject.toml" +towncrier.settings = "backend/pyproject.toml" diff --git a/tests/_resources/repository_toml/spec2_multi_package.toml b/tests/_resources/repository_toml/spec2_multi_package.toml index a826600..d135096 100644 --- a/tests/_resources/repository_toml/spec2_multi_package.toml +++ b/tests/_resources/repository_toml/spec2_multi_package.toml @@ -18,7 +18,7 @@ name = "acme.core" path = "backend" code_path = "src/acme/core" changelog = "backend/CHANGELOG.md" -towncrier_settings = "backend/pyproject.toml" +towncrier.settings = "backend/pyproject.toml" base_package = "Products.CMFPlone" python_version = "3.13" python_versions = ["3.11", "3.12", "3.13"] @@ -30,7 +30,7 @@ type = "python-plone" name = "acme.theme" path = "backend/sources/acme.theme" changelog = "backend/sources/acme.theme/CHANGELOG.md" -towncrier_settings = "backend/sources/acme.theme/pyproject.toml" +towncrier.settings = "backend/sources/acme.theme/pyproject.toml" publish = true [[package]] @@ -40,7 +40,7 @@ name = "@acme/volto-core" path = "frontend/packages/volto-core" code_path = "src" changelog = "frontend/packages/volto-core/CHANGELOG.md" -towncrier_settings = "frontend/packages/volto-core/towncrier.toml" +towncrier.settings = "frontend/packages/volto-core/towncrier.toml" base_package = "@plone/volto" publish = true @@ -49,5 +49,5 @@ type = "node-volto" name = "@acme/volto-theme" path = "frontend/packages/volto-theme" changelog = "frontend/packages/volto-theme/CHANGELOG.md" -towncrier_settings = "frontend/packages/volto-theme/towncrier.toml" +towncrier.settings = "frontend/packages/volto-theme/towncrier.toml" publish = true diff --git a/tests/_resources/repository_toml/spec2_node_aurora.toml b/tests/_resources/repository_toml/spec2_node_aurora.toml index 390d3f0..0c72206 100644 --- a/tests/_resources/repository_toml/spec2_node_aurora.toml +++ b/tests/_resources/repository_toml/spec2_node_aurora.toml @@ -10,6 +10,6 @@ type = "node-aurora" name = "@acme/aurora-core" path = "frontend/packages/aurora-core" changelog = "frontend/packages/aurora-core/CHANGELOG.md" -towncrier_settings = "frontend/packages/aurora-core/towncrier.toml" +towncrier.settings = "frontend/packages/aurora-core/towncrier.toml" base_package = "@acme/aurora-base" publish = true diff --git a/tests/_resources/repository_toml/spec2_node_aurora_default_base_package.toml b/tests/_resources/repository_toml/spec2_node_aurora_default_base_package.toml index c61292e..3ed9919 100644 --- a/tests/_resources/repository_toml/spec2_node_aurora_default_base_package.toml +++ b/tests/_resources/repository_toml/spec2_node_aurora_default_base_package.toml @@ -11,4 +11,4 @@ type = "node-aurora" name = "@acme/aurora-core" path = "frontend/packages/aurora-core" changelog = "frontend/packages/aurora-core/CHANGELOG.md" -towncrier_settings = "frontend/packages/aurora-core/towncrier.toml" +towncrier.settings = "frontend/packages/aurora-core/towncrier.toml" diff --git a/tests/_resources/repository_toml/spec2_release_pipeline.toml b/tests/_resources/repository_toml/spec2_release_pipeline.toml index 0071c1c..e98e5db 100644 --- a/tests/_resources/repository_toml/spec2_release_pipeline.toml +++ b/tests/_resources/repository_toml/spec2_release_pipeline.toml @@ -27,4 +27,4 @@ type = "python-plone" name = "acme.core" path = "backend" changelog = "backend/CHANGELOG.md" -towncrier_settings = "backend/pyproject.toml" +towncrier.settings = "backend/pyproject.toml" diff --git a/tests/_resources/repository_toml/spec2_root_package.toml b/tests/_resources/repository_toml/spec2_root_package.toml index 5e6648d..d76bc9a 100644 --- a/tests/_resources/repository_toml/spec2_root_package.toml +++ b/tests/_resources/repository_toml/spec2_root_package.toml @@ -12,5 +12,5 @@ name = "repoplone" path = "." code_path = "src/repoplone" changelog = "CHANGELOG.md" -towncrier_settings = "pyproject.toml" +towncrier.settings = "pyproject.toml" publish = true diff --git a/tests/_resources/repository_toml/spec2_section_override.toml b/tests/_resources/repository_toml/spec2_section_override.toml index 7d05cf0..8f15974 100644 --- a/tests/_resources/repository_toml/spec2_section_override.toml +++ b/tests/_resources/repository_toml/spec2_section_override.toml @@ -1,4 +1,4 @@ -# `section` overrides the changelog heading, which defaults to the package name. +# `towncrier.section` overrides the changelog heading, which defaults to the package name. spec_version = "2" [repository] @@ -10,14 +10,14 @@ version = "version.txt" type = "python-plone" name = "acme.core" path = "backend" -section = "Backend" +towncrier.section = "Backend" changelog = "backend/CHANGELOG.md" -towncrier_settings = "backend/pyproject.toml" +towncrier.settings = "backend/pyproject.toml" [[package]] type = "node-volto" name = "@acme/volto-core" path = "frontend/packages/volto-core" -section = "Frontend" +towncrier.section = "Frontend" changelog = "frontend/packages/volto-core/CHANGELOG.md" -towncrier_settings = "frontend/packages/volto-core/towncrier.toml" +towncrier.settings = "frontend/packages/volto-core/towncrier.toml" diff --git a/tests/_resources/repository_toml/spec2_towncrier_defaults.toml b/tests/_resources/repository_toml/spec2_towncrier_defaults.toml new file mode 100644 index 0000000..55c32d9 --- /dev/null +++ b/tests/_resources/repository_toml/spec2_towncrier_defaults.toml @@ -0,0 +1,21 @@ +# No towncrier table anywhere: each package finds its settings the way +# towncrier does, takes its name as heading, and the repository has no +# section of its own. +spec_version = "2" + +[repository] +name = "acme-site" +changelog = "CHANGELOG.md" +version = "version.txt" + +[[package]] +type = "python-plone" +name = "acme.core" +path = "backend" +changelog = "backend/CHANGELOG.md" + +[[package]] +type = "node-volto" +name = "@acme/volto-core" +path = "frontend/packages/volto-core" +changelog = "frontend/packages/volto-core/CHANGELOG.md" diff --git a/tests/_resources/repository_toml/spec2_towncrier_package_forms.toml b/tests/_resources/repository_toml/spec2_towncrier_package_forms.toml new file mode 100644 index 0000000..3722506 --- /dev/null +++ b/tests/_resources/repository_toml/spec2_towncrier_package_forms.toml @@ -0,0 +1,32 @@ +# The three ways TOML spells the same towncrier table. +spec_version = "2" + +[repository] +name = "acme-site" +changelog = "CHANGELOG.md" +version = "version.txt" + +[[package]] +type = "python-plone" +name = "acme.core" +path = "backend" +changelog = "backend/CHANGELOG.md" +towncrier.settings = "backend/pyproject.toml" +towncrier.section = "Dotted" + +[[package]] +type = "node-volto" +name = "@acme/volto-core" +path = "frontend/packages/volto-core" +changelog = "frontend/packages/volto-core/CHANGELOG.md" +towncrier = { settings = "frontend/packages/volto-core/towncrier.toml", section = "Inline" } + +[[package]] +type = "node-volto" +name = "@acme/volto-theme" +path = "frontend/packages/volto-theme" +changelog = "frontend/packages/volto-theme/CHANGELOG.md" + +[package.towncrier] +settings = "frontend/packages/volto-theme/towncrier.toml" +section = "Sub-table" diff --git a/tests/_resources/repository_toml/spec2_towncrier_package_section_only.toml b/tests/_resources/repository_toml/spec2_towncrier_package_section_only.toml new file mode 100644 index 0000000..3e551be --- /dev/null +++ b/tests/_resources/repository_toml/spec2_towncrier_package_section_only.toml @@ -0,0 +1,14 @@ +# Only the heading is set; the settings file comes from the default lookup. +spec_version = "2" + +[repository] +name = "acme-site" +changelog = "CHANGELOG.md" +version = "version.txt" + +[[package]] +type = "python-plone" +name = "acme.core" +path = "backend" +changelog = "backend/CHANGELOG.md" +towncrier.section = "Backend" diff --git a/tests/_resources/repository_toml/spec2_towncrier_package_settings_only.toml b/tests/_resources/repository_toml/spec2_towncrier_package_settings_only.toml new file mode 100644 index 0000000..7b5f811 --- /dev/null +++ b/tests/_resources/repository_toml/spec2_towncrier_package_settings_only.toml @@ -0,0 +1,14 @@ +# Only the settings file is set; the heading defaults to the package name. +spec_version = "2" + +[repository] +name = "acme-site" +changelog = "CHANGELOG.md" +version = "version.txt" + +[[package]] +type = "python-plone" +name = "acme.core" +path = "backend" +changelog = "backend/CHANGELOG.md" +towncrier.settings = "backend/news.toml" diff --git a/tests/_resources/repository_toml/spec2_towncrier_repository_defaults.toml b/tests/_resources/repository_toml/spec2_towncrier_repository_defaults.toml new file mode 100644 index 0000000..efcb023 --- /dev/null +++ b/tests/_resources/repository_toml/spec2_towncrier_repository_defaults.toml @@ -0,0 +1,15 @@ +# An empty table turns the repository section on, with both defaults. +spec_version = "2" + +[repository] +name = "acme-site" +changelog = "CHANGELOG.md" +version = "version.txt" + +[repository.towncrier] + +[[package]] +type = "python-plone" +name = "acme.core" +path = "backend" +changelog = "backend/CHANGELOG.md" diff --git a/tests/_resources/repository_toml/spec2_towncrier_repository_section_only.toml b/tests/_resources/repository_toml/spec2_towncrier_repository_section_only.toml new file mode 100644 index 0000000..9de17c6 --- /dev/null +++ b/tests/_resources/repository_toml/spec2_towncrier_repository_section_only.toml @@ -0,0 +1,16 @@ +# The repository settings file defaults to towncrier.toml. +spec_version = "2" + +[repository] +name = "acme-site" +changelog = "CHANGELOG.md" +version = "version.txt" + +[repository.towncrier] +section = "Monorepo" + +[[package]] +type = "python-plone" +name = "acme.core" +path = "backend" +changelog = "backend/CHANGELOG.md" diff --git a/tests/_resources/repository_toml/spec2_towncrier_repository_settings_only.toml b/tests/_resources/repository_toml/spec2_towncrier_repository_settings_only.toml new file mode 100644 index 0000000..982c291 --- /dev/null +++ b/tests/_resources/repository_toml/spec2_towncrier_repository_settings_only.toml @@ -0,0 +1,16 @@ +# The repository heading defaults to "Project". +spec_version = "2" + +[repository] +name = "acme-site" +changelog = "CHANGELOG.md" +version = "version.txt" + +[repository.towncrier] +settings = "news/towncrier.toml" + +[[package]] +type = "python-plone" +name = "acme.core" +path = "backend" +changelog = "backend/CHANGELOG.md" diff --git a/tests/_resources/repository_toml/spec2_type_aliases.toml b/tests/_resources/repository_toml/spec2_type_aliases.toml index 819a6c7..fa8ded0 100644 --- a/tests/_resources/repository_toml/spec2_type_aliases.toml +++ b/tests/_resources/repository_toml/spec2_type_aliases.toml @@ -12,7 +12,7 @@ type = "backend" name = "acme.core" path = "backend" changelog = "backend/CHANGELOG.md" -towncrier_settings = "backend/pyproject.toml" +towncrier.settings = "backend/pyproject.toml" plone_versions = ["6.1"] [[package]] @@ -20,4 +20,4 @@ type = "frontend" name = "@acme/volto-core" path = "frontend/packages/volto-core" changelog = "frontend/packages/volto-core/CHANGELOG.md" -towncrier_settings = "frontend/packages/volto-core/towncrier.toml" +towncrier.settings = "frontend/packages/volto-core/towncrier.toml" diff --git a/tests/commands/settings/test_migrate.py b/tests/commands/settings/test_migrate.py index c2fcc48..27e1856 100644 --- a/tests/commands/settings/test_migrate.py +++ b/tests/commands/settings/test_migrate.py @@ -143,12 +143,174 @@ def test_notes_report_the_changelog_heading_change(spec1_file): _, notes = migrate.migrate_file(spec1_file) joined = "\n".join(notes) assert "Changelog sections" in joined - assert 'section = "Backend"' in joined + assert 'Add `towncrier.section = "Backend"` to a package' in joined def test_no_section_keys_are_written(migrated_data: dict): """Preserving the old headings would pin spec 1 behaviour into the file.""" - assert all("section" not in entry for entry in migrated_data["package"]) + for entry in migrated_data["package"]: + assert "section" not in entry + assert "section" not in entry["towncrier"] + + +def test_towncrier_settings_become_a_table(migrated_data: dict): + assert [entry["towncrier"] for entry in migrated_data["package"]] == [ + {"settings": "backend/pyproject.toml"}, + {"settings": "frontend/packages/fake-project/towncrier.toml"}, + ] + for entry in migrated_data["package"]: + assert "towncrier_settings" not in entry + + +def test_towncrier_keys_are_written_dotted(migrated: str): + """Dotted keys keep the setting among the package's other keys.""" + assert 'towncrier.settings = "backend/pyproject.toml"' in migrated + assert "[package.towncrier]" not in migrated + assert "towncrier_settings" not in migrated + + +#: A spec 1 file for the towncrier rewrites, filled in per test. +TOWNCRIER_SPEC1 = """[repository] +name = "fake-project" +changelog = "CHANGELOG.md" +version = "version.txt" +{repository} +[backend.package] +name = "fake.project" +path = "backend" +changelog = "backend/CHANGELOG.md" +{package} +""" + + +def _migrate_text(tmp_path: Path, repository: str = "", package: str = ""): + """Migrate a spec 1 file built from :data:`TOWNCRIER_SPEC1`. + + :param tmp_path: Directory to write the file to. + :param repository: Lines inserted after the ``[repository]`` keys. + :param package: Lines inserted inside ``[backend.package]``. + :returns: The migrated text, its parsed data and the notes. + """ + path = tmp_path / "repository.toml" + path.write_text(TOWNCRIER_SPEC1.format(repository=repository, package=package)) + text, notes = migrate.migrate_file(path) + migrate.validate_migrated(text) + return text, tomlkit.parse(text).unwrap(), notes + + +@pytest.mark.parametrize( + "package,expected", + [ + [ + 'towncrier_settings = "backend/pyproject.toml"\nsection = "Backend"', + {"settings": "backend/pyproject.toml", "section": "Backend"}, + ], + [ + 'section = "Backend"\ntowncrier_settings = "backend/pyproject.toml"', + {"section": "Backend", "settings": "backend/pyproject.toml"}, + ], + ['section = "Backend"', {"section": "Backend"}], + ['towncrier_settings = "backend/news.toml"', {"settings": "backend/news.toml"}], + ], + ids=["settings-then-section", "section-then-settings", "section", "settings"], +) +def test_package_towncrier_keys_move_into_the_table( + tmp_path, package: str, expected: dict +): + _, data, _ = _migrate_text(tmp_path, package=package) + assert data["package"][0]["towncrier"] == expected + assert list(data["package"][0]["towncrier"]) == list(expected) + + +@pytest.mark.parametrize("package", ["", 'towncrier_settings = ""', 'section = ""']) +def test_empty_or_missing_towncrier_keys_leave_the_default(tmp_path, package: str): + """An empty spec 1 value meant "unset"; spec 2 then applies its default.""" + text, data, _ = _migrate_text(tmp_path, package=package) + assert "towncrier" not in data["package"][0] + assert "towncrier" not in text + + +def test_heading_note_skips_packages_that_keep_a_section(tmp_path): + _, _, notes = _migrate_text(tmp_path, package='section = "Backend"') + assert not any("Changelog sections" in note for note in notes) + + +def test_heading_note_lists_packages_without_a_section(tmp_path): + _, _, notes = _migrate_text( + tmp_path, package='towncrier_settings = "backend/pyproject.toml"' + ) + assert any("Changelog sections will now be titled fake.project" in n for n in notes) + + +def test_repository_towncrier_with_settings_is_kept(tmp_path): + repository = ( + '\n[repository.towncrier]\nsection = "Project"\nsettings = "towncrier.toml"\n' + ) + _, data, notes = _migrate_text(tmp_path, repository=repository) + assert data["repository"]["towncrier"] == { + "section": "Project", + "settings": "towncrier.toml", + } + assert not any("repository.towncrier" in note for note in notes) + + +@pytest.mark.parametrize("enabled", ["true", "false"]) +def test_repository_towncrier_enabled_is_dropped(tmp_path, enabled: str): + """Spec 1 never read enabled: naming a settings file was what turned it on.""" + repository = ( + "\n[repository.towncrier]\n" + f'enabled = {enabled}\nsection = "Project"\nsettings = "towncrier.toml"\n' + ) + _, data, notes = _migrate_text(tmp_path, repository=repository) + assert data["repository"]["towncrier"] == { + "section": "Project", + "settings": "towncrier.toml", + } + assert "Removed repository.towncrier.enabled" in notes + + +@pytest.mark.parametrize( + "table", + [ + '[repository.towncrier]\nsection = "Project"\n', + '[repository.towncrier]\nsection = "Project"\nsettings = ""\n', + "[repository.towncrier]\nenabled = true\n", + "[repository.towncrier]\n", + ], + ids=["no-settings", "empty-settings", "enabled-only", "empty"], +) +def test_repository_towncrier_that_was_off_is_removed(tmp_path, table: str): + """Kept as is, spec 2 would turn on a section spec 1 had off.""" + _, data, notes = _migrate_text(tmp_path, repository=f"\n{table}") + assert "towncrier" not in data["repository"] + assert any("Removed [repository.towncrier]" in note for note in notes) + + +def test_repository_without_towncrier_is_left_alone(tmp_path): + _, data, notes = _migrate_text(tmp_path) + assert "towncrier" not in data["repository"] + assert not any("repository.towncrier" in note for note in notes) + + +def test_migrated_file_loads_with_the_same_towncrier_sections( + test_project_root_changelog, bust_path_cache +): + """Same settings files before and after; only the headings may change.""" + from repoplone import settings + + before = settings.get_settings() + path = test_project_root_changelog / "repository.toml" + text, _ = migrate.migrate_file(path) + path.write_text(text) + after = settings.get_settings() + assert after.spec_version == 2 + assert [(s.section_id, s.path) for s in after.towncrier.sections] == [ + (s.section_id, s.path) for s in before.towncrier.sections + ] + repository_before = before.towncrier.get("repository") + repository_after = after.towncrier.get("repository") + assert repository_before is not None and repository_after is not None + assert repository_after.name == repository_before.name def test_release_steps_are_renamed(tmp_path): diff --git a/tests/settings/test_towncrier.py b/tests/settings/test_towncrier.py new file mode 100644 index 0000000..a68b398 --- /dev/null +++ b/tests/settings/test_towncrier.py @@ -0,0 +1,453 @@ +"""Cover the ``towncrier`` table of a specification 2 ``repository.toml``. + +The same table is accepted in ``[repository.towncrier]`` and in each +``[[package]]``, with different defaults. These tests pin the table's rules +(:mod:`repoplone.utils._towncrier`), how a loaded repository resolves it, and +that specification 1 files keep reading their flat keys. +""" + +from pathlib import Path +from repoplone import settings +from repoplone.settings import spec +from repoplone.utils import _towncrier as towncrier + +import pytest + + +@pytest.fixture +def project(test_multi_package_project, get_resource_file, bust_path_cache): + """Return a callable putting a ``repository_toml`` fixture on a real tree. + + Loading a file reads each package's version from disk, so the fixture + replaces the ``repository.toml`` of the multi-package project, whose + ``backend``, ``volto-core`` and ``volto-theme`` packages the towncrier + fixtures point at. ``backend`` ships a ``pyproject.toml`` and each node + package a ``towncrier.toml``, which is what the default lookup finds. + """ + root = test_multi_package_project + + def func(filename: str) -> Path: + source = get_resource_file(f"repository_toml/{filename}") + (root / "repository.toml").write_text(source.read_text()) + return root + + return func + + +@pytest.fixture +def load(project): + """Return a callable loading the settings of a ``repository_toml`` fixture.""" + + def func(filename: str): + return settings._get_settings(project(filename)) + + return func + + +def _touch(root: Path, *paths: str) -> None: + """Create empty files below a project root. + + :param root: Project root. + :param paths: File paths, relative to the root. + """ + for relative in paths: + path = root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("") + + +def _sections(result) -> dict[str, tuple[str, Path]]: + """Return the towncrier sections of loaded settings, keyed by id. + + :param result: Loaded repository settings. + :returns: ``{section_id: (heading, settings file)}``. + """ + return { + section.section_id: (section.name, section.path) + for section in result.towncrier.sections + } + + +# ---------------------------------------------------------------- table rules + + +@pytest.mark.parametrize( + "raw", + [ + {}, + {"settings": "towncrier.toml"}, + {"section": "Project"}, + {"settings": "news/towncrier.toml", "section": "Project"}, + ], +) +def test_table_errors_accepts_valid_tables(raw: dict): + assert towncrier.table_errors(raw, "[repository]") == [] + + +@pytest.mark.parametrize("raw", ["towncrier.toml", 1, True, ["settings"], None]) +def test_table_errors_rejects_a_value_that_is_not_a_table(raw): + errors = towncrier.table_errors(raw, "[repository]") + assert len(errors) == 1 + assert "must be a table" in errors[0] + + +def test_table_errors_rejects_enabled_with_its_own_message(): + errors = towncrier.table_errors({"enabled": True}, "[repository]") + assert len(errors) == 1 + assert "towncrier.enabled is not part of spec 2" in errors[0] + assert "table being present turns it on" in errors[0] + + +@pytest.mark.parametrize("key", ["setting", "Settings", "sections", "path"]) +def test_table_errors_rejects_unknown_keys(key: str): + errors = towncrier.table_errors({key: "x"}, "[[package]] #1 (acme.core)") + assert errors == [ + f"[[package]] #1 (acme.core) towncrier has an unknown key {key!r}. " + "Use settings or section." + ] + + +@pytest.mark.parametrize("key", towncrier.KEYS) +@pytest.mark.parametrize("value", ["", " ", 0, False, ["a"], {"a": "b"}]) +def test_table_errors_rejects_empty_or_non_string_values(key: str, value): + errors = towncrier.table_errors({key: value}, "[repository]") + assert errors == [ + f"[repository] towncrier.{key} must be a non-empty string, not {value!r}." + ] + + +def test_table_errors_reports_every_problem(): + raw = {"enabled": False, "setings": "x", "section": ""} + assert len(towncrier.table_errors(raw, "[repository]")) == 3 + + +# ------------------------------------------------------- package defaults + + +@pytest.mark.parametrize( + "existing,expected", + [ + [("towncrier.toml",), "towncrier.toml"], + [("pyproject.toml",), "pyproject.toml"], + [("towncrier.toml", "pyproject.toml"), "towncrier.toml"], + [(), "towncrier.toml"], + ], + ids=["towncrier-only", "pyproject-only", "both", "neither"], +) +def test_default_package_settings_follows_towncrier( + tmp_path: Path, existing: tuple[str, ...], expected: str +): + """towncrier.toml wins over pyproject.toml, as in towncrier itself.""" + _touch(tmp_path, *existing) + assert towncrier.default_package_settings(tmp_path) == tmp_path / expected + + +@pytest.mark.parametrize("raw", [None, {}, {"section": "Backend"}]) +def test_package_settings_defaults_without_a_settings_key(tmp_path: Path, raw): + package_path = tmp_path / "backend" + _touch(tmp_path, "backend/pyproject.toml") + result = towncrier.package_settings(tmp_path, package_path, raw) + assert result == package_path / "pyproject.toml" + + +def test_package_settings_is_relative_to_the_repository_root(tmp_path: Path): + """Like every other path in the file, not relative to the package.""" + package_path = tmp_path / "backend" + raw = {"settings": "backend/news.toml"} + result = towncrier.package_settings(tmp_path, package_path, raw) + assert result == (tmp_path / "backend" / "news.toml").resolve() + + +def test_package_settings_explicit_wins_over_existing_defaults(tmp_path: Path): + package_path = tmp_path / "backend" + _touch(tmp_path, "backend/towncrier.toml", "backend/pyproject.toml") + raw = {"settings": "news.toml"} + result = towncrier.package_settings(tmp_path, package_path, raw) + assert result == (tmp_path / "news.toml").resolve() + + +@pytest.mark.parametrize( + "raw,expected", + [ + [None, ""], + [{}, ""], + [{"settings": "x.toml"}, ""], + [{"section": "Backend"}, "Backend"], + ], +) +def test_package_section(raw, expected: str): + assert towncrier.package_section(raw) == expected + + +# --------------------------------------------------- repository defaults + + +def test_repository_section_absent_table(tmp_path: Path): + assert towncrier.repository_section(tmp_path, None) is None + + +@pytest.mark.parametrize( + "raw,settings_file,heading", + [ + [{}, "towncrier.toml", "Project"], + [{"settings": "news/towncrier.toml"}, "news/towncrier.toml", "Project"], + [{"section": "Monorepo"}, "towncrier.toml", "Monorepo"], + [ + {"settings": "news/towncrier.toml", "section": "Monorepo"}, + "news/towncrier.toml", + "Monorepo", + ], + ], + ids=["empty", "settings-only", "section-only", "both"], +) +def test_repository_section_defaults( + tmp_path: Path, raw: dict, settings_file: str, heading: str +): + result = towncrier.repository_section(tmp_path, raw) + assert result == ((tmp_path / settings_file).resolve(), heading) + + +def test_repository_defaults_are_the_generated_values(): + """Every generated repository writes these two values today.""" + assert towncrier.REPOSITORY_SETTINGS == "towncrier.toml" + assert towncrier.REPOSITORY_SECTION == "Project" + + +# ------------------------------------------------ loading a spec 2 file + + +def test_no_table_anywhere(project): + """Each package finds its own settings; the repository has no section.""" + root = project("spec2_towncrier_defaults.toml") + result = settings._get_settings(root) + assert _sections(result) == { + "python": ("acme.core", (root / "backend/pyproject.toml").resolve()), + "node": ( + "@acme/volto-core", + (root / "frontend/packages/volto-core/towncrier.toml").resolve(), + ), + } + + +def test_no_table_prefers_towncrier_toml(project): + root = project("spec2_towncrier_defaults.toml") + _touch(root, "backend/towncrier.toml") + result = settings._get_settings(root) + assert _sections(result)["python"][1] == (root / "backend/towncrier.toml").resolve() + + +def test_no_table_and_no_file_names_towncrier_toml(project): + """The sanity check then reports the file the lookup expected.""" + root = project("spec2_towncrier_defaults.toml") + (root / "frontend/packages/volto-core/towncrier.toml").unlink() + result = settings._get_settings(root) + node = result.packages_for("node")[0] + expected = (root / "frontend/packages/volto-core/towncrier.toml").resolve() + assert node.towncrier == expected + assert not node.towncrier.exists() + assert node.sanity() is False + + +def test_package_section_defaults_to_the_package_name(load): + result = load("spec2_towncrier_defaults.toml") + assert [package.section for package in result.packages] == ["", ""] + assert [section.name for section in result.towncrier.sections] == [ + "acme.core", + "@acme/volto-core", + ] + + +def test_three_spellings_of_the_package_table(project): + """Dotted keys, an inline table and a sub-table all read the same.""" + root = project("spec2_towncrier_package_forms.toml") + result = settings._get_settings(root) + assert _sections(result) == { + "python": ("Dotted", (root / "backend/pyproject.toml").resolve()), + "node": ( + "Inline", + (root / "frontend/packages/volto-core/towncrier.toml").resolve(), + ), + "node:@acme/volto-theme": ( + "Sub-table", + (root / "frontend/packages/volto-theme/towncrier.toml").resolve(), + ), + } + + +def test_package_section_only(project): + root = project("spec2_towncrier_package_section_only.toml") + result = settings._get_settings(root) + assert _sections(result) == { + "python": ("Backend", (root / "backend/pyproject.toml").resolve()), + } + + +def test_package_settings_only(project): + root = project("spec2_towncrier_package_settings_only.toml") + result = settings._get_settings(root) + assert _sections(result) == { + "python": ("acme.core", (root / "backend/news.toml").resolve()), + } + + +def test_existing_section_override_fixture(load): + """The fixture that set headings with the flat key, now in the table.""" + result = load("spec2_section_override.toml") + assert [section.name for section in result.towncrier.sections] == [ + "Backend", + "Frontend", + ] + + +@pytest.mark.parametrize( + "filename,settings_file,heading", + [ + ["spec2_towncrier_repository_defaults.toml", "towncrier.toml", "Project"], + [ + "spec2_towncrier_repository_settings_only.toml", + "news/towncrier.toml", + "Project", + ], + [ + "spec2_towncrier_repository_section_only.toml", + "towncrier.toml", + "Monorepo", + ], + ], +) +def test_repository_table(project, filename, settings_file, heading): + root = project(filename) + result = settings._get_settings(root) + repository = result.towncrier.get("repository") + assert repository is not None + assert repository.name == heading + assert repository.path == (root / settings_file).resolve() + + +def test_repository_section_comes_last(load): + result = load("spec2_towncrier_repository_defaults.toml") + assert [section.section_id for section in result.towncrier.sections] == [ + "python", + "repository", + ] + + +@pytest.mark.parametrize( + "filename", + [ + "spec2_towncrier_defaults.toml", + "spec2_towncrier_package_forms.toml", + "spec2_towncrier_package_settings_only.toml", + ], +) +def test_no_repository_table_means_no_repository_section(load, filename: str): + result = load(filename) + assert result.towncrier.get("repository") is None + + +# ------------------------------------------------ rejecting a spec 2 file + + +@pytest.mark.parametrize( + "filename,message", + [ + [ + "spec2_invalid_towncrier_flat_settings.toml", + r"\[\[package\]\] #1 \(acme.core\) towncrier_settings is not part of " + r"spec 2\. Write towncrier.settings = 'backend/pyproject.toml' instead\.", + ], + [ + "spec2_invalid_towncrier_flat_section.toml", + r"\[\[package\]\] #1 \(acme.core\) section is not part of spec 2\. " + r"Write towncrier.section = 'Backend' instead\.", + ], + [ + "spec2_invalid_towncrier_empty_settings.toml", + r"towncrier.settings must be a non-empty string", + ], + [ + "spec2_invalid_towncrier_empty_section.toml", + r"towncrier.section must be a non-empty string", + ], + [ + "spec2_invalid_towncrier_package_unknown_key.toml", + r"\(acme.core\) towncrier has an unknown key 'setings'", + ], + [ + "spec2_invalid_towncrier_not_a_table.toml", + r"\(acme.core\) towncrier must be a table", + ], + [ + "spec2_invalid_towncrier_repository_enabled.toml", + r"\[repository\] towncrier.enabled is not part of spec 2", + ], + [ + "spec2_invalid_towncrier_repository_unknown_key.toml", + r"\[repository\] towncrier has an unknown key 'setting'", + ], + ], +) +def test_invalid_table_is_rejected_on_load(load, filename: str, message: str): + with pytest.raises(spec.RepositorySpecError, match=message): + load(filename) + + +def test_rejection_names_the_file(load): + with pytest.raises(spec.RepositorySpecError, match=r"^repository\.toml: "): + load("spec2_invalid_towncrier_flat_settings.toml") + + +def test_package_label_without_a_name(): + assert spec._package_label({}, 2) == "[[package]] #3" + assert spec._package_label({"name": "acme"}, 0) == "[[package]] #1 (acme)" + + +# ------------------------------------------------------------ spec 1 is unchanged + + +def test_spec1_reads_the_flat_keys(test_public_project, bust_path_cache): + result = settings.get_settings() + assert result.spec_version == 1 + assert _sections(result) == { + "python": ( + "Backend", + (test_public_project / "backend/pyproject.toml").resolve(), + ), + "node": ( + "Frontend", + ( + test_public_project + / "frontend/packages/fake-distribution/towncrier.toml" + ).resolve(), + ), + } + + +def test_spec1_repository_section(test_project_root_changelog, bust_path_cache): + result = settings.get_settings() + assert result.spec_version == 1 + assert _sections(result)["repository"] == ( + "Project", + (test_project_root_changelog / "towncrier.toml").resolve(), + ) + + +@pytest.mark.parametrize( + "replacement,present", + [ + ['settings = ""', False], + ['settings = "towncrier.toml"\nenabled = false', True], + ['settings = "towncrier.toml"\nenabled = true', True], + ], + ids=["empty-settings-is-off", "enabled-false-is-ignored", "enabled-true"], +) +def test_spec1_repository_section_depends_on_settings_only( + test_project_root_changelog, bust_path_cache, replacement: str, present: bool +): + """Spec 1 turns the section on by naming a file; enabled is never read.""" + path = test_project_root_changelog / "repository.toml" + text = path.read_text() + assert text.count('settings = "towncrier.toml"') == 1 + path.write_text(text.replace('settings = "towncrier.toml"', replacement)) + result = settings.get_settings() + assert (result.towncrier.get("repository") is not None) is present diff --git a/tests/test_schemas.py b/tests/test_schemas.py index a3f7774..49e6afd 100644 --- a/tests/test_schemas.py +++ b/tests/test_schemas.py @@ -13,6 +13,7 @@ from pytest_jsonschema import schemas as plugin_schemas from repoplone import schemas +import copy import jsonschema import pytest import tomlkit @@ -108,16 +109,49 @@ def _ids(paths: list[Path]) -> list[str]: ), } +#: Invalid fixtures the *published* spec 2 schema still accepts. The other +#: towncrier fixtures are rejected upstream too, if only because their +#: packages lack the towncrier_settings key pytest-jsonschema 1.1.0 requires. +PENDING_UPSTREAM_INVALID: dict[str, str] = { + "spec2_invalid_towncrier_flat_settings.toml": ( + "the published schema still requires the flat towncrier_settings key" + ), +} + +#: Why a valid spec 2 file fails through the published schema when its +#: packages use the towncrier table instead of the flat keys. +TOWNCRIER_TABLE_PENDING = ( + "the published schema still requires towncrier_settings on every package" +) + + +def _pending_reason(path: Path) -> str | None: + """Return why the published schema rejects a valid fixture, if it does. + + :param path: Fixture path. + :returns: The reason, or ``None`` when the published schema accepts it. + """ + if reason := PENDING_UPSTREAM.get(path.name): + return reason + packages = _load(path).get("package", []) + if any("towncrier_settings" not in package for package in packages): + return TOWNCRIER_TABLE_PENDING + return None -def _plugin_params(paths: list[Path]) -> list: - """Return parametrize entries, marking the ones the published schema rejects. + +def _plugin_params(paths: list[Path], valid: bool = True) -> list: + """Return parametrize entries, marking the ones where upstream lags. :param paths: Fixture paths. + :param valid: Whether the fixtures must pass validation. :returns: One entry per path, xfailed where upstream lags. """ params = [] for path in paths: - reason = PENDING_UPSTREAM.get(path.name) + if valid: + reason = _pending_reason(path) + else: + reason = PENDING_UPSTREAM_INVALID.get(path.name) marks = [pytest.mark.xfail(strict=True, reason=reason)] if reason else [] params.append( pytest.param(path, marks=marks, id=f"{path.parent.name}/{path.name}") @@ -218,10 +252,12 @@ def test_shipped_spec1_schema_matches_pytest_jsonschema(): @pytest.mark.xfail( strict=True, reason=( - "repository-v2 dropped the node-aurora base_package requirement once " - "the default (@plone/aurora) was settled. pytest-jsonschema 1.1.0 " - "still ships the stricter copy. When a release carries the change " - "this XPASSes and fails strictly -- remove the marker then." + "repository-v2 dropped the node-aurora base_package requirement and " + "replaced towncrier_settings, section and the repository-level " + "repositoryTowncrier definition with a shared towncrier table. " + "pytest-jsonschema 1.1.0 still ships the older copy. When a release " + "carries the change this XPASSes and fails strictly -- remove the " + "marker then." ), ) def test_shipped_spec2_schema_matches_pytest_jsonschema(): @@ -229,17 +265,66 @@ def test_shipped_spec2_schema_matches_pytest_jsonschema(): assert schemas.load(name) == plugin_schemas.load(name) +#: The repository-level towncrier definition pytest-jsonschema 1.1.0 ships. +PUBLISHED_REPOSITORY_TOWNCRIER = { + "type": "object", + "description": "Repository-level towncrier settings.", + "properties": { + "enabled": { + "description": ( + "Whether the repository-level towncrier is enabled. Derived " + "from the presence of this table." + ), + "type": "boolean", + }, + "section": { + "description": ( + "Heading used for this section in the repository changelog." + ), + "type": "string", + }, + "settings": { + "description": "Path to the towncrier settings file.", + "type": "string", + }, + }, + "additionalProperties": True, +} + +#: The flat package keys pytest-jsonschema 1.1.0 ships. +PUBLISHED_PACKAGE_TOWNCRIER_KEYS = { + "towncrier_settings": { + "description": ( + "Path to the package towncrier settings, relative to the repository root." + ), + "type": "string", + "minLength": 1, + }, + "section": { + "description": ( + "Heading used for this package in the repository changelog. " + "Defaults to the package name." + ), + "type": "string", + "minLength": 1, + }, +} + + def test_spec2_schemas_differ_only_in_the_known_way(): """Pin exactly how the two spec 2 copies differ, so nothing else drifts. The plain equality check above is expected to fail until pytest-jsonschema ships the update; without this, any *other* edit to one copy would hide - behind that expected failure. + behind that expected failure. Two changes are pending upstream: the + node-aurora base_package branch, and the towncrier table. """ - ours = schemas.load(schemas.SPEC_SCHEMAS[2]) - theirs = plugin_schemas.load(schemas.SPEC_SCHEMAS[2]) - ours_branches = ours["$defs"]["package"]["allOf"] - theirs_branches = theirs["$defs"]["package"]["allOf"] + ours = copy.deepcopy(schemas.load(schemas.SPEC_SCHEMAS[2])) + theirs = copy.deepcopy(plugin_schemas.load(schemas.SPEC_SCHEMAS[2])) + ours_package = ours["$defs"]["package"] + theirs_package = theirs["$defs"]["package"] + + # 1. The node-aurora branch, which upstream still carries. aurora = { "$comment": ( "node-aurora has no built-in base package default, so it must be declared." @@ -250,15 +335,32 @@ def test_spec2_schemas_differ_only_in_the_known_way(): }, "then": {"required": ["base_package"]}, } - assert theirs_branches == [*ours_branches, aurora] + assert theirs_package.pop("allOf") == [*ours_package.pop("allOf"), aurora] + + # 2. The towncrier table: one shared definition here, flat keys upstream. + assert theirs_package.pop("required") == [ + *ours_package.pop("required"), + "towncrier_settings", + ] + ours_towncrier = ours_package["properties"].pop("towncrier") + assert ours_towncrier["$ref"] == "#/$defs/towncrier" + for key, published in PUBLISHED_PACKAGE_TOWNCRIER_KEYS.items(): + assert theirs_package["properties"].pop(key) == published + ours_repository = ours["$defs"]["repository"]["properties"].pop("towncrier") + assert ours_repository["$ref"] == "#/$defs/towncrier" + assert theirs["$defs"]["repository"]["properties"].pop("towncrier") == { + "$ref": "#/$defs/repositoryTowncrier" + } + assert theirs["$defs"].pop("repositoryTowncrier") == ( + PUBLISHED_REPOSITORY_TOWNCRIER + ) + assert set(ours["$defs"].pop("towncrier")["properties"]) == { + "settings", + "section", + } - # Everything outside that one branch is identical. - ours_rest = {k: v for k, v in ours.items() if k != "$defs"} - theirs_rest = {k: v for k, v in theirs.items() if k != "$defs"} - assert ours_rest == theirs_rest - ours_defs = {k: v for k, v in ours["$defs"].items() if k != "package"} - theirs_defs = {k: v for k, v in theirs["$defs"].items() if k != "package"} - assert ours_defs == theirs_defs + # Everything else is identical, key order included. + assert ours == theirs @pytest.mark.parametrize("path", VALID_SPEC1_FILES, ids=_ids(VALID_SPEC1_FILES)) @@ -272,6 +374,6 @@ def test_valid_spec2_file_through_plugin(schema_validate_file, path: Path): assert schema_validate_file(path=path, schema_name="repository-v2") is True -@pytest.mark.parametrize("path", INVALID_SPEC2_FILES, ids=_ids(INVALID_SPEC2_FILES)) +@pytest.mark.parametrize("path", _plugin_params(INVALID_SPEC2_FILES, valid=False)) def test_invalid_spec2_file_through_plugin(schema_validate_file, path: Path): assert schema_validate_file(path=path, schema_name="repository-v2") is False