From a4d65649dec30a445ed74f8bc7f69828b2aaa4db Mon Sep 17 00:00:00 2001 From: George Fu Date: Fri, 4 Dec 2026 16:48:12 +0000 Subject: [PATCH] Add what-will-release target --- Makefile | 23 +- codegen/gen_fragments.py | 88 ++++- scripts/changelog/new-entry.py | 1 + scripts/changelog/new-release.py | 1 + scripts/changelog/templates/PACKAGE | 5 +- scripts/release/plan.py | 478 ++++++++++++++++++++++++++++ scripts/release/tests/test_plan.py | 343 ++++++++++++++++++++ 7 files changed, 925 insertions(+), 14 deletions(-) create mode 100644 scripts/release/plan.py create mode 100644 scripts/release/tests/test_plan.py diff --git a/Makefile b/Makefile index 1cde2cf6e..3a1a667fb 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,7 @@ SMITHY_PYTHON ?= ../smithy-python # Clients per gradle build in `make clients`; lower it if the build runs out of heap. BATCH_SIZE ?= 25 -.PHONY: docs docs-serve docs-clean docs-install docs-lock venv gen clients fragments publish-codegen aio-check meta-package-check static-analysis test-unit test-functional test-integration \ +.PHONY: docs docs-serve docs-clean docs-install docs-lock venv gen clients fragments alignment-fragments what-will-release wwr wwr-json publish-codegen aio-check meta-package-check static-analysis test-unit test-functional test-integration \ check-imports check-conventions check-api check-dependencies check-packaging check-import-stability verify-venv api-snapshot \ canonical-imports dunder-all source-order dynamic-imports banned-imports docstrings declared-deps import-cycles \ dep-specifiers package-metadata package-metadata-fix version-consistency export-names exception-hierarchy secret-repr import-hygiene \ @@ -32,6 +32,7 @@ INTEGRATION_SKIP := clients/aws-sdk-qbusiness static-analysis: $(MAKE) meta-package-check + $(MAKE) wwr uv run --no-project --python $(PYTHON_VERSION) python scripts/project-checks/project_checks.py \ $(RUFF_VERSION) $(PYRIGHT_VERSION) $(PYTHON_VERSION) $(PROJECTS) $(MAKE) aio-check @@ -93,6 +94,26 @@ clients: fragments: uv run --no-project --python $(PYTHON_VERSION) python codegen/gen_fragments.py +what-will-release: ## Catches a repo that cannot release, and shows what a release would publish and why. + uv run --no-project --python $(PYTHON_VERSION) python scripts/release/plan.py $(WWR_ARGS) + +wwr: what-will-release ## Short alias for what-will-release. + +wwr-json: ## Gives release tooling the release plan as JSON on stdout, with no table or make echo to strip. + @uv run --no-project --python $(PYTHON_VERSION) python scripts/release/plan.py --json - + +# Lets a lockstep minor release when clients have no change of their own, since the +# planner rejects a lockstep release in which a client has no fragment. +alignment-fragments: ## Writes the alignment fragment that lets clients without changes join a lockstep release. + @set -e; \ + minor=$$(uv run --no-project --python $(PYTHON_VERSION) python scripts/release/plan.py --next-minor); \ + for p in clients/*; do \ + [ $$(basename $$p) = aws-sdk-python ] && continue; \ + ls $$p/.changes/next-release/*.json >/dev/null 2>&1 && continue; \ + python3 scripts/changelog/new-entry.py -t alignment -p $$(basename $$p) \ + -d "Aligned with the $$minor release of the AWS SDK clients."; \ + done + ########################## Granular targets below ########################## # Publishes the smithy-python codegen jars to the local Maven cache so `gen` diff --git a/codegen/gen_fragments.py b/codegen/gen_fragments.py index 9746e9271..c2fb8d418 100644 --- a/codegen/gen_fragments.py +++ b/codegen/gen_fragments.py @@ -2,16 +2,21 @@ """Write a codegen sync changelog fragment for every generated client. Usage: python codegen/gen_fragments.py - Only for a smithy-python pointer move; the text comes from CODEGEN_SYNC_CHANGELOG.md - in the repo root. + Only for a smithy-python pointer move, after `make clients`. The text comes from + CODEGEN_SYNC_CHANGELOG.md in the repo root. A client whose smithy dependencies moved + a major or minor since the merge-base with origin/develop gets a `feature` fragment + (minor bump), any other client an `enhancement` (patch). Diffing against develop + means committing the regenerated files first does not hide a move. """ import json import re +import subprocess import sys import time import tomllib from pathlib import Path +from typing import Any from gen_client import load_services @@ -20,16 +25,23 @@ CLIENTS = REPO / "clients" POINTER = CODEGEN_DIR / "smithy-python.toml" SYNC_CHANGELOG = REPO / "CODEGEN_SYNC_CHANGELOG.md" +DEVELOP = "origin/develop" SMITHY_PYTHON_COMMITS = "https://github.com/smithy-lang/smithy-python/commits" # An older file is assumed to be left over from a previous sync. SYNC_CHANGELOG_MAX_AGE_SECONDS = 8 * 60 * 60 +_SMITHY_REQUIREMENT = re.compile( + r"^\s*(?Psmithy[-_][A-Za-z0-9_.-]*)\s*(?:\[[^\]]*\])?\s*" + r"(?:~=|==|>=)\s*(?P\d+)\.(?P\d+)", + re.IGNORECASE, +) def main() -> None: previous, commit = _pointer_commits() description = _description(previous, commit) + base = _base_commit() for name in _generated_clients(): - _write_fragment(name, commit, description) + _write_fragment(name, commit, _fragment_type(name, base), description) def _pointer_commits() -> tuple[str, str]: @@ -69,17 +81,69 @@ def _generated_clients() -> list[str]: return [f"aws-sdk-{service.slug}" for service in load_services()] -def _write_fragment(name: str, commit: str, description: str) -> None: - # Keyed by target commit: a rerun for the same pin overwrites, a later sync adds. - fragment = ( - CLIENTS - / name - / ".changes" - / "next-release" - / f"{name}-enhancement-codegen-sync-{commit}.json" +def _base_commit() -> str: + result = subprocess.run( + ["git", "merge-base", "HEAD", DEVELOP], + cwd=REPO, + capture_output=True, + text=True, + ) + if result.returncode != 0: + sys.exit(f"cannot diff client dependencies: no merge-base with {DEVELOP}") + return result.stdout.strip() + + +def _fragment_type(name: str, base: str) -> str: + head = _pyproject_at(name, base) + # A client absent from the base has no baseline to have moved from. + if head is None: + return "enhancement" + after = _read_pyproject(CLIENTS / name / "pyproject.toml") + return "feature" if _smithy_series(head) != _smithy_series(after) else "enhancement" + + +def _pyproject_at(name: str, base: str) -> dict[str, Any] | None: + result = subprocess.run( + ["git", "show", f"{base}:clients/{name}/pyproject.toml"], + cwd=REPO, + capture_output=True, + text=True, ) + return tomllib.loads(result.stdout) if result.returncode == 0 else None + + +def _read_pyproject(path: Path) -> dict[str, Any]: + with path.open("rb") as f: + return tomllib.load(f) + + +def _smithy_series(pyproject: dict[str, Any]) -> dict[str, tuple[int, int]]: + """Maps each smithy dependency to the highest major.minor it requires.""" + project = pyproject.get("project", {}) + requirements = list(project.get("dependencies", [])) + for extra in project.get("optional-dependencies", {}).values(): + requirements.extend(extra) + + series: dict[str, tuple[int, int]] = {} + for requirement in requirements: + match = _SMITHY_REQUIREMENT.match(requirement) + if match: + name = match["name"].lower().replace("_", "-") + found = (int(match["major"]), int(match["minor"])) + series[name] = max(series.get(name, found), found) + return series + + +def _write_fragment(name: str, commit: str, kind: str, description: str) -> None: + changes = CLIENTS / name / ".changes" / "next-release" + # Keyed by target commit: a rerun for the same pin overwrites, a later sync adds. + fragment = changes / f"{name}-{kind}-codegen-sync-{commit}.json" fragment.parent.mkdir(parents=True, exist_ok=True) - entry = {"type": "enhancement", "description": description} + # A rerun can change the type, which would otherwise leave both files behind. + for stale in changes.glob(f"{name}-*-codegen-sync-{commit}.json"): + if stale != fragment: + stale.unlink() + entry = {"type": kind, "description": description} fragment.write_text(json.dumps(entry, indent=2) + "\n") print(f"wrote {fragment}") diff --git a/scripts/changelog/new-entry.py b/scripts/changelog/new-entry.py index d99f14991..fadca66b6 100755 --- a/scripts/changelog/new-entry.py +++ b/scripts/changelog/new-entry.py @@ -87,6 +87,7 @@ def main(): "breaking", "dependency", "api-change", + "alignment", "summary", ), required=True, diff --git a/scripts/changelog/new-release.py b/scripts/changelog/new-release.py index 430e6c495..40c899aae 100755 --- a/scripts/changelog/new-release.py +++ b/scripts/changelog/new-release.py @@ -24,6 +24,7 @@ "enhancement": 3, "bugfix": 4, "dependency": 5, + "alignment": 6, } CHANGE_TYPES = tuple(CHANGE_TYPES_ORDER.keys()) diff --git a/scripts/changelog/templates/PACKAGE b/scripts/changelog/templates/PACKAGE index 2fd77369b..545bb4289 100644 --- a/scripts/changelog/templates/PACKAGE +++ b/scripts/changelog/templates/PACKAGE @@ -5,7 +5,7 @@ {{ changes.summary }} {%- endif %} -{%- for type_name in ['api-change', 'breaking', 'feature', 'enhancement', 'bugfix', 'dependency'] %} +{%- for type_name in ['api-change', 'breaking', 'feature', 'enhancement', 'bugfix', 'dependency', 'alignment'] %} {%- for change in changes.changes if change.type == type_name %} {%- if loop.first %} {%- if type_name == 'api-change' %} @@ -26,6 +26,9 @@ {%- elif type_name == 'dependency' %} ### Dependencies +{%- elif type_name == 'alignment' %} + +### Alignment {%- endif %} {%- endif %} * {{ change.description }} diff --git a/scripts/release/plan.py b/scripts/release/plan.py new file mode 100644 index 000000000..e9e6acb4c --- /dev/null +++ b/scripts/release/plan.py @@ -0,0 +1,478 @@ +#!/usr/bin/env python3 +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Plan the next release of the clients and packages from their changelog fragments.""" + +import argparse +import json +import re +import sys +import tomllib +from collections.abc import Sequence +from dataclasses import asdict, dataclass +from graphlib import TopologicalSorter +from pathlib import Path + +META_PACKAGE = "aws-sdk-python" +CHANGE_TYPES = ( + "api-change", + "breaking", + "feature", + "enhancement", + "bugfix", + "dependency", + "alignment", +) + +_CLIENTS_DIR = "clients" +_PACKAGES_DIR = "packages" +# CAUTION: add 4 here at the manual GA. +_MAJORS = (0,) +_RELEASE_FILE = re.compile(r"^\d+\.\d+\.\d+\.json$") +_CONSTRAINED_DEPENDENCY = re.compile( + r"^\s*([A-Za-z0-9][A-Za-z0-9._-]*)\s*(?:\[[^\]]*\])?\s*(~=|==)" +) +_VERSION_ASSIGNMENT = re.compile( + r"""^__version__\s*=\s*["']([^"']+)["']""", re.MULTILINE +) + + +class InvalidState(Exception): + """The repository cannot release in its current state.""" + + def __init__(self, problems: Sequence[str]): + super().__init__("\n".join(problems)) + self.problems = list(problems) + + +@dataclass +class PackageVersionPlan: + """Version plan for a single package.""" + + name: str + current_version: str | None + new_version: str + change_type: str + path: str + changelog_note: str | None = None + + +@dataclass +class VersionPlan: + """Complete version plan for the packages of one repository.""" + + packages: list[PackageVersionPlan] + + def to_json(self) -> str: + return json.dumps(asdict(self), indent=2) + + +@dataclass +class Release: + """A version plan with the reasons that the table shows.""" + + plan: VersionPlan + reasons: dict[str, str] + lockstep: str | None + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Show what the next release contains.") + parser.add_argument( + "--root", type=Path, default=Path(__file__).resolve().parents[2] + ) + parser.add_argument( + "--json", metavar="PATH", help="Write the plan as JSON; '-' for stdout." + ) + parser.add_argument( + "--next-minor", + action="store_true", + help="Print the J.N minor that the next lockstep release moves the clients to.", + ) + args = parser.parse_args(argv) + + try: + if args.next_minor: + print(".".join(next_lockstep_version(args.root).split(".")[:2])) + return 0 + release = plan_release(args.root) + except InvalidState as error: + print("The repository is not in a releasable state:", file=sys.stderr) + for problem in error.problems: + print(f" {problem}", file=sys.stderr) + return 1 + + if args.json == "-": + print(release.plan.to_json()) + return 0 + if args.json: + Path(args.json).write_text(release.plan.to_json() + "\n") + print(format_table(release)) + return 0 + + +def plan_release(root: Path) -> Release: + """Plan the release of every client and package under root.""" + packages = _load_packages(root) + problems = [ + problem for package in packages.values() for problem in package.problems + ] + problems += [ + f"{name} pins in-repo dependency {dependency} with ==; use ~=" + for name, package in packages.items() + for dependency, operator in package.constrained.items() + if operator == "==" and dependency in packages + ] + problems += [ + f"{name} is at {package.version}; clients and the meta-package must be 0.x" + for name, package in packages.items() + if package.in_lockstep_scope and _parse(package.version)[0] not in _MAJORS + ] + if problems: + raise InvalidState(problems) + + plans: dict[str, _Plan] = {} + initial = { + name for name, p in packages.items() if p.is_unreleased_client and p.fragments + } + order = _release_order(packages) + _plan_own_and_propagated(packages, order, plans, initial, frozen=set()) + + lockstep_version = None + if any( + name in plans and plans[name].bump == "minor" + for name in _lockstep_names(packages) + ): + lockstep_version = next_lockstep_version(root, packages) + frozen = _apply_lockstep(packages, plans, lockstep_version) + _plan_own_and_propagated(packages, order, plans, initial, frozen=frozen) + + _plan_initial_releases(packages, plans, initial, lockstep_version) + + entries: list[PackageVersionPlan] = [] + reasons: dict[str, str] = {} + for name, package in packages.items(): + plan = plans.get(name) + if plan is None: + continue + entries.append( + PackageVersionPlan( + name=name, + current_version=None if name in initial else package.version, + new_version=plan.new_version, + change_type=plan.bump if plan.bump != "initial" else "minor", + path=str(package.path), + ) + ) + reasons[name] = plan.reason + return Release(VersionPlan(entries), reasons, lockstep_version) + + +def next_lockstep_version( + root: Path, packages: "dict[str, _Package] | None" = None +) -> str: + """Return the J.(N+1).0 that a lockstep release moves every client to.""" + packages = packages if packages is not None else _load_packages(root) + major, minor = _prevailing_series(packages) + return f"{major}.{minor + 1}.0" + + +def format_table(release: Release) -> str: + """Render the plan as a table with the reason for each version.""" + rows = [("package", "current", "new", "bump", "why")] + for entry in release.plan.packages: + bump = "initial" if entry.current_version is None else entry.change_type + rows.append( + ( + entry.name, + entry.current_version or "unreleased", + entry.new_version, + bump, + release.reasons[entry.name], + ) + ) + widths = [max(len(row[i]) for row in rows) for i in range(4)] + lines = [ + " ".join(cell.ljust(widths[i]) for i, cell in enumerate(row[:4])) + + f" {row[4]}" + for row in rows + ] + header = ( + f"Lockstep release: clients and {META_PACKAGE} move to {release.lockstep}" + if release.lockstep + else "No lockstep release." + ) + lines = [header, "", *lines] + if len(rows) == 1: + lines.append("(nothing to release)") + return "\n".join(lines) + + +@dataclass +class _Plan: + new_version: str + bump: str + reason: str + + +@dataclass +class _Package: + name: str + path: Path + kind: str + version: str + released: bool + fragments: list[str] + constrained: dict[str, str] + problems: list[str] + + @property + def is_unreleased_client(self) -> bool: + return self.kind == "client" and not self.released + + @property + def in_lockstep_scope(self) -> bool: + return self.kind in ("client", "meta") + + +def _load_packages(root: Path) -> dict[str, _Package]: + packages: dict[str, _Package] = {} + for directory in (_CLIENTS_DIR, _PACKAGES_DIR): + for path in sorted((root / directory).glob("*/pyproject.toml")): + package = _load_package(path.parent, directory) + packages[package.name] = package + + names = set(packages) + for package in packages.values(): + package.constrained = { + dep: op + for dep, op in package.constrained.items() + if dep in names and dep != package.name + } + return packages + + +def _load_package(path: Path, directory: str) -> _Package: + with open(path / "pyproject.toml", "rb") as f: + pyproject = tomllib.load(f) + project = pyproject["project"] + name = _normalize(project["name"]) + kind = ( + "package" + if directory == _PACKAGES_DIR + else "meta" + if name == META_PACKAGE + else "client" + ) + + problems: list[str] = [] + fragments = _load_fragments(path, name, problems) + changes = path / ".changes" + released = changes.is_dir() and any( + _RELEASE_FILE.match(f.name) for f in changes.iterdir() + ) + + return _Package( + name=name, + path=path, + kind=kind, + version=_read_version(path, pyproject), + released=released, + fragments=fragments, + constrained=_constrained_dependencies(project), + problems=problems, + ) + + +def _load_fragments(path: Path, name: str, problems: list[str]) -> list[str]: + directory = path / ".changes" / "next-release" + types: list[str] = [] + if not directory.is_dir(): + return types + for fragment in sorted(directory.glob("*.json")): + if fragment.name == "SUMMARY.json": + continue + try: + change_type = json.loads(fragment.read_text()).get("type") + except (OSError, json.JSONDecodeError, AttributeError) as error: + problems.append(f"{name}: cannot read fragment {fragment.name}: {error}") + continue + if change_type not in CHANGE_TYPES: + problems.append( + f"{name}: fragment {fragment.name} has unknown type {change_type!r}" + ) + continue + types.append(change_type) + return types + + +def _read_version(path: Path, pyproject: dict) -> str: + project = pyproject["project"] + if "version" in project: + return project["version"] + relative = pyproject.get("tool", {}).get("hatch", {}).get("version", {}).get("path") + if relative is None: + raise ValueError( + f"{path.name}: no version in pyproject.toml and no hatch version path" + ) + match = _VERSION_ASSIGNMENT.search((path / relative).read_text()) + if match is None: + raise ValueError(f"{path.name}: no __version__ in {relative}") + return match.group(1) + + +def _constrained_dependencies(project: dict) -> dict[str, str]: + requirements = list(project.get("dependencies", [])) + for group in project.get("optional-dependencies", {}).values(): + requirements.extend(group) + constrained: dict[str, str] = {} + for requirement in requirements: + match = _CONSTRAINED_DEPENDENCY.match(requirement) + if match: + constrained[_normalize(match.group(1))] = match.group(2) + return constrained + + +def _normalize(name: str) -> str: + return re.sub(r"[-_.]+", "-", name).lower() + + +def _release_order(packages: dict[str, _Package]) -> list[str]: + graph = {name: set(package.constrained) for name, package in packages.items()} + return list(TopologicalSorter(graph).static_order()) + + +def _lockstep_names(packages: dict[str, _Package]) -> list[str]: + return [name for name, package in packages.items() if package.in_lockstep_scope] + + +def _prevailing_series(packages: dict[str, _Package]) -> tuple[int, int]: + released = [ + _parse(package.version) + for package in packages.values() + if package.kind == "client" and package.released + ] + if not released: + raise InvalidState(["no released client to take the prevailing version from"]) + major = max(version[0] for version in released) + return major, max(version[1] for version in released if version[0] == major) + + +def _plan_own_and_propagated( + packages: dict[str, _Package], + order: list[str], + plans: dict[str, _Plan], + initial: set[str], + frozen: set[str], +) -> None: + for name in order: + package = packages[name] + if name in frozen or name in initial: + continue + bump, reason = _own_bump(package) + for dependency, operator in sorted(package.constrained.items()): + moved = plans.get(dependency) + if moved is not None and moved.bump in ("minor", "major"): + if bump not in ("minor", "major"): + bump, reason = ( + "minor", + f"`{operator}` range on {dependency} moves to {moved.new_version}", + ) + break + if bump == "none": + plans.pop(name, None) + else: + plans[name] = _Plan(_apply_bump(package.version, bump), bump, reason) + + +def _own_bump(package: _Package) -> tuple[str, str]: + types = set(package.fragments) + if not types: + return "none", "" + reason = ", ".join(sorted(types)) + if package.in_lockstep_scope: + minor = "breaking" in types or ( + "feature" in types and (package.released or package.kind == "meta") + ) + return ("minor" if minor else "patch"), reason + if "breaking" in types: + return ("major" if _parse(package.version)[0] >= 1 else "minor"), reason + if "feature" in types: + return "minor", reason + return "patch", reason + + +def _apply_lockstep( + packages: dict[str, _Package], plans: dict[str, _Plan], target: str +) -> set[str]: + missing = [ + name + for name, package in packages.items() + if package.in_lockstep_scope + and package.kind != "meta" + and not package.fragments + ] + if missing: + raise InvalidState( + [ + f"lockstep release {target} needs a fragment in .changes/next-release for:" + ] + + [f" {name}" for name in missing] + ) + + frozen: set[str] = set() + problems: list[str] = [] + for name, package in packages.items(): + if not package.in_lockstep_scope or package.is_unreleased_client: + continue + if _parse(target) <= _parse(package.version): + problems.append( + f"{name} is at {package.version}, not below lockstep version {target}" + ) + continue + own = plans.get(name) + reason = ( + "lockstep" + if own is None or own.bump != "minor" + else f"{own.reason}; lockstep" + ) + plans[name] = _Plan(target, "minor", reason) + frozen.add(name) + if problems: + raise InvalidState(problems) + return frozen + + +def _plan_initial_releases( + packages: dict[str, _Package], + plans: dict[str, _Plan], + initial: set[str], + lockstep_version: str | None, +) -> None: + if not initial: + return + if lockstep_version is None: + major, minor = _prevailing_series(packages) + version = f"{major}.{minor}.0" + else: + version = lockstep_version + for name in initial: + plans[name] = _Plan(version, "initial", "initial client release") + + +def _apply_bump(version: str, bump: str) -> str: + major, minor, patch = _parse(version) + if bump == "major": + return f"{major + 1}.0.0" + if bump == "minor": + return f"{major}.{minor + 1}.0" + return f"{major}.{minor}.{patch + 1}" + + +def _parse(version: str) -> tuple[int, int, int]: + major, minor, patch = (int(part) for part in version.split(".")) + return major, minor, patch + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/release/tests/test_plan.py b/scripts/release/tests/test_plan.py new file mode 100644 index 000000000..afa5ea197 --- /dev/null +++ b/scripts/release/tests/test_plan.py @@ -0,0 +1,343 @@ +"""Tests for the release planner.""" + +import json +from pathlib import Path + +import pytest + +from scripts.release.plan import InvalidState, main, next_lockstep_version, plan_release + + +def add_package( + root: Path, + directory: str, + name: str, + version: str, + fragments: tuple[str, ...] = (), + released: bool = True, + deps: tuple[str, ...] = (), + extras: tuple[str, ...] = (), +) -> None: + path = root / directory / name + path.mkdir(parents=True) + dependencies = ", ".join(f'"{dep}"' for dep in deps) + optional = "".join(f'x{i} = ["{extra}"]\n' for i, extra in enumerate(extras)) + (path / "pyproject.toml").write_text( + f'[project]\nname = "{name}"\nversion = "{version}"\n' + f"dependencies = [{dependencies}]\n[project.optional-dependencies]\n{optional}" + ) + changes = path / ".changes" + (changes / "next-release").mkdir(parents=True) + if released: + (changes / f"{version}.json").write_text('{"changes": []}') + for index, change_type in enumerate(fragments): + fragment = {"type": change_type, "description": "d"} + (changes / "next-release" / f"{index}.json").write_text(json.dumps(fragment)) + + +def versions(root: Path) -> dict[str, str]: + return {p.name: p.new_version for p in plan_release(root).plan.packages} + + +def test_model_only_patches(tmp_path: Path) -> None: + add_package(tmp_path, "clients", "aws-sdk-a", "0.13.1", ("api-change",)) + add_package(tmp_path, "clients", "aws-sdk-b", "0.13.4") + add_package(tmp_path, "clients", "aws-sdk-python", "0.13.1", ("dependency",)) + + release = plan_release(tmp_path) + + assert release.lockstep is None + assert {p.name: (p.new_version, p.change_type) for p in release.plan.packages} == { + "aws-sdk-a": ("0.13.2", "patch"), + "aws-sdk-python": ("0.13.2", "patch"), + } + + +def test_feature_triggers_lockstep(tmp_path: Path) -> None: + add_package(tmp_path, "clients", "aws-sdk-a", "0.13.1", ("feature",)) + add_package(tmp_path, "clients", "aws-sdk-b", "0.13.4", ("api-change",)) + add_package(tmp_path, "clients", "aws-sdk-c", "0.12.9", ("alignment",)) + add_package(tmp_path, "clients", "aws-sdk-python", "0.13.1", ("dependency",)) + + release = plan_release(tmp_path) + + assert release.lockstep == "0.14.0" + assert versions(tmp_path) == { + "aws-sdk-a": "0.14.0", + "aws-sdk-b": "0.14.0", + "aws-sdk-c": "0.14.0", + "aws-sdk-python": "0.14.0", + } + + +def test_lockstep_uses_highest_released_minor(tmp_path: Path) -> None: + add_package(tmp_path, "clients", "aws-sdk-a", "0.13.1", ("feature",)) + add_package(tmp_path, "clients", "aws-sdk-b", "0.15.0", ("api-change",)) + add_package(tmp_path, "clients", "aws-sdk-python", "0.13.1", ("dependency",)) + + assert next_lockstep_version(tmp_path) == "0.16.0" + + +def test_lockstep_with_missing_fragments_fails( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + add_package(tmp_path, "clients", "aws-sdk-a", "0.13.1", ("feature",)) + add_package(tmp_path, "clients", "aws-sdk-b", "0.13.1") + add_package(tmp_path, "clients", "aws-sdk-c", "0.13.1") + add_package(tmp_path, "clients", "aws-sdk-python", "0.13.1", ("dependency",)) + + with pytest.raises(InvalidState) as error: + plan_release(tmp_path) + assert error.value.problems[1:] == [" aws-sdk-b", " aws-sdk-c"] + + assert main(["--root", str(tmp_path)]) == 1 + err = capsys.readouterr().err + assert "aws-sdk-b" in err and "aws-sdk-c" in err + + +def test_meta_package_without_fragment_follows_lockstep(tmp_path: Path) -> None: + add_package(tmp_path, "clients", "aws-sdk-a", "0.13.1", ("feature",)) + add_package(tmp_path, "clients", "aws-sdk-python", "0.13.1") + + release = plan_release(tmp_path) + + assert {p.name: p.new_version for p in release.plan.packages}[ + "aws-sdk-python" + ] == "0.14.0" + + +@pytest.mark.parametrize("version", ["1.0.0", "4.2.0"]) +def test_client_major_other_than_0_or_4_is_invalid( + tmp_path: Path, version: str +) -> None: + add_package(tmp_path, "clients", "aws-sdk-a", version, ("api-change",)) + + with pytest.raises(InvalidState) as error: + plan_release(tmp_path) + + assert error.value.problems == [ + f"aws-sdk-a is at {version}; clients and the meta-package must be 0.x" + ] + + +def test_exact_pin_of_an_in_repo_package_is_invalid(tmp_path: Path) -> None: + add_package(tmp_path, "clients", "aws-sdk-a", "0.13.1", ("api-change",)) + add_package( + tmp_path, "packages", "aws-credentials-x", "0.5.0", deps=("aws-sdk-a==0.13.1",) + ) + + with pytest.raises(InvalidState) as error: + plan_release(tmp_path) + + assert error.value.problems == [ + "aws-credentials-x pins in-repo dependency aws-sdk-a with ==; use ~=" + ] + + +def test_unreleased_client_does_not_trigger_lockstep(tmp_path: Path) -> None: + add_package(tmp_path, "clients", "aws-sdk-a", "0.13.1", ("api-change",)) + add_package( + tmp_path, "clients", "aws-sdk-new", "0.13.0", ("feature",), released=False + ) + add_package(tmp_path, "clients", "aws-sdk-python", "0.13.1", ("dependency",)) + + release = plan_release(tmp_path) + + assert release.lockstep is None + assert {p.name: p.new_version for p in release.plan.packages}[ + "aws-sdk-new" + ] == "0.13.0" + + +def test_unreleased_client_joins_lockstep_minor(tmp_path: Path) -> None: + add_package(tmp_path, "clients", "aws-sdk-a", "0.13.1", ("feature",)) + add_package( + tmp_path, "clients", "aws-sdk-new", "0.13.0", ("feature",), released=False + ) + add_package(tmp_path, "clients", "aws-sdk-python", "0.13.1", ("dependency",)) + + assert versions(tmp_path)["aws-sdk-new"] == "0.14.0" + + +def test_unreleased_client_without_fragment_blocks_lockstep(tmp_path: Path) -> None: + add_package(tmp_path, "clients", "aws-sdk-a", "0.13.1", ("feature",)) + add_package(tmp_path, "clients", "aws-sdk-new", "0.13.0", released=False) + add_package(tmp_path, "clients", "aws-sdk-python", "0.13.1", ("dependency",)) + + with pytest.raises(InvalidState, match="aws-sdk-new"): + plan_release(tmp_path) + + +def test_meta_package_follows_lockstep(tmp_path: Path) -> None: + add_package(tmp_path, "clients", "aws-sdk-a", "0.13.1", ("feature",)) + add_package( + tmp_path, + "clients", + "aws-sdk-python", + "0.13.1", + ("dependency",), + extras=("aws_sdk_a~=0.13.0",), + ) + + assert versions(tmp_path)["aws-sdk-python"] == "0.14.0" + + +def test_meta_package_feature_triggers_lockstep(tmp_path: Path) -> None: + add_package(tmp_path, "clients", "aws-sdk-a", "0.13.1", ("api-change",)) + add_package(tmp_path, "clients", "aws-sdk-python", "0.13.1", ("feature",)) + + assert versions(tmp_path) == {"aws-sdk-a": "0.14.0", "aws-sdk-python": "0.14.0"} + + +def test_packages_use_generic_rules(tmp_path: Path) -> None: + add_package(tmp_path, "clients", "aws-sdk-a", "0.13.1", ("api-change",)) + add_package(tmp_path, "clients", "aws-sdk-python", "0.13.1", ("dependency",)) + add_package(tmp_path, "packages", "aws-credentials-x", "0.5.0", ("enhancement",)) + add_package(tmp_path, "packages", "aws-credentials-y", "0.5.0", ("feature",)) + add_package(tmp_path, "packages", "aws-credentials-z", "1.2.3", ("breaking",)) + add_package(tmp_path, "packages", "aws-credentials-w", "0.5.0", ("breaking",)) + add_package( + tmp_path, + "packages", + "aws-credentials-dep", + "0.2.0", + ("bugfix",), + deps=("aws-credentials-y~=0.5.0",), + ) + + result = versions(tmp_path) + + assert result["aws-credentials-x"] == "0.5.1" + assert result["aws-credentials-y"] == "0.6.0" + assert result["aws-credentials-z"] == "2.0.0" + assert result["aws-credentials-w"] == "0.6.0" + assert result["aws-credentials-dep"] == "0.3.0" + assert result["aws-sdk-a"] == "0.13.2" + + +def test_package_without_fragments_does_not_release(tmp_path: Path) -> None: + add_package(tmp_path, "clients", "aws-sdk-a", "0.13.1", ("api-change",)) + add_package(tmp_path, "packages", "aws-credentials-x", "0.5.0") + + assert versions(tmp_path) == {"aws-sdk-a": "0.13.2"} + + +def test_package_minor_propagates_to_client_and_triggers_lockstep( + tmp_path: Path, +) -> None: + add_package(tmp_path, "packages", "aws-credentials-x", "0.5.0", ("feature",)) + add_package( + tmp_path, + "clients", + "aws-sdk-a", + "0.13.1", + ("api-change",), + deps=("aws-credentials-x~=0.5.0",), + ) + add_package(tmp_path, "clients", "aws-sdk-b", "0.13.1", ("api-change",)) + add_package(tmp_path, "clients", "aws-sdk-python", "0.13.1", ("dependency",)) + + result = versions(tmp_path) + + assert result["aws-credentials-x"] == "0.6.0" + assert ( + result["aws-sdk-a"] + == result["aws-sdk-b"] + == result["aws-sdk-python"] + == "0.14.0" + ) + + +def test_client_breaking_is_clamped_to_minor(tmp_path: Path) -> None: + add_package(tmp_path, "clients", "aws-sdk-a", "0.4.2", ("breaking",)) + add_package(tmp_path, "clients", "aws-sdk-b", "0.4.0", ("api-change",)) + add_package(tmp_path, "clients", "aws-sdk-python", "0.4.2", ("dependency",)) + + assert versions(tmp_path) == { + "aws-sdk-a": "0.5.0", + "aws-sdk-b": "0.5.0", + "aws-sdk-python": "0.5.0", + } + + +def test_alignment_alone_patches(tmp_path: Path) -> None: + add_package(tmp_path, "clients", "aws-sdk-a", "0.13.1", ("alignment",)) + + assert versions(tmp_path) == {"aws-sdk-a": "0.13.2"} + + +def test_unknown_fragment_type_is_invalid(tmp_path: Path) -> None: + add_package(tmp_path, "clients", "aws-sdk-a", "0.13.1", ("bogus",)) + + with pytest.raises(InvalidState, match="aws-sdk-a"): + plan_release(tmp_path) + + +def test_summary_file_is_not_a_fragment(tmp_path: Path) -> None: + add_package(tmp_path, "clients", "aws-sdk-a", "0.13.1") + (tmp_path / "clients/aws-sdk-a/.changes/next-release/SUMMARY.json").write_text( + '{"summary": "s"}' + ) + + assert versions(tmp_path) == {} + + +def test_version_read_from_hatch_path(tmp_path: Path) -> None: + add_package(tmp_path, "clients", "aws-sdk-a", "0.13.1", ("api-change",)) + path = tmp_path / "clients/aws-sdk-a" + (path / "pyproject.toml").write_text( + '[project]\nname = "aws-sdk-a"\ndynamic = ["version"]\n' + '[tool.hatch.version]\npath = "src/a/__init__.py"\n' + ) + (path / "src/a").mkdir(parents=True) + (path / "src/a/__init__.py").write_text('__version__ = "0.13.1"\n') + + assert versions(tmp_path) == {"aws-sdk-a": "0.13.2"} + + +def test_json_schema(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + add_package(tmp_path, "clients", "aws-sdk-a", "0.13.1", ("api-change",)) + add_package( + tmp_path, "clients", "aws-sdk-new", "0.13.0", ("feature",), released=False + ) + + assert main(["--root", str(tmp_path), "--json", "-"]) == 0 + data = json.loads(capsys.readouterr().out) + + assert list(data) == ["packages"] + keys = [ + "name", + "current_version", + "new_version", + "change_type", + "path", + "changelog_note", + ] + assert all(list(package) == keys for package in data["packages"]) + assert data["packages"][0] == { + "name": "aws-sdk-a", + "current_version": "0.13.1", + "new_version": "0.13.2", + "change_type": "patch", + "path": str(tmp_path / "clients/aws-sdk-a"), + "changelog_note": None, + } + + +def test_json_file_and_table( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + add_package(tmp_path, "clients", "aws-sdk-a", "0.13.1", ("api-change",)) + out = tmp_path / "plan.json" + + assert main(["--root", str(tmp_path), "--json", str(out)]) == 0 + + assert json.loads(out.read_text())["packages"][0]["name"] == "aws-sdk-a" + assert "aws-sdk-a" in capsys.readouterr().out + + +def test_next_minor_flag(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + add_package(tmp_path, "clients", "aws-sdk-a", "0.13.1") + + assert main(["--root", str(tmp_path), "--next-minor"]) == 0 + assert capsys.readouterr().out.strip() == "0.14"