From 90c699cb9f4179e2352c1ecc10118203824f0153 Mon Sep 17 00:00:00 2001 From: jcook3701 Date: Tue, 1 Dec 2026 17:03:09 -0800 Subject: [PATCH 1/2] feat: prepare reviewed Python generator releases --- .github/workflows/release-preparation.yml | 61 ++ Makefile | 72 +- README.md | 8 + changelogs/CHANGELOG.md | 4 + changelogs/releases/v0.1.0.md | 6 +- docs/jekyll/README.md | 9 + docs/release-cycle.md | 23 + pyproject.toml | 18 +- release-policy.json | 25 + scripts/release_plan.py | 825 ++++++++++++++++++++++ scripts/release_prepare.py | 187 +++++ scripts/release_publish.py | 426 +++++++++++ tests/test_generator_release.py | 100 +++ 13 files changed, 1730 insertions(+), 34 deletions(-) create mode 100644 .github/workflows/release-preparation.yml create mode 100644 docs/release-cycle.md create mode 100644 release-policy.json create mode 100644 scripts/release_plan.py create mode 100644 scripts/release_prepare.py create mode 100644 scripts/release_publish.py create mode 100644 tests/test_generator_release.py diff --git a/.github/workflows/release-preparation.yml b/.github/workflows/release-preparation.yml new file mode 100644 index 0000000..f619051 --- /dev/null +++ b/.github/workflows/release-preparation.yml @@ -0,0 +1,61 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, Jared W. Cook +# SPDX-License-Identifier: AGPL-3.0-or-later +--- +name: Release Preparation +on: + push: + branches: ["main"] + workflow_dispatch: + inputs: + baseline: + description: "Verified published baseline commit (optional)" + type: string + required: false + published_version: + description: "Verified published version (required with baseline)" + type: string + required: false + +permissions: + contents: read + +concurrency: + group: release-preparation-${{ github.sha }} + cancel-in-progress: false + +jobs: + prepare: + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + timeout-minutes: 10 + env: + RELEASE_BASELINE: ${{ inputs.baseline }} + PUBLISHED_VERSION: ${{ inputs.published_version }} + steps: + - name: Checkout exact production commit + uses: actions/checkout@v7 + with: + fetch-depth: 0 + persist-credentials: false + - name: Set up Python + uses: actions/setup-python@v7 + with: + python-version: "3.11" + - name: Set artifact directory + run: echo "RELEASE_OUTPUT=$RUNNER_TEMP/release-artifacts" >> "$GITHUB_ENV" + - name: Verify snapshot and package source + run: make package-source + - name: Calculate release plan + if: env.RELEASE_BASELINE != '' || env.PUBLISHED_VERSION != '' + run: make release-plan > "$RELEASE_OUTPUT/plan.json" + - name: Verify source checksum + working-directory: ${{ env.RELEASE_OUTPUT }} + run: | + sha256sum -c SHA256SUMS + sha256sum release.json + - name: Preserve production candidate + uses: actions/upload-artifact@v4 + with: + name: release-candidate-${{ github.sha }} + path: ${{ env.RELEASE_OUTPUT }} + if-no-files-found: error diff --git a/Makefile b/Makefile index 2cd1e33..3050e1f 100644 --- a/Makefile +++ b/Makefile @@ -416,15 +416,13 @@ pip-install: ## The standard package installer for Python. # -------------------------------------------------- # πŸš€ Release (git-push, github-release) # -------------------------------------------------- -git-push: ## Distributed version control system for tracking changes in source code. - $(AT)echo "Running πŸš€ Pushing tag $(RELEASE) to origin..." - $(AT)$(GIT) push origin $(RELEASE) - $(AT)echo "βœ… Push complete!" +git-push: + $(AT)echo "Use reviewed release preparation; direct release mutations are disabled." + $(AT)false -github-release: ## GitHub’s official command line tool for repository and release management. - $(AT)echo "Running πŸš€ Creating GitHub release for $(RELEASE)..." - $(AT)$(GITHUB) release create $(RELEASE) --generate-notes - $(AT)echo "βœ… GitHub release created!" +github-release: + $(AT)echo "Use reviewed release preparation; direct release mutations are disabled." + $(AT)false # -------------------------------------------------- # πŸ› οΈ Setup (venv-create, git-init, git-remote, github-auth) # -------------------------------------------------- @@ -527,25 +525,21 @@ git-commit: ## Distributed version control system for tracking changes in source # -------------------------------------------------- # πŸ”– Versioning (bumpversion-patch, bumpversion-minor, bumpversion-major, git-tag) # -------------------------------------------------- -bumpversion-patch: ## Version bumping tool with Git tagging support. - $(AT)echo "Running πŸ”– Updating $(PROJECT_NAME) patch version from $(VERSION)..." - $(AT)$(BUMPVERSION) bump --verbose patch - $(AT)echo "βœ… Patch version update complete!" +bumpversion-patch: + $(AT)echo "Use reviewed release preparation; direct release mutations are disabled." + $(AT)false -bumpversion-minor: ## Version bumping tool with Git tagging support. - $(AT)echo "Running πŸ”– Updating $(PROJECT_NAME) minor version from $(VERSION)..." - $(AT)$(BUMPVERSION) bump --verbose minor - $(AT)echo "βœ… Minor version update complete!" +bumpversion-minor: + $(AT)echo "Use reviewed release preparation; direct release mutations are disabled." + $(AT)false -bumpversion-major: ## Version bumping tool with Git tagging support. - $(AT)echo "Running πŸ”– Updating $(PROJECT_NAME) major version from $(VERSION)..." - $(AT)$(BUMPVERSION) bump --verbose major - $(AT)echo "βœ… Major version update complete!" +bumpversion-major: + $(AT)echo "Use reviewed release preparation; direct release mutations are disabled." + $(AT)false -git-tag: ## Distributed version control system for tracking changes in source code. - $(AT)echo "Running πŸ”– Creating Git tag for $(RELEASE)..." - $(AT)$(GIT) tag -a $(RELEASE) -m 'Release $(RELEASE)' - $(AT)echo "βœ… Git tag created!" +git-tag: + $(AT)echo "Use reviewed release preparation; direct release mutations are disabled." + $(AT)false # -------------------------------------------------- # Compatibility targets (existing CI, hooks and project commands) @@ -592,18 +586,34 @@ test: test-run .PHONY: readme readme: nutrimatic-readme .PHONY: bump-version-patch -bump-version-patch: bumpversion-patch +bump-version-patch: + $(AT)echo "Use reviewed release preparation; direct release mutations are disabled." + $(AT)false .PHONY: changelog changelog: git-cliff-full git-cliff-unreleased $(AT)$(GIT) add "$(CHANGELOG_FILE)" "$(CHANGELOG_RELEASE_FILE)" .PHONY: git-release release git-release: - $(AT)$(MAKE) git-tag - $(AT)$(MAKE) git-push - $(AT)$(MAKE) github-release -release: - $(AT)$(MAKE) git-release - $(AT)$(MAKE) bump-version-patch + $(AT)echo "Use reviewed release preparation; direct release mutations are disabled." + $(AT)false +# Version planning is read-only. Publishing is separately authorized. +.PHONY: release-plan package-source release-prepare +release-plan: + $(AT)python3 scripts/release_plan.py --baseline "$$RELEASE_BASELINE" \ + --published-version "$$PUBLISHED_VERSION" --current-version "$(VERSION)" + +release-prepare: + $(AT)test -n "$$RELEASE_OUTPUT" + $(AT)$(PYTHON) scripts/release_prepare.py --baseline "$$RELEASE_BASELINE" \ + --published-version "$$PUBLISHED_VERSION" --current-version "$(VERSION)" \ + --output "$$RELEASE_OUTPUT" + +package-source: + $(AT)test -n "$$RELEASE_OUTPUT" + $(AT)python3 scripts/release_plan.py --current-version "$(VERSION)" \ + --package-dir "$$RELEASE_OUTPUT" + +release: release-plan # Keep setup and checks sequential even when make is invoked with -j. all: python-install $(AT)$(MAKE) lint-check diff --git a/README.md b/README.md index 41367bf..ba075e8 100644 --- a/README.md +++ b/README.md @@ -174,3 +174,11 @@ make release-plan was generated. Direct publication, upload, tagging and version-bump commands are disabled in generated projects. Publication requires separate configuration and approval. The current build dependencies are not locked.

+ +

Generator source release preparation

+ +

The generator itself has a separate read-only source package workflow. +Use make release-plan, make release-prepare and make package-source +at the generator root. See docs/release-cycle.md in the generator +repository for the exact baseline, output directory and checksum checks. +This does not publish packages or modify a generated project’s version.

diff --git a/changelogs/CHANGELOG.md b/changelogs/CHANGELOG.md index eab83a4..d957045 100644 --- a/changelogs/CHANGELOG.md +++ b/changelogs/CHANGELOG.md @@ -11,6 +11,7 @@ - Migrate repository configuration to cookscodeinc - Import shared spelling dictionary - Add containerized documentation preview +- Generate reviewed Python release preparation ### πŸ› Fixed @@ -173,3 +174,6 @@ fix: update shared spelling dictionary - Merge pull request #27 from cookscodeinc/feat-011 fix: update shared spelling dictionary +- Merge pull request #29 from cookscodeinc/feat-012 + +feat: generate reviewed Python release preparation diff --git a/changelogs/releases/v0.1.0.md b/changelogs/releases/v0.1.0.md index 27540c9..9fe48cb 100644 --- a/changelogs/releases/v0.1.0.md +++ b/changelogs/releases/v0.1.0.md @@ -2,7 +2,7 @@ # Changelog: # -------------------------------------------------- -## [0.1.0] - 2026-12-01 +## [0.1.0] - 2026-12-02 ### πŸš€ Added @@ -11,6 +11,7 @@ - Migrate repository configuration to cookscodeinc - Import shared spelling dictionary - Add containerized documentation preview +- Generate reviewed Python release preparation ### πŸ› Fixed @@ -173,3 +174,6 @@ fix: update shared spelling dictionary - Merge pull request #27 from cookscodeinc/feat-011 fix: update shared spelling dictionary +- Merge pull request #29 from cookscodeinc/feat-012 + +feat: generate reviewed Python release preparation diff --git a/docs/jekyll/README.md b/docs/jekyll/README.md index 7bc3ae5..3fedf10 100644 --- a/docs/jekyll/README.md +++ b/docs/jekyll/README.md @@ -159,3 +159,12 @@ The version selectors cover package metadata and the documentation that was generated. Direct publication, upload, tagging and version-bump commands are disabled in generated projects. Publication requires separate configuration and approval. The current build dependencies are not locked. + + +## Generator source release preparation + +The generator itself has a separate read-only source package workflow. +Use `make release-plan`, `make release-prepare` and `make package-source` +at the generator root. See `docs/release-cycle.md` in the generator +repository for the exact baseline, output directory and checksum checks. +This does not publish packages or modify a generated project's version. diff --git a/docs/release-cycle.md b/docs/release-cycle.md new file mode 100644 index 0000000..a45e9f4 --- /dev/null +++ b/docs/release-cycle.md @@ -0,0 +1,23 @@ +# Generator release preparation + +The Python generator's own release is separate from releases of the +projects it generates. Its source candidate is a ZIP archive of the +generator, not an installable project package. + +On a clean numbered feature branch, provide the exact full commit of +a verified published baseline and the corresponding published version. +Set `RELEASE_BASELINE` and `PUBLISHED_VERSION`, then run +`make release-plan`. Run `make release-prepare` with `RELEASE_OUTPUT` +pointing to a new directory outside the checkout to export a proposed +version patch. The helper verifies all supported version fields without +applying changes, committing, tagging or publishing. + +Run `make package-source` with a new `RELEASE_OUTPUT` directory to +prepare the exact committed source archive. Verify `SHA256SUMS` and +retain the complete `release.json` manifest. The main-branch Release +Preparation workflow preserves this candidate with read-only repository +permissions. No GitHub Release or package registry publication is enabled. + +Legacy direct release targets at the generator root fail closed. +Generated projects retain their existing package workflows and manual +lifecycle commands. Their versions and publication approvals are separate. diff --git a/pyproject.toml b/pyproject.toml index 0b57291..2571e3c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -132,11 +132,25 @@ tag = false commit = false [[tool.bumpversion.files]] -filename = "Makefile" +filename = "pyproject.toml" +search = "\nversion = \"{current_version}\"" +replace = "\nversion = \"{new_version}\"" [[tool.bumpversion.files]] -filename = "README.md" +filename = "Makefile" +search = "VERSION := {current_version}" +replace = "VERSION := {new_version}" [[tool.bumpversion.files]] filename = "docs/cookiecutter_input.json" +search = '"version": "{current_version}"' +replace = '"version": "{new_version}"' +[[tool.bumpversion.files]] +filename = "docs/jekyll/Makefile" +search = 'VERSION = "{current_version}"' +replace = 'VERSION = "{new_version}"' +[[tool.bumpversion.files]] +filename = "docs/jekyll/_config.yml" +search = 'version: "{current_version}"' +replace = 'version: "{new_version}"' # ==================================== # Codespell Configuration: # ==================================== diff --git a/release-policy.json b/release-policy.json new file mode 100644 index 0000000..b91b1ec --- /dev/null +++ b/release-policy.json @@ -0,0 +1,25 @@ +{ + "candidate_adapter": { + "kind": "source" + }, + "required_pr_checks": [ + "tests", + "jinja2-lint", + "typecheck", + "black-format-check", + "dependency-check", + "security-audit", + "spellcheck", + "CLAAssistant" + ], + "required_push_workflows": [ + ".github/workflows/dependency-check.yml", + ".github/workflows/format-check.yml", + ".github/workflows/lint-check.yml", + ".github/workflows/security-audit.yml", + ".github/workflows/spellcheck.yml", + ".github/workflows/tests.yml", + ".github/workflows/typecheck.yml", + ".github/workflows/release-preparation.yml" + ] +} diff --git a/scripts/release_plan.py b/scripts/release_plan.py new file mode 100644 index 0000000..ee6e783 --- /dev/null +++ b/scripts/release_plan.py @@ -0,0 +1,825 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, Jared W. Cook +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Calculate a release plan without changing files, tags, branches or remotes.""" + +import argparse +import ast +import base64 +import csv +import hashlib +import io +import json +import posixpath +import re +import stat +import subprocess +import tarfile +import tomllib +import zipfile +from collections.abc import Callable +from email.parser import BytesParser +from pathlib import Path +from typing import Any + +VERSION = re.compile(r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)") +COMMIT = re.compile(r"^[a-z]+(?:\([^\n()]+\))?(!)?: .+") +BREAKING = re.compile(r"^BREAKING(?: CHANGE|-CHANGE):\s*\S", re.MULTILINE) +LEVELS = ("none", "patch", "minor", "major") + + +def parse_version(value: str) -> tuple[int, int, int]: + """Accept only stable semantic versions.""" + match = VERSION.fullmatch(value) + if not match: + raise ValueError(f"Invalid stable version: {value}") + return int(match[1]), int(match[2]), int(match[3]) + + +def severity(message: str) -> int: + """Classify a Conventional Commit; unrelated maintenance does not bump.""" + subject = message.splitlines()[0] if message else "" + match = COMMIT.fullmatch(subject) + if BREAKING.search(message) or (match and match[1]): + return 3 + if match and subject.startswith(("feat:", "feat(")): + return 2 + if match and subject.startswith(("fix:", "fix(", "perf:", "perf(")): + return 1 + return 0 + + +def bumped(version: tuple[int, int, int], level: int) -> tuple[int, int, int]: + """Apply the highest required change to the published version.""" + major, minor, patch = version + return ( + (major, minor, patch), + (major, minor, patch + 1), + (major, minor + 1, 0), + (major + 1, 0, 0), + )[level] + + +def git(root: Path, *args: str) -> str: + """Read local repository history only.""" + return subprocess.check_output(["git", "-C", str(root), *args], text=True).strip() + + +def verify_versions(root: Path, head: str, expected: str) -> dict[str, str]: + """Check known project version fields in the exact committed snapshot. + + Generator defaults in cookiecutter.json and dependency versions are + deliberately not project release versions. + """ + paths = set(git(root, "ls-tree", "-r", "--name-only", head).splitlines()) + kind = "source" + if "release-policy.json" in paths: + adapter = committed_adapter(root, head) + candidate_names(expected, adapter) + kind = str(adapter["kind"]) + verify_adapter_identity( + paths, lambda path: git(root, "show", f"{head}:{path}"), adapter + ) + return verify_version_fields( + paths, lambda path: git(root, "show", f"{head}:{path}"), expected, kind + ) + + +def verify_adapter_identity( + paths: set[str], content: Callable[[str], str], adapter: dict[str, object] +) -> None: + """Bind the configured package identity to authoritative committed metadata.""" + kind = adapter["kind"] + if kind == "python": + if "pyproject.toml" not in paths: + raise ValueError("Required package version metadata missing") + name = tomllib.loads(content("pyproject.toml")).get("project", {}).get("name") + if ( + not isinstance(name, str) + or normalized_distribution(name) != adapter["package"] + ): + raise ValueError("Python package identity mismatch") + elif kind == "wxt": + if "package.json" not in paths: + raise ValueError("Required package version metadata missing") + name = json.loads(content("package.json")).get("name") + if not isinstance(name, str) or name.lower() != adapter["package"]: + raise ValueError("Browser package identity mismatch") + if "package-lock.json" not in paths: + raise ValueError("Required package version metadata missing") + lock = json.loads(content("package-lock.json")) + if ( + lock.get("name") != name + or lock.get("packages", {}).get("", {}).get("name") != name + ): + raise ValueError("Browser lockfile identity mismatch") + elif kind == "galaxy": + if "galaxy.yml" not in paths: + raise ValueError("Required package version metadata missing") + for field, key in (("namespace", "namespace"), ("name", "collection")): + matches = re.findall( + rf"""^{field}:\s*["']?([a-z][a-z0-9_]*)["']?\s*$""", + content("galaxy.yml"), + re.MULTILINE, + ) + if matches != [adapter[key]]: + raise ValueError("Collection identity mismatch") + + +def text_version_fields( + paths: set[str], content: Callable[[str], str], kind: str +) -> dict[str, str]: + """Read plain text version declarations without executing project files.""" + values: dict[str, str] = {} + for name, pattern in ( + ("Makefile", r"""^VERSION\s*[:?]?=\s*["']?([0-9.]+)["']?\s*$"""), + ("docs/jekyll/Makefile", r"""^VERSION\s*[:?]?=\s*["']?([0-9.]+)["']?\s*$"""), + ("docs/jekyll/_config.yml", r"""^version:\s*["']?([0-9.]+)["']?\s*$"""), + ("galaxy.yml", r"""^version:\s*["']?([0-9.]+)["']?\s*$"""), + ): + if name in paths: + text = content(name) + matches = re.findall(pattern, text, re.MULTILINE) + if ( + kind == "wxt" + and name == "Makefile" + and not matches + and not re.search(r"^VERSION\s*[:?+!]?=", text, re.MULTILINE) + ): + continue + if len(matches) != 1: + raise ValueError(f"Ambiguous or missing project version in {name}") + values[f"{name}:version"] = matches[0] + return values + + +def sphinx_release(content: str) -> str: + """Read a literal Sphinx release declaration without executing configuration.""" + try: + tree = ast.parse(content) + except SyntaxError as error: + raise ValueError("Invalid Sphinx configuration syntax") from error + values: list[ast.expr | None] = [] + for node in tree.body: + if isinstance(node, ast.Assign) and any( + isinstance(target, ast.Name) and target.id == "release" + for target in node.targets + ): + values.append(node.value) + elif ( + isinstance(node, ast.AnnAssign) + and isinstance(node.target, ast.Name) + and node.target.id == "release" + ): + values.append(node.value) + if len(values) != 1 or not isinstance(values[0], ast.Constant): + raise ValueError("Ambiguous or nonliteral Sphinx release declaration") + value = values[0].value + if not isinstance(value, str): + raise ValueError("Sphinx release must be a string") + return value + + +def verify_version_fields( + paths: set[str], content: Callable[[str], str], expected: str, kind: str = "source" +) -> dict[str, str]: + """Validate version metadata using an explicit snapshot reader.""" + values: dict[str, str] = {} + + def add(label: str, value: object) -> None: + if not isinstance(value, str) or value != expected: + raise ValueError( + f"Version mismatch: {label} (expected {expected}, found {value})" + ) + values[label] = value + + required = { + "wxt": {"package.json", "package-lock.json"}, + "python": {"pyproject.toml"}, + "galaxy": {"galaxy.yml"}, + }.get(kind, set()) + if not required <= paths: + raise ValueError("Required package version metadata missing") + if "pyproject.toml" in paths: + data = tomllib.loads(content("pyproject.toml")) + add("pyproject.toml:project.version", data.get("project", {}).get("version")) + bump = data.get("tool", {}).get("bumpversion") + if bump is not None: + add( + "pyproject.toml:tool.bumpversion.current_version", + bump.get("current_version"), + ) + for name in ("package.json", "package-lock.json", "docs/cookiecutter_input.json"): + if name in paths: + data = json.loads(content(name)) + add(f"{name}:version", data.get("version")) + if name == "package-lock.json" and (kind == "wxt" or "packages" in data): + add( + f"{name}:packages.root.version", + data.get("packages", {}).get("", {}).get("version"), + ) + if kind == "wxt" and "manifest.json" in paths: + add( + "manifest.json:version", json.loads(content("manifest.json")).get("version") + ) + if "Cargo.toml" in paths: + add( + "Cargo.toml:package.version", + tomllib.loads(content("Cargo.toml")).get("package", {}).get("version"), + ) + for label, value in text_version_fields(paths, content, kind).items(): + add(label, value) + if kind == "python" and "docs/sphinx/conf.py" in paths: + add( + "docs/sphinx/conf.py:release", + sphinx_release(content("docs/sphinx/conf.py")), + ) + if not values: + raise ValueError("No supported project version fields found") + return values + + +def release_plan( + root: Path, baseline: str, published: str, current: str, target: str = "HEAD" +) -> dict[str, object]: + """Require an explicit verified baseline; never infer publication from tags.""" + if not re.fullmatch(r"[0-9a-f]{40}", baseline): + raise ValueError("Baseline must be a full commit ID") + if git(root, "rev-parse", "--is-shallow-repository") != "false": + raise ValueError("Complete Git history is required") + base = git(root, "rev-parse", "--verify", baseline + "^{commit}") + head = git(root, "rev-parse", "--verify", "--end-of-options", target + "^{commit}") + if ( + subprocess.run( + ["git", "-C", str(root), "merge-base", "--is-ancestor", base, head], + check=False, + ).returncode + != 0 + ): + raise ValueError("Published baseline is not an ancestor of the target") + old = parse_version(published) + existing = parse_version(current) + if existing < old: + raise ValueError("Source version is older than published version") + version_files = verify_versions(root, head, current) + records = git( + root, "log", "--no-merges", "--format=%H%x00%B%x00", f"{base}..{head}" + ) + fields = records.split("\x00") if records else [] + changes = [] + level = 0 + for index in range(0, len(fields) - 1, 2): + commit = fields[index].strip() + message = fields[index + 1] + impact = severity(message) + level = max(level, impact) + changes.append( + { + "commit": commit, + "subject": message.splitlines()[0] if message else "", + "impact": LEVELS[impact], + } + ) + required = bumped(old, level) + proposed = max(required, existing) + return { + "baseline_commit": base, + "target_commit": head, + "published_version": published, + "current_version": current, + "impact": LEVELS[level], + "proposed_version": ".".join(map(str, proposed)), + "version_change_required": proposed != existing, + "release_candidate": proposed > old, + "changes": changes, + "version_files": version_files, + "nonconventional_commits": [ + change["commit"] + for change in changes + if not COMMIT.fullmatch(change["subject"]) + ], + } + + +def normalized_distribution(name: str) -> str: + """Normalize a Python distribution name for its archive filename.""" + return re.sub(r"[-_.]+", "_", name).lower() + + +def package_identity(adapter: dict[str, object]) -> str: + """Accept only explicitly supported package identities.""" + kind = adapter.get("kind") + if kind == "python" and set(adapter) == {"kind", "package"}: + name = adapter["package"] + if isinstance(name, str) and re.fullmatch(r"[a-z0-9]+(?:_[a-z0-9]+)*", name): + return name + if kind == "galaxy" and set(adapter) == {"kind", "namespace", "collection"}: + namespace, collection = adapter["namespace"], adapter["collection"] + if ( + isinstance(namespace, str) + and isinstance(collection, str) + and re.fullmatch(r"[a-z][a-z0-9_]*", namespace) + and re.fullmatch(r"[a-z][a-z0-9_]*", collection) + ): + return f"{namespace}-{collection}" + raise ValueError("Invalid package identity policy") + + +def candidate_names(version: str, adapter: dict[str, object]) -> list[str]: + """Resolve only explicitly supported, policy-approved package sets.""" + parse_version(version) + kind = adapter.get("kind") + if adapter == {"kind": "source"}: + return [f"source-v{version}.zip"] + if kind == "python": + name = package_identity(adapter) + return [f"{name}-{version}-py3-none-any.whl", f"{name}-{version}.tar.gz"] + if kind == "galaxy": + return [f"{package_identity(adapter)}-{version}.tar.gz"] + if set(adapter) != {"kind", "package", "targets"} or kind != "wxt": + raise ValueError("Unsupported package adapter") + package, targets = adapter["package"], adapter["targets"] + if ( + not isinstance(package, str) + or not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", package) + or not isinstance(targets, list) + or targets not in (["chrome", "sources"], ["chrome", "firefox", "sources"]) + ): + raise ValueError("Invalid browser package policy") + return [f"{package}-{version}-{target}.zip" for target in targets] + + +def unsafe_archive_path(name: str) -> bool: + """Reject traversal, credential paths and platform-specific absolute paths.""" + parts = name.rstrip("/").split("/") + return ( + not name + or name.startswith("/") + or chr(92) in name + or any( + part in ("", ".", "..", ".git", ".venv", "node_modules") for part in parts + ) + or any(part.startswith(".env") for part in parts) + or bool(re.match(r"^[A-Za-z]:", name)) + or Path(name).suffix.lower() in (".pem", ".key", ".p12", ".pfx") + ) + + +def verify_zip_paths(archive: zipfile.ZipFile) -> None: + """Allow ordinary files and directories, never links or special files.""" + for entry in archive.infolist(): + mode = (entry.external_attr >> 16) & 0o170000 + if unsafe_archive_path(entry.filename) or mode not in (0, 0o100000, 0o040000): + raise ValueError("Unsafe package archive entry") + + +def verify_python_metadata(data: bytes, package: str, version: str) -> None: + """Check the embedded distribution identity and version.""" + metadata = BytesParser().parsebytes(data) + names = metadata.get_all("Name", []) + versions = metadata.get_all("Version", []) + if ( + len(names) != 1 + or normalized_distribution(str(names[0])) != package + or versions != [version] + ): + raise ValueError("Python package metadata mismatch") + + +def verify_wheel_record(archive: zipfile.ZipFile, record: str) -> None: + """Verify the wheel's complete file inventory and embedded SHA-256 hashes.""" + expected = {entry.filename for entry in archive.infolist() if not entry.is_dir()} + seen: set[str] = set() + rows = csv.reader(io.StringIO(archive.read(record).decode("utf-8"), newline="")) + for row in rows: + if len(row) != 3 or row[0] in seen or row[0] not in expected: + raise ValueError("Invalid wheel RECORD inventory") + name, digest, size = row + seen.add(name) + if name == record: + if digest or size: + raise ValueError("Invalid wheel RECORD self entry") + continue + data = archive.read(name) + encoded = ( + base64.urlsafe_b64encode(hashlib.sha256(data).digest()).decode().rstrip("=") + ) + if digest != f"sha256={encoded}" or size != str(len(data)): + raise ValueError("Wheel RECORD checksum or size mismatch") + if seen != expected: + raise ValueError("Incomplete wheel RECORD inventory") + + +def verify_python_wheel(archive: zipfile.ZipFile, package: str, version: str) -> None: + """Validate the supported pure-Python wheel and its metadata.""" + verify_zip_paths(archive) + prefix = f"{package}-{version}.dist-info" + if { + name.split("/")[0] + for name in archive.namelist() + if name.split("/")[0].endswith(".dist-info") + } != {prefix}: + raise ValueError("Wheel metadata directory mismatch") + verify_python_metadata(archive.read(f"{prefix}/METADATA"), package, version) + wheel = BytesParser().parsebytes(archive.read(f"{prefix}/WHEEL")) + if wheel.get_all("Tag", []) != ["py3-none-any"] or wheel.get_all( + "Root-Is-Purelib", [] + ) != ["true"]: + raise ValueError("Unsupported wheel platform") + verify_wheel_record(archive, f"{prefix}/RECORD") + + +def tar_members(archive: tarfile.TarFile) -> dict[str, tarfile.TarInfo]: + """Inspect tar archives without extracting any paths.""" + members: dict[str, tarfile.TarInfo] = {} + for entry in archive.getmembers(): + if unsafe_archive_path(entry.name) or not (entry.isfile() or entry.isdir()): + raise ValueError("Unsafe package archive entry") + if entry.name in members: + raise ValueError("Duplicate archive entries") + members[entry.name] = entry + return members + + +def tar_read(archive: tarfile.TarFile, name: str) -> bytes: + """Read a regular member only, never follow an archive link.""" + entry = archive.getmember(name) + if not entry.isfile(): + raise ValueError("Expected a regular archive member") + stream = archive.extractfile(entry) + if stream is None: + raise ValueError("Missing archive member") + with stream: + data = stream.read() + if len(data) != entry.size: + raise ValueError("Archive member size mismatch") + return data + + +def verify_python_sdist(archive: tarfile.TarFile, package: str, version: str) -> None: + """Verify the expected source distribution root and metadata.""" + members = tar_members(archive) + prefix = f"{package}-{version}" + if {name.split("/")[0] for name in members} != {prefix}: + raise ValueError("Python source distribution root mismatch") + verify_python_metadata(tar_read(archive, f"{prefix}/PKG-INFO"), package, version) + + +def verify_collection_files( + archive: tarfile.TarFile, files: list[Any], members: dict[str, tarfile.TarInfo] +) -> None: + """Check every collection manifest entry against the actual tar member.""" + expected = set(members) - {"MANIFEST.json", "FILES.json"} + seen: set[str] = set() + roots = 0 + for item in files: + name = item["name"] + if name == "." and item["ftype"] == "dir": + roots += 1 + continue + if name in seen or name not in expected: + raise ValueError("Collection file manifest inventory mismatch") + seen.add(name) + entry = members[name] + if entry.isdir() and item["ftype"] == "dir": + continue + if not entry.isfile() or item["ftype"] != "file": + raise ValueError("Collection file manifest type mismatch") + if ( + item["chksum_type"] != "sha256" + or hashlib.sha256(tar_read(archive, name)).hexdigest() + != item["chksum_sha256"] + ): + raise ValueError("Collection member checksum mismatch") + if seen != expected or roots != 1: + raise ValueError("Collection file manifest inventory mismatch") + + +def verify_galaxy_archive( + archive: tarfile.TarFile, adapter: dict[str, object], version: str +) -> None: + """Validate collection identity, manifest coverage and file checksums.""" + members = tar_members(archive) + manifest = json.loads(tar_read(archive, "MANIFEST.json")) + info = manifest["collection_info"] + if (info["namespace"], info["name"], info["version"]) != ( + adapter["namespace"], + adapter["collection"], + version, + ): + raise ValueError("Collection metadata mismatch") + data = tar_read(archive, "FILES.json") + reference = manifest["file_manifest_file"] + if ( + reference["name"] != "FILES.json" + or reference["ftype"] != "file" + or reference["chksum_type"] != "sha256" + or reference["chksum_sha256"] != hashlib.sha256(data).hexdigest() + ): + raise ValueError("Collection file manifest checksum mismatch") + verify_collection_files(archive, json.loads(data)["files"], members) + + +def verify_browser_archive(archive: zipfile.ZipFile, name: str, version: str) -> None: + """Reject unsafe archive entries and mismatched browser metadata.""" + try: + verify_zip_paths(archive) + except ValueError as error: + raise ValueError("Unsafe browser archive entry") from error + if name.endswith("-sources.zip"): + metadata = json.loads(archive.read("package.json")) + if metadata.get("version") != version: + raise ValueError("Browser source package version mismatch") + return + metadata = json.loads(archive.read("manifest.json")) + if metadata.get("version") != version: + raise ValueError("Browser archive version mismatch") + if name.endswith("-chrome.zip") and metadata.get("manifest_version") != 3: + raise ValueError("Chrome manifest version mismatch") + if name.endswith("-firefox.zip") and not metadata.get( + "browser_specific_settings", {} + ).get("gecko", {}).get("id"): + raise ValueError("Firefox extension identity missing") + + +def safe_source_link(name: str, link: str, entries: dict[str, str]) -> None: + """Accept links to committed regular files or entirely regular subtrees. + + Resolve only leading parent components; reject traversal through another + link, dangling links, cycles and links to directories containing links. + """ + parts = link.split("/") + if ( + not link + or posixpath.isabs(link) + or "\\" in link + or any(ord(char) < 32 for char in link) + or any(part in ("", ".") for part in parts) + ): + raise ValueError(f"Unsafe release symlink: {name}") + while parts and parts[0] == "..": + parts.pop(0) + if not parts or ".." in parts: + raise ValueError(f"Unsafe release symlink: {name}") + destination = posixpath.normpath(posixpath.join(posixpath.dirname(name), link)) + if destination in (".", "..") or destination.startswith("../"): + raise ValueError(f"Unsafe release symlink: {name}") + regular = {"100644", "100755"} + if entries.get(destination) in regular: + return + descendants = [ + mode for path, mode in entries.items() if path.startswith(destination + "/") + ] + if ( + entries.get(destination, "040000") != "040000" + or not any(mode in regular for mode in descendants) + or any(mode not in regular | {"040000"} for mode in descendants) + ): + raise ValueError(f"Unsafe release symlink: {name}") + + +def verify_source_zip(archive: zipfile.ZipFile, commit: str) -> None: + """Verify the actual archived paths and link targets, not just the tree.""" + if archive.comment != commit.encode("ascii"): + raise ValueError("Archive commit provenance mismatch") + entries: dict[str, str] = {} + links: dict[str, str] = {} + for info in archive.infolist(): + name = info.filename.rstrip("/") + if ( + not name + or posixpath.isabs(name) + or posixpath.normpath(name) != name + or name in (".", "..") + or name.startswith("../") + or "\\" in name + or name in entries + ): + raise ValueError("Unsafe source archive path") + kind = stat.S_IFMT(info.external_attr >> 16) + if kind == stat.S_IFLNK and not info.is_dir(): + entries[name] = "120000" + links[name] = archive.read(info).decode("utf-8") + elif info.is_dir() and kind in (0, stat.S_IFDIR): + entries[name] = "040000" + elif not info.is_dir() and kind in (0, stat.S_IFREG): + entries[name] = "100644" + else: + raise ValueError("Unsupported source archive entry") + for name in entries: + parent = posixpath.dirname(name) + while parent: + if entries.get(parent, "040000") != "040000": + raise ValueError("Unsafe source archive parent") + parent = posixpath.dirname(parent) + for name, link in links.items(): + safe_source_link(name, link, entries) + + +def verify_candidate_archive( + path: Path, commit: str, version: str, adapter: dict[str, object] +) -> None: + """Validate archive integrity and adapter-specific provenance.""" + kind = adapter["kind"] + if kind == "galaxy": + with tarfile.open(path, "r:gz") as archive: + verify_galaxy_archive(archive, adapter, version) + return + if kind == "python" and path.name.endswith(".tar.gz"): + with tarfile.open(path, "r:gz") as archive: + verify_python_sdist(archive, package_identity(adapter), version) + return + with zipfile.ZipFile(path) as archive: + names = archive.namelist() + if len(names) != len(set(names)): + raise ValueError("Duplicate archive entries") + if archive.testzip() is not None: + raise ValueError("Archive CRC verification failed") + if kind == "source": + verify_source_zip(archive, commit) + elif kind == "python": + verify_python_wheel(archive, package_identity(adapter), version) + else: + verify_browser_archive(archive, path.name, version) + + +def candidate_manifest( + directory: Path, commit: str, version: str, adapter: dict[str, object] +) -> dict[str, object]: + """Verify the exact allowed assets and calculate their complete manifest.""" + if not re.fullmatch(r"[0-9a-f]{40}", commit): + raise ValueError("Invalid candidate commit") + assets = [] + for name in candidate_names(version, adapter): + path = directory / name + if not path.is_file() or path.is_symlink(): + raise ValueError(f"Candidate file missing or unsafe: {name}") + verify_candidate_archive(path, commit, version, adapter) + with path.open("rb") as stream: + digest = hashlib.file_digest(stream, "sha256").hexdigest() + assets.append({"name": name, "sha256": digest, "bytes": path.stat().st_size}) + return { + "schema": 1, + "commit": commit, + "version": version, + "adapter": adapter, + "assets": assets, + } + + +def manifest_bytes(manifest: dict[str, object]) -> bytes: + """Use a single deterministic representation for the approval checksum.""" + return (json.dumps(manifest, indent=2, sort_keys=True) + "\n").encode("utf-8") + + +def manifest_checksums( + directory: Path, version: str, adapter: dict[str, object] +) -> str: + """Build the conventional checksum file from the exact expected assets.""" + lines = [] + for name in candidate_names(version, adapter): + with (directory / name).open("rb") as stream: + lines.append( + f"{hashlib.file_digest(stream, 'sha256').hexdigest()} {name}\n" + ) + return "".join(lines) + + +def seal_candidate( + directory: Path, commit: str, version: str, adapter: dict[str, object] +) -> dict[str, object]: + """Seal freshly packaged assets without overwriting a previous candidate.""" + if {p.name for p in directory.iterdir()} != set(candidate_names(version, adapter)): + raise ValueError("Unexpected candidate files") + manifest = candidate_manifest(directory, commit, version, adapter) + with (directory / "release.json").open("xb") as stream: + stream.write(manifest_bytes(manifest)) + with (directory / "SHA256SUMS").open("x") as stream: + stream.write(manifest_checksums(directory, version, adapter)) + return manifest + + +def package_source( + root: Path, target: str, version: str, output: Path +) -> dict[str, object]: + """Create a checksummed source candidate from the exact committed tree.""" + parse_version(version) + head = git(root, "rev-parse", "--verify", "--end-of-options", target + "^{commit}") + if git(root, "ls-tree", head, "--", "release-policy.json"): + if committed_adapter(root, head) != {"kind": "source"}: + raise ValueError("Source builder requires the source adapter") + verify_versions(root, head, version) + # Package only tracked files. Reject unsafe paths and credential-file names + # rather than silently dropping them from a release. + entries = { + name: metadata.split()[0] + for metadata, name in ( + entry.split("\t", 1) + for entry in git(root, "ls-tree", "-rz", head).split("\x00") + if entry + ) + } + for name, mode in entries.items(): + path = Path(name) + if ( + mode == "160000" + or path.is_absolute() + or ".." in path.parts + or any(part == ".git" or part.startswith(".env") for part in path.parts) + or path.suffix.lower() in (".pem", ".key", ".p12", ".pfx") + ): + raise ValueError(f"Unsupported or unsafe release path: {name}") + if mode == "120000": + link = subprocess.check_output( + ["git", "-C", str(root), "show", f"{head}:{name}"], text=True + ) + safe_source_link(name, link, entries) + if output.exists(): + raise ValueError("Release output must not already exist") + archive = subprocess.check_output( + ["git", "-C", str(root), "archive", "--format=zip", head] + ) + name = f"source-v{version}.zip" + output.mkdir(parents=True, exist_ok=False) + path = output / name + path.write_bytes(archive) + return seal_candidate(output, head, version, {"kind": "source"}) + + +def committed_adapter(root: Path, head: str) -> dict[str, object]: + """Read the explicitly committed adapter rather than accepting a CLI override.""" + policy = json.loads(git(root, "show", f"{head}:release-policy.json")) + adapter = policy["candidate_adapter"] + if not isinstance(adapter, dict): + raise ValueError("Invalid package adapter policy") + return dict(adapter) + + +def seal_built_packages( + root: Path, target: str, version: str, directory: Path +) -> dict[str, object]: + """Seal package outputs from the exact clean tracked build checkout.""" + head = git(root, "rev-parse", "--verify", "--end-of-options", target + "^{commit}") + if head != git(root, "rev-parse", "HEAD"): + raise ValueError("Package checkout does not match target commit") + if git(root, "status", "--porcelain", "--untracked-files=no"): + raise ValueError("Tracked files changed during package build") + adapter = committed_adapter(root, head) + if adapter.get("kind") == "source": + raise ValueError("Source packages must use the Git archive builder") + verify_versions(root, head, version) + return seal_candidate(directory, head, version, adapter) + + +def main() -> None: + """Print a reviewable JSON plan; never publish or commit.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--baseline") + parser.add_argument("--published-version") + parser.add_argument("--current-version", required=True) + parser.add_argument("--target", default="HEAD") + outputs = parser.add_mutually_exclusive_group() + outputs.add_argument("--package-dir", type=Path) + outputs.add_argument("--seal-dir", type=Path) + args = parser.parse_args() + try: + plan: dict[str, object] | dict[str, str] + if args.seal_dir is not None: + if args.baseline or args.published_version: + parser.error( + "Package sealing and release planning are separate operations" + ) + plan = seal_built_packages( + Path.cwd(), args.target, args.current_version, args.seal_dir + ) + elif args.package_dir is not None: + if args.baseline or args.published_version: + parser.error( + "Package creation and release planning are separate operations" + ) + plan = package_source( + Path.cwd(), args.target, args.current_version, args.package_dir + ) + else: + if not args.baseline or not args.published_version: + parser.error("Planning requires baseline and published version") + plan = release_plan( + Path.cwd(), + args.baseline, + args.published_version, + args.current_version, + args.target, + ) + except ( + ValueError, + KeyError, + OSError, + tarfile.TarError, + zipfile.BadZipFile, + subprocess.CalledProcessError, + ) as error: + parser.error(str(error)) + print(json.dumps(plan, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/scripts/release_prepare.py b/scripts/release_prepare.py new file mode 100644 index 0000000..20fd551 --- /dev/null +++ b/scripts/release_prepare.py @@ -0,0 +1,187 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, Jared W. Cook +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Prepare a reviewed version patch without modifying the repository.""" + +import argparse +import difflib +import json +import subprocess +import sys +import tempfile +import tomllib +from pathlib import Path +from typing import Any + +from release_plan import ( + committed_adapter, + git, + parse_version, + release_plan, + verify_version_fields, +) + + +def source(root: Path, head: str, path: str) -> str: + """Read exact committed regular file bytes, retaining final newlines.""" + entry = git(root, "ls-tree", head, "--", path) + if not entry.startswith(("100644 ", "100755 ")): + raise ValueError(f"Not a regular tracked file: {path}") + return subprocess.check_output( + ["git", "-C", str(root), "show", f"{head}:{path}"], text=True + ) + + +def prepared_patch(root: Path, plan: dict[str, Any], directory: Path) -> str: + """Run the declared bump tool in an isolated directory and verify output.""" + head = plan["target_commit"] + old = plan["current_version"] + new = plan["proposed_version"] + if not plan["version_change_required"]: + return "" + if parse_version(new) <= parse_version(old): + raise ValueError("Version must increase") + config = tomllib.loads(source(root, head, "pyproject.toml"))["tool"]["bumpversion"] + if config["current_version"] != old or config.get("commit") or config.get("tag"): + raise ValueError("Unsafe or inconsistent bump configuration") + allowed = {field.split(":", 1)[0] for field in plan["version_files"]} + files = config["files"] + names = [item["filename"] for item in files] + if ( + set(names) != allowed + or len(set(names)) != len(names) + or any("glob" in item for item in files) + ): + raise ValueError( + "Bump configuration must cover exactly the supported version files" + ) + before = {name: source(root, head, name) for name in sorted(allowed)} + for name, text in before.items(): + path = directory / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + subprocess.run( + [ + sys.executable, + "-m", + "bumpversion", + "bump", + "--config-file", + "pyproject.toml", + "--no-commit", + "--no-tag", + "--no-push-tag", + "--no-ignore-missing-files", + "--no-ignore-missing-version", + "--new-version", + new, + "patch", + ], + cwd=directory, + check=True, + stdin=subprocess.DEVNULL, + ) + after = {name: (directory / name).read_text() for name in before} + kind = "source" + if git(root, "ls-tree", head, "--", "release-policy.json"): + kind = str(committed_adapter(root, head)["kind"]) + verify_version_fields(allowed, after.__getitem__, new, kind) + # The configured exact search/replace is the only permitted change. + for item in files: + name = item["filename"] + search = item["search"].format(current_version=old, new_version=new) + replacement = item["replace"].format(current_version=old, new_version=new) + if before[name].count(search) != 1: + raise ValueError(f"Ambiguous version selector: {name}") + expected = before[name].replace(search, replacement, 1) + if name == "pyproject.toml": + marker = f'current_version = "{old}"' + if expected.count(marker) != 1: + raise ValueError("Ambiguous bump configuration version") + expected = expected.replace(marker, f'current_version = "{new}"', 1) + if after[name] != expected: + raise ValueError(f"Unexpected bump tool modification: {name}") + return "".join( + "".join( + difflib.unified_diff( + before[name].splitlines(keepends=True), + after[name].splitlines(keepends=True), + fromfile=f"a/{name}", + tofile=f"b/{name}", + ) + ) + for name in before + ) + + +def prepare( + root: Path, baseline: str, published: str, current: str, output: Path +) -> dict[str, Any]: + """Export a deterministic release plan and local version patch for review.""" + if output.resolve().is_relative_to(root.resolve()): + raise ValueError("Preparation output must be outside the repository") + if output.exists(): + raise ValueError("Preparation output already exists") + if git(root, "status", "--porcelain"): + raise ValueError("A clean feature checkout is required") + branch = git(root, "branch", "--show-current") + if not branch.startswith("feat-") or not branch[5:].isdigit(): + raise ValueError("Prepare versions on a numbered feature branch") + plan: dict[str, Any] = release_plan(root, baseline, published, current) + if not plan["release_candidate"]: + raise ValueError("No new release candidate is required") + with tempfile.TemporaryDirectory() as tmp: + patch = prepared_patch(root, plan, Path(tmp)) + if patch: + subprocess.run( + ["git", "-C", str(root), "apply", "--check", "-"], + input=patch, + text=True, + check=True, + ) + if git(root, "status", "--porcelain"): + raise ValueError("Repository changed during version preparation") + output.mkdir(parents=True, exist_ok=False) + (output / "plan.json").write_text(json.dumps(plan, indent=2) + "\n") + (output / "version.patch").write_text(patch) + changes = plan["changes"] + lines = [ + f"# Release {plan['proposed_version']}", + "", + f"Published baseline: `{plan['baseline_commit']}`", + "", + f"Prepared source: `{plan['target_commit']}`", + "", + "## Changes", + "", + ] + lines.extend(f"- {item['subject']} (`{item['commit'][:12]}`)" for item in changes) + (output / "release-notes.md").write_text("\n".join(lines) + "\n") + return plan + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--baseline", required=True) + parser.add_argument("--published-version", required=True) + parser.add_argument("--current-version", required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + try: + print( + json.dumps( + prepare( + Path.cwd(), + args.baseline, + args.published_version, + args.current_version, + args.output, + ), + indent=2, + ) + ) + except (ValueError, KeyError, subprocess.CalledProcessError) as error: + parser.error(str(error)) + + +if __name__ == "__main__": + main() diff --git a/scripts/release_publish.py b/scripts/release_publish.py new file mode 100644 index 0000000..b394507 --- /dev/null +++ b/scripts/release_publish.py @@ -0,0 +1,426 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, Jared W. Cook +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Publish only an explicitly approved, verified production package candidate.""" + +import argparse +import hashlib +import json +import os +import re +import subprocess +import tempfile +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from release_plan import ( + candidate_manifest, + candidate_names, + git, + manifest_bytes, + manifest_checksums, + parse_version, + verify_versions, +) + + +def require(condition: bool, message: str) -> None: + """Fail closed on an unexpected release state.""" + if not condition: + raise ValueError(message) + + +def command(*args: str) -> str: + return subprocess.check_output(args, text=True, stdin=subprocess.DEVNULL).strip() + + +def api(endpoint: str) -> Any: + return json.loads(command("gh", "api", "--method", "GET", endpoint)) + + +def pages(endpoint: str, key: str = "") -> list[dict[str, Any]]: + """Use successful paginated reads; do not mistake API errors for absence.""" + result: list[dict[str, Any]] = [] + for page in range(1, 101): + separator = "&" if "?" in endpoint else "?" + data = api(f"{endpoint}{separator}per_page=100&page={page}") + records = data[key] if key else data + require(isinstance(records, list), "Invalid GitHub listing") + result.extend(records) + if len(records) < 100: + return result + raise ValueError("GitHub listing exceeded safety limit") + + +def sha256(path: Path) -> str: + with path.open("rb") as stream: + return hashlib.file_digest(stream, "sha256").hexdigest() + + +def verify_main(root: Path, repo: str, commit: str) -> None: + require( + git(root, "rev-parse", "HEAD") == commit, "Checkout does not match approval" + ) + require( + api(f"repos/{repo}/git/ref/heads/main")["object"]["sha"] == commit, + "Main moved; a new release approval is required", + ) + + +def verify_ci(root: Path, repo: str, commit: str) -> int: + """Require the merged production PR, CLA and successful exact-main CI.""" + policy = json.loads(git(root, "show", f"{commit}:release-policy.json")) + checks = set(policy["required_pr_checks"]) + workflows = set(policy["required_push_workflows"]) + require( + "CLAAssistant" in checks and bool(workflows), "Release CI policy is incomplete" + ) + pulls = [ + item + for item in pages(f"repos/{repo}/commits/{commit}/pulls") + if item["merge_commit_sha"] == commit + and item["merged_at"] + and item["base"]["ref"] == "main" + and item["head"]["ref"] == "develop" + and item["base"]["repo"]["full_name"] == repo + and item["head"]["repo"]["full_name"] == repo + ] + require(len(pulls) == 1, "No unique approved production promotion PR") + number = pulls[0]["number"] + pr = json.loads( + command( + "gh", + "pr", + "view", + str(number), + "--repo", + repo, + "--json", + "state,mergeCommit,headRefOid,statusCheckRollup", + ) + ) + require( + pr["state"] == "MERGED" + and pr["mergeCommit"]["oid"] == commit + and pr["headRefOid"] == pulls[0]["head"]["sha"], + "Production PR does not match the approved commit", + ) + rollup = pr["statusCheckRollup"] + require( + checks <= {item["name"] for item in rollup}, "Required PR checks are missing" + ) + require( + all( + item["status"] == "COMPLETED" and item["conclusion"] == "SUCCESS" + for item in rollup + ), + "Production PR checks have not all passed", + ) + runs = pages( + f"repos/{repo}/actions/runs?branch=main&event=push&head_sha={commit}", + "workflow_runs", + ) + latest: dict[str, dict[str, Any]] = {} + for run in sorted(runs, key=lambda item: item["id"], reverse=True): + if ( + run["head_sha"] == commit + and run["head_branch"] == "main" + and run["event"] == "push" + and run["repository"]["full_name"] == repo + ): + latest.setdefault(run["path"], run) + require(workflows <= latest.keys(), "Required production workflows are missing") + require( + all( + latest[path]["status"] == "completed" + and latest[path]["conclusion"] == "success" + for path in workflows + ), + "Required production workflows have not all passed", + ) + return int(number) + + +def download_candidate(repo: str, commit: str, run_id: str, destination: Path) -> None: + run = api(f"repos/{repo}/actions/runs/{run_id}") + require( + run["head_sha"] == commit + and run["head_branch"] == "main" + and run["repository"]["full_name"] == repo + and run["head_repository"]["full_name"] == repo + and run["path"] == ".github/workflows/release-preparation.yml" + and run["event"] in ("push", "workflow_dispatch") + and run["status"] == "completed" + and run["conclusion"] == "success", + "Artifact run is not a successful exact-main release preparation", + ) + name = f"release-candidate-{commit}" + artifacts = pages(f"repos/{repo}/actions/runs/{run_id}/artifacts", "artifacts") + matches = [item for item in artifacts if item["name"] == name] + require( + len(matches) == 1 and not matches[0]["expired"], + "Candidate artifact unavailable", + ) + command( + "gh", + "run", + "download", + run_id, + "--repo", + repo, + "--name", + name, + "--dir", + str(destination), + ) + + +def release_adapter(root: Path, commit: str) -> dict[str, object]: + """Read the package allowlist from the exact approved production commit.""" + policy = json.loads(git(root, "show", f"{commit}:release-policy.json")) + adapter = policy["candidate_adapter"] + require(isinstance(adapter, dict), "Invalid package adapter policy") + return dict(adapter) + + +def verify_candidate( + directory: Path, + commit: str, + version: str, + digest: str, + adapter: dict[str, object], +) -> list[Path]: + names = candidate_names(version, adapter) + files = [directory / item for item in (*names, "SHA256SUMS", "release.json")] + require( + all(p.is_file() and not p.is_symlink() for p in files), + "Candidate files missing", + ) + require( + {p.name for p in directory.iterdir()} + <= {*names, "SHA256SUMS", "release.json", "plan.json"}, + "Unexpected candidate files", + ) + plan = directory / "plan.json" + require( + not plan.is_symlink() and (not plan.exists() or plan.is_file()), + "Unexpected candidate plan", + ) + require(sha256(files[-1]) == digest, "Candidate manifest checksum mismatch") + expected = candidate_manifest(directory, commit, version, adapter) + require( + files[-1].read_bytes() == manifest_bytes(expected), + "Candidate manifest differs from assets or provenance", + ) + require( + files[-2].read_text() == manifest_checksums(directory, version, adapter), + "Candidate checksum manifest mismatch", + ) + return files + + +def existing_release(repo: str, tag: str) -> dict[str, Any] | None: + matches = [ + item for item in pages(f"repos/{repo}/releases") if item["tag_name"] == tag + ] + require(len(matches) <= 1, "Multiple releases for the same tag") + return matches[0] if matches else None + + +def tag_commit(repo: str, tag: str) -> str | None: + refs = pages(f"repos/{repo}/git/matching-refs/tags/{tag}") + exact = [item["object"] for item in refs if item["ref"] == f"refs/tags/{tag}"] + require(len(exact) <= 1, "Multiple exact tag refs") + if not exact: + return None + obj = exact[0] + for _ in range(8): + if obj["type"] == "commit": + return str(obj["sha"]) + require(obj["type"] == "tag", "Tag does not resolve to a commit") + obj = api(f"repos/{repo}/git/tags/{obj['sha']}")["object"] + raise ValueError("Tag chain is too deep") + + +def verify_assets( + repo: str, record: dict[str, Any], files: list[Path], destination: Path +) -> None: + assets = record["assets"] + require( + len(assets) == len(files) + and {a["name"] for a in assets} == {p.name for p in files} + and all(a["state"] == "uploaded" for a in assets), + "Release asset set does not match the approved candidate", + ) + destination.mkdir() + by_name = {asset["name"]: asset for asset in assets} + for path in files: + asset_id = int(by_name[path.name]["id"]) + received = destination / path.name + with received.open("xb") as stream: + subprocess.run( + [ + "gh", + "api", + "--method", + "GET", + "-H", + "Accept: application/octet-stream", + f"repos/{repo}/releases/assets/{asset_id}", + ], + stdout=stream, + stdin=subprocess.DEVNULL, + check=True, + ) + require(sha256(received) == sha256(path), f"Release asset differs: {path.name}") + + +@dataclass(frozen=True) +class ReleaseRequest: + """Exact release inputs approved by the operator.""" + + repo: str + commit: str + version: str + run_id: str + digest: str + + +def publish( + root: Path, request: ReleaseRequest, directory: Path, *, write: bool +) -> str: + """Verify a release, or create a draft and publish it only after verification.""" + repo, commit, version, run_id, digest = ( + request.repo, + request.commit, + request.version, + request.run_id, + request.digest, + ) + parse_version(version) + require(bool(re.fullmatch(r"[0-9a-f]{40}", commit)), "Invalid commit ID") + require( + bool(re.fullmatch(r"[0-9a-f]{64}", digest)), + "Invalid candidate manifest checksum", + ) + require(bool(re.fullmatch(r"[1-9][0-9]*", run_id)), "Invalid artifact run ID") + require( + bool(re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repo)), + "Invalid repository", + ) + verify_main(root, repo, commit) + verify_versions(root, commit, version) + pr = verify_ci(root, repo, commit) + candidate = directory / "candidate" + download_candidate(repo, commit, run_id, candidate) + files = verify_candidate( + candidate, commit, version, digest, release_adapter(root, commit) + ) + tag = f"v{version}" + record = existing_release(repo, tag) + target = tag_commit(repo, tag) + require( + target is None or target == commit, "Existing tag points to a different commit" + ) + if record is not None: + require( + not record["draft"] and not record["prerelease"] and target == commit, + "Existing draft or release requires manual reconciliation", + ) + verify_assets(repo, record, files, directory / "existing") + return "Existing release matches the approved candidate; no changes" + if not write: + return f"Verified release candidate from production PR #{pr}; no changes" + verify_main(root, repo, commit) + require(existing_release(repo, tag) is None, "Release appeared during verification") + require(tag_commit(repo, tag) == target, "Tag changed during verification") + notes = directory / "notes.md" + notes.write_text( + f"Source commit: `{commit}`\n\nCandidate manifest SHA-256: `{digest}`\n\n" + f"Production PR: #{pr}\n\n[Full source](" + f"https://github.com/{repo}/tree/{commit})\n" + ) + command( + "gh", + "release", + "create", + tag, + *(str(path) for path in files), + "--repo", + repo, + "--draft", + "--target", + commit, + "--title", + tag, + "--notes-file", + str(notes), + ) + record = existing_release(repo, tag) + require( + record is not None and record["draft"] and not record["prerelease"], + "Expected a new draft release", + ) + assert record is not None + require( + record["target_commitish"] == commit or tag_commit(repo, tag) == commit, + "Draft target does not match approved commit", + ) + verify_assets(repo, record, files, directory / "draft") + verify_main(root, repo, commit) + require(tag_commit(repo, tag) in (None, commit), "Tag changed before publication") + # No retries or overwrites if a write is ambiguous. Inspect the draft first. + command("gh", "release", "edit", tag, "--repo", repo, "--draft=false") + record = existing_release(repo, tag) + require( + record is not None + and not record["draft"] + and not record["prerelease"] + and tag_commit(repo, tag) == commit, + "Publication state requires reconciliation", + ) + assert record is not None + verify_assets(repo, record, files, directory / "published") + return f"Published and verified {tag}" + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--version", required=True) + parser.add_argument("--commit", required=True) + parser.add_argument("--artifact-run", required=True) + parser.add_argument("--candidate-sha256", required=True) + parser.add_argument("--publish", action="store_true") + args = parser.parse_args() + require(os.environ.get("GITHUB_REF") == "refs/heads/main", "Only main may release") + require( + os.environ.get("GITHUB_SHA") == args.commit, + "Workflow commit differs from approval", + ) + require( + os.environ.get("GITHUB_EVENT_NAME") == "workflow_dispatch", + "Manual dispatch required", + ) + require( + os.environ.get("RELEASE_CONFIRMATION") == "PUBLISH GITHUB RELEASE", + "Explicit release approval required", + ) + with tempfile.TemporaryDirectory() as temp: + print( + publish( + Path.cwd(), + ReleaseRequest( + os.environ["GITHUB_REPOSITORY"], + args.commit, + args.version, + args.artifact_run, + args.candidate_sha256, + ), + Path(temp), + write=args.publish, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/tests/test_generator_release.py b/tests/test_generator_release.py new file mode 100644 index 0000000..e81cbc4 --- /dev/null +++ b/tests/test_generator_release.py @@ -0,0 +1,100 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, Jared W. Cook +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Test the generator's own reviewed release cycle without remote writes.""" + +import json +import subprocess +import sys +import tomllib +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def git(root: Path, *args: str) -> str: + return subprocess.check_output(["git", "-C", str(root), *args], text=True).strip() + + +def test_generator_release(tmp_path: Path) -> None: + root = tmp_path / "source" + root.mkdir() + version = tomllib.loads((ROOT / "pyproject.toml").read_text())["project"]["version"] + files = { + "pyproject.toml", + "Makefile", + "docs/cookiecutter_input.json", + "docs/jekyll/Makefile", + "docs/jekyll/_config.yml", + } + for name in files | {"cookiecutter.json", "release-policy.json"}: + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes((ROOT / name).read_bytes()) + git(root, "init", "-b", "feat-001") + git(root, "config", "user.name", "Synthetic Test") + git(root, "config", "user.email", "test@example.invalid") + git(root, "add", "-A") + git(root, "commit", "-m", "chore: synthetic published baseline") + baseline = git(root, "rev-parse", "HEAD") + git(root, "commit", "--allow-empty", "-m", "fix: synthetic generator fix") + head = git(root, "rev-parse", "HEAD") + out = tmp_path / "prepared" + subprocess.run( + [ + sys.executable, + str(ROOT / "scripts/release_prepare.py"), + "--baseline", + baseline, + "--published-version", + version, + "--current-version", + version, + "--output", + str(out), + ], + cwd=root, + check=True, + ) + major, minor, patch = map(int, version.split(".")) + proposed = f"{major}.{minor}.{patch + 1}" + assert json.loads((out / "plan.json").read_text())["proposed_version"] == proposed + assert git(root, "rev-parse", "HEAD") == head + assert not git(root, "status", "--porcelain") + candidate = tmp_path / "candidate" + subprocess.run( + [ + sys.executable, + str(ROOT / "scripts/release_plan.py"), + "--current-version", + version, + "--package-dir", + str(candidate), + ], + cwd=root, + check=True, + ) + subprocess.run(["sha256sum", "-c", "SHA256SUMS"], cwd=candidate, check=True) + manifest = json.loads((candidate / "release.json").read_text()) + assert manifest["commit"] == head and manifest["version"] == version + git(root, "apply", str(out / "version.patch")) + assert set(git(root, "diff", "--name-only").splitlines()) == files + assert ( + tomllib.loads((root / "pyproject.toml").read_text())["project"]["version"] + == proposed + ) + assert not git(root, "tag", "--list") + for target in ( + "git-release", + "github-release", + "git-tag", + "git-push", + "bump-version-patch", + "bumpversion-patch", + "bumpversion-minor", + "bumpversion-major", + ): + result = subprocess.run( + ["make", target], cwd=root, capture_output=True, text=True, check=False + ) + assert result.returncode != 0 + assert "direct release mutations are disabled" in result.stdout From 8b6a9a32cb5e4f8f309d816ccb1a17f6a44880bd Mon Sep 17 00:00:00 2001 From: jcook3701 Date: Tue, 1 Dec 2026 17:26:40 -0800 Subject: [PATCH 2/2] fix: keep generated readme paths portable --- Makefile | 1 + README.md | 2 +- changelogs/CHANGELOG.md | 1 + changelogs/releases/v0.1.0.md | 1 + 4 files changed, 4 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 3050e1f..88df35a 100644 --- a/Makefile +++ b/Makefile @@ -302,6 +302,7 @@ deps-check: deptry-check ## Run all Dependencies check tasks. nutrimatic-readme: ## Automated documentation assistant for Jinja and Jekyll templates. $(AT)echo "Running β˜• Nutri-Matic readme generator..." $(AT)$(NUTRIMATIC) build readme $(JEKYLL_DIR) $(README_FILE) --tmp-dir $(README_GEN_DIR) --jekyll-cmd 'bundle exec jekyll build --quiet' + $(AT)sed -i 's|^ Edit .*/docs/jekyll/README[.]md instead[.]| Edit docs/jekyll/README.md instead.|' "$(README_FILE)" $(AT)echo "βœ… Nutri-Matic documentation generation complete!" jekyll-build: ## A Ruby-based static site generator for project documentation. diff --git a/README.md b/README.md index ba075e8..14bf1de 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@

python3-cookiecutter

diff --git a/changelogs/CHANGELOG.md b/changelogs/CHANGELOG.md index d957045..a293fb4 100644 --- a/changelogs/CHANGELOG.md +++ b/changelogs/CHANGELOG.md @@ -12,6 +12,7 @@ - Import shared spelling dictionary - Add containerized documentation preview - Generate reviewed Python release preparation +- Prepare reviewed Python generator releases ### πŸ› Fixed diff --git a/changelogs/releases/v0.1.0.md b/changelogs/releases/v0.1.0.md index 9fe48cb..db7dc60 100644 --- a/changelogs/releases/v0.1.0.md +++ b/changelogs/releases/v0.1.0.md @@ -12,6 +12,7 @@ - Import shared spelling dictionary - Add containerized documentation preview - Generate reviewed Python release preparation +- Prepare reviewed Python generator releases ### πŸ› Fixed