diff --git a/.github/scripts/release.py b/.github/scripts/release.py new file mode 100644 index 0000000..134d0d4 --- /dev/null +++ b/.github/scripts/release.py @@ -0,0 +1,169 @@ +"""Prepare a versioned, retryable release from a main-branch source commit.""" +import datetime +import io +import json +import os +from pathlib import Path +import re +import subprocess +import tarfile +import tomllib +import urllib.error +import urllib.request + +REPOSITORY = "https://github.com/LukasNiessen/ArchUnitRust" +METADATA_FILES = ( + "Cargo.toml", "Cargo.lock", "CHANGELOG.md", "README.md", "docs/index.md", + "tests/fixtures/registry_consumer/Cargo.toml.template", +) + + +def git(*args): + return subprocess.check_output(["git", *args], text=True).strip() + + +def version_tuple(version): + if not re.fullmatch(r"(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)", version): + raise ValueError(f"Expected a stable x.y.z version, got {version!r}") + return tuple(map(int, version.split("."))) + + +def select_version(current, published, head, published_head=None): + """Honor explicit bumps; otherwise increment the latest published patch.""" + current_key = version_tuple(current) + if current in published and published_head == head: + return current, False + stable = [version_tuple(v) for v in published if re.fullmatch(r"\d+\.\d+\.\d+", v)] + if not stable or current_key > max(stable): + return current, True + major, minor, patch = max(stable) + return f"{major}.{minor}.{patch + 1}", True + + +def fetch(url): + request = urllib.request.Request(url, headers={ + "User-Agent": f"ArchUnitRust release automation ({REPOSITORY})", + }) + with urllib.request.urlopen(request, timeout=45) as response: + return response.read() + + +def registry_versions(): + try: + data = json.loads(fetch("https://crates.io/api/v1/crates/archunit")) + except urllib.error.HTTPError as error: + if error.code == 404: + return [] + raise + if (data["crate"].get("repository") or "").rstrip("/") != REPOSITORY: + raise RuntimeError("The existing archunit crate belongs to a different repository.") + # Include yanked versions: their version numbers cannot be reused either. + return [version["num"] for version in data["versions"]] + + +def published_commit(version): + version_tuple(version) + archive = fetch(f"https://static.crates.io/crates/archunit/archunit-{version}.crate") + with tarfile.open(fileobj=io.BytesIO(archive), mode="r:gz") as crate: + metadata = crate.extractfile(f"archunit-{version}/.cargo_vcs_info.json") + if metadata is None: + raise RuntimeError("Published crate has no source commit metadata.") + return json.load(metadata)["git"]["sha1"] + + +def replace_once(content, pattern, replacement, path): + result, count = re.subn(pattern, lambda _: replacement, content, count=1, flags=re.MULTILINE) + if count != 1: + raise RuntimeError(f"Missing release version field in {path}") + return result + + +def update_metadata(root, old, new, source, today=None): + today = today or datetime.datetime.now(datetime.timezone.utc).date().isoformat() + manifest_path = root / "Cargo.toml" + manifest = manifest_path.read_text(encoding="utf-8") + manifest = replace_once(manifest, rf'^version = "{re.escape(old)}"$', + f'version = "{new}"', manifest_path) + manifest_path.write_text(manifest, encoding="utf-8") + + lock_path = root / "Cargo.lock" + lock = lock_path.read_text(encoding="utf-8") + lock = replace_once(lock, rf'(\[\[package\]\]\nname = "archunit"\n)version = "{re.escape(old)}"', + f'[[package]]\nname = "archunit"\nversion = "{new}"', lock_path) + lock_path.write_text(lock, encoding="utf-8") + + fixture_path = root / METADATA_FILES[-1] + fixture = fixture_path.read_text(encoding="utf-8") + fixture = replace_once(fixture, r'^archunit = "=[^"]+"$', f'archunit = "={new}"', fixture_path) + fixture_path.write_text(fixture, encoding="utf-8") + + for name in ("README.md", "docs/index.md"): + path = root / name + content = path.read_text(encoding="utf-8") + for before, after in ( + (f"archunit@{old}", f"archunit@{new}"), + (f'archunit = "{old}"', f'archunit = "{new}"'), + (f"archunit\N{GRAVE ACCENT} {old}", f"archunit\N{GRAVE ACCENT} {new}"), + (f"ArchUnitRust {old} installs", f"ArchUnitRust {new} installs"), + ): + content = content.replace(before, after) + path.write_text(content, encoding="utf-8") + + changelog_path = root / "CHANGELOG.md" + changelog = changelog_path.read_text(encoding="utf-8") + if f"## [{new}]" not in changelog: + heading = ( + f"## [Unreleased]\n\n## [{new}] - {today}\n\n" + f"- Automated release of changes through [{source[:7]}]({REPOSITORY}/commit/{source})." + ) + changelog = changelog.replace("## [Unreleased]", heading, 1) + changelog += f"\n[{new}]: {REPOSITORY}/releases/tag/v{new}\n" + changelog = re.sub(r"(?m)^\[Unreleased\]: .+$", + f"[Unreleased]: {REPOSITORY}/compare/v{new}...HEAD", changelog) + changelog_path.write_text(changelog, encoding="utf-8") + + +def recover_release_commit(source): + """Resume a previous attempt's metadata commit without picking up other changes.""" + candidates = git("log", "origin/main", "--format=%H", "--fixed-strings", + "--grep", f"Release-Source: {source}").splitlines() + for candidate in candidates: + if git("rev-parse", f"{candidate}^") != source: + continue + changed = set(git("diff-tree", "--no-commit-id", "--name-only", "-r", candidate).splitlines()) + if changed and changed.issubset(METADATA_FILES): + subprocess.run(["git", "checkout", "--detach", candidate], check=True) + return + + +def main(): + source = os.environ["GITHUB_SHA"] + if not re.fullmatch(r"[0-9a-f]{40}", source): + raise RuntimeError("Expected a full source commit SHA.") + recover_release_commit(source) + root = Path.cwd() + manifest = tomllib.loads((root / "Cargo.toml").read_text(encoding="utf-8")) + if manifest["package"]["name"] != "archunit": + raise RuntimeError("This workflow only publishes archunit.") + current = manifest["package"]["version"] + published = registry_versions() + head = git("rev-parse", "HEAD") + existing_head = published_commit(current) if current in published else None + version, publish = select_version(current, published, head, existing_head) + if publish: + update_metadata(root, current, version, source) + subprocess.run(["git", "add", "--", *METADATA_FILES], check=True) + if subprocess.run(["git", "diff", "--cached", "--quiet"]).returncode == 1: + subprocess.run([ + "git", "commit", "-m", + f"chore(release): archunit v{version}\n\nRelease-Source: {source}", + ], check=True) + if git("status", "--porcelain"): + raise RuntimeError("Release checkout must be clean before packaging.") + with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output: + output.write(f"version={version}\npublish={str(publish).lower()}\nsha={git('rev-parse', 'HEAD')}\n") + print(f"archunit {version}: {'publish after checks' if publish else 'already published; verify only'}") + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/test_release.py b/.github/scripts/test_release.py new file mode 100644 index 0000000..74655f1 --- /dev/null +++ b/.github/scripts/test_release.py @@ -0,0 +1,121 @@ +import importlib.util +from pathlib import Path +import tempfile +import unittest + +SPEC = importlib.util.spec_from_file_location("release", Path(__file__).with_name("release.py")) +release = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(release) + + +class ReleaseTests(unittest.TestCase): + def test_first_publication_keeps_manifest_version(self): + self.assertEqual(release.select_version("0.0.1", [], "new"), ("0.0.1", True)) + + def test_new_commit_gets_next_patch(self): + self.assertEqual( + release.select_version("0.0.1", ["0.0.1"], "new", "old"), ("0.0.2", True) + ) + + def test_retry_recognizes_published_source(self): + self.assertEqual( + release.select_version("0.0.2", ["0.0.1", "0.0.2"], "same", "same"), + ("0.0.2", False), + ) + + def test_explicit_minor_bump_is_preserved(self): + self.assertEqual(release.select_version("0.1.0", ["0.0.8"], "new"), ("0.1.0", True)) + + def test_versions_sort_numerically_and_include_reserved_numbers(self): + self.assertEqual( + release.select_version("0.0.1", ["0.0.9", "0.0.10"], "new"), ("0.0.11", True) + ) + + def test_prereleases_do_not_replace_stable_version_order(self): + self.assertEqual( + release.select_version("0.0.1", ["0.0.1", "1.0.0-beta.1"], "new"), ("0.0.2", True) + ) + + def test_invalid_manifest_versions_are_rejected(self): + for version in ("0.1", "v0.0.1", "0.0.01", "1.0.0-beta", "../secret"): + with self.subTest(version=version), self.assertRaises(ValueError): + release.select_version(version, [], "new") + + def test_metadata_changes_only_the_root_package_and_current_install_examples(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + files = { + "Cargo.toml": '[package]\nname = "archunit"\nversion = "0.0.1"\n', + "Cargo.lock": 'version = 4\n\n[[package]]\nname = "archunit"\nversion = "0.0.1"\n\n' + '[[package]]\nname = "other"\nversion = "0.0.1"\n', + "README.md": 'cargo add --dev archunit@0.0.1\narchunit = "0.0.1"\n', + "docs/index.md": 'ArchUnitRust 0.0.1 installs from crates.io\n', + "CHANGELOG.md": '# Changelog\n\n## [Unreleased]\n\n## [0.0.1] - 2026-08-24\n\n' + '[Unreleased]: old\n', + release.METADATA_FILES[-1]: '[dev-dependencies]\narchunit = "=0.0.1"\n', + } + for name, content in files.items(): + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content, encoding="utf-8") + release.update_metadata(root, "0.0.1", "0.0.2", "a" * 40, "2026-09-20") + lock = (root / "Cargo.lock").read_text(encoding="utf-8") + self.assertIn('name = "archunit"\nversion = "0.0.2"', lock) + self.assertIn('name = "other"\nversion = "0.0.1"', lock) + self.assertIn('archunit = "=0.0.2"', (root / release.METADATA_FILES[-1]).read_text()) + self.assertIn("archunit@0.0.2", (root / "README.md").read_text()) + self.assertIn("## [0.0.2] - 2026-09-20", (root / "CHANGELOG.md").read_text()) + self.assertIn("## [0.0.1] - 2026-08-24", (root / "CHANGELOG.md").read_text()) + + + def test_partial_release_retry_recovers_the_same_metadata_commit(self): + import os + import subprocess + from unittest.mock import patch + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) / "repo" + root.mkdir() + output = Path(directory) / "outputs" + original_directory = Path.cwd() + try: + os.chdir(root) + for name, content in { + "Cargo.toml": '[package]\nname = "archunit"\nversion = "0.0.1"\n', + "Cargo.lock": 'version = 4\n\n[[package]]\nname = "archunit"\nversion = "0.0.1"\n', + "README.md": 'archunit@0.0.1\n', + "docs/index.md": 'ArchUnitRust 0.0.1 installs\n', + "CHANGELOG.md": '## [Unreleased]\n\n## [0.0.1] - 2026-08-24\n[Unreleased]: old\n', + release.METADATA_FILES[-1]: 'archunit = "=0.0.1"\n', + }.items(): + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content, encoding="utf-8") + for args in ( + ("init", "-q"), ("config", "user.name", "Release Test"), + ("config", "user.email", "release@example.invalid"), + ("add", "."), ("commit", "-qm", "source"), + ): + subprocess.run(["git", *args], check=True) + source = release.git("rev-parse", "HEAD") + subprocess.run(["git", "update-ref", "refs/remotes/origin/main", source], check=True) + with patch.dict(os.environ, {"GITHUB_SHA": source, "GITHUB_OUTPUT": str(output)}): + with patch.object(release, "registry_versions", return_value=["0.0.1"]), \ + patch.object(release, "published_commit", return_value="0" * 40): + release.main() + metadata_commit = release.git("rev-parse", "HEAD") + self.assertNotEqual(source, metadata_commit) + self.assertIn("version=0.0.2\npublish=true", output.read_text()) + subprocess.run(["git", "update-ref", "refs/remotes/origin/main", metadata_commit], check=True) + subprocess.run(["git", "checkout", "-q", "--detach", source], check=True) + with patch.object(release, "registry_versions", return_value=["0.0.1", "0.0.2"]), \ + patch.object(release, "published_commit", return_value=metadata_commit): + release.main() + self.assertEqual(release.git("rev-parse", "HEAD"), metadata_commit) + self.assertIn("version=0.0.2\npublish=false", output.read_text()) + finally: + os.chdir(original_directory) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 93130aa..f793c6d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,6 +4,7 @@ on: push: pull_request: workflow_dispatch: + workflow_call: permissions: contents: read @@ -27,6 +28,9 @@ jobs: - name: Install stable Rust with quality components run: rustup toolchain install stable --profile minimal --component rustfmt,clippy --no-self-update + - name: Test release version selection and metadata updates + run: python3 -m unittest discover -s .github/scripts -p 'test_*.py' + - name: Check formatting run: cargo +stable fmt --all -- --check diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7ffd9b3..b790c9d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,29 +1,33 @@ name: Release on: + push: + branches: [main] workflow_dispatch: - inputs: - version: - description: Version from Cargo.toml, without a leading v - required: true - type: string + +permissions: + contents: read concurrency: group: crates-io-release cancel-in-progress: false jobs: + checks: + name: Release quality gates + uses: ./.github/workflows/ci.yml + publish: - name: Publish archunit ${{ inputs.version }} + name: Publish and verify archunit + needs: checks if: github.ref == 'refs/heads/main' runs-on: ubuntu-latest - timeout-minutes: 30 + timeout-minutes: 45 environment: release permissions: - contents: read - id-token: write + contents: write steps: - - name: Check out the release commit + - name: Check out the source commit and release history uses: actions/checkout@v7 with: fetch-depth: 0 @@ -32,22 +36,16 @@ jobs: - name: Install stable Rust with quality components run: rustup toolchain install stable --profile minimal --component rustfmt,clippy --no-self-update - - name: Verify the requested version and release inputs - env: - RELEASE_VERSION: ${{ inputs.version }} + - name: Prepare the next version or resume this release + id: prepare run: | - actual_version=$(cargo +stable metadata --no-deps --format-version 1 | jq -r '.packages[] | select(.name == "archunit") | .version') - if [ "$actual_version" != "$RELEASE_VERSION" ]; then - echo "Requested $RELEASE_VERSION, but Cargo.toml contains $actual_version" >&2 - exit 1 - fi - if git rev-parse --quiet --verify "refs/tags/v$RELEASE_VERSION" >/dev/null; then - echo "Tag v$RELEASE_VERSION already exists" >&2 - exit 1 - fi - grep --fixed-strings "archunit = \"=$RELEASE_VERSION\"" tests/fixtures/registry_consumer/Cargo.toml.template + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git fetch origin main + python3 .github/scripts/release.py - - name: Re-run every release quality gate + - name: Validate the final versioned archive + if: steps.prepare.outputs.publish == 'true' run: | cargo +stable fmt --all -- --check cargo +stable clippy --workspace --all-targets --all-features --locked -- -D warnings @@ -55,31 +53,28 @@ jobs: RUSTDOCFLAGS="-D warnings" cargo +stable doc --workspace --all-features --no-deps --locked cargo +stable publish --dry-run --locked - - name: Acquire a short-lived crates.io token - id: auth - uses: rust-lang/crates-io-auth-action@v1 + - name: Record release metadata on main before uploading + if: steps.prepare.outputs.publish == 'true' + env: + GH_TOKEN: ${{ github.token }} + run: | + # No force push: a newer main commit makes this attempt stop before publishing. + # GITHUB_TOKEN pushes do not recursively trigger another workflow run. + export GIT_CONFIG_COUNT=1 + export GIT_CONFIG_KEY_0=http.https://github.com/.extraheader + export GIT_CONFIG_VALUE_0="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$GH_TOKEN" | base64 -w0)" + git push origin HEAD:main - name: Publish the immutable crate archive + if: steps.prepare.outputs.publish == 'true' env: - CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }} - run: cargo +stable publish --locked - - verify: - name: Verify registry installation and create the GitHub release - needs: publish - runs-on: ubuntu-latest - timeout-minutes: 10 - permissions: - contents: write - steps: - - name: Check out the published commit - uses: actions/checkout@v7 - with: - fetch-depth: 0 - persist-credentials: false - - - name: Install stable Rust - run: rustup toolchain install stable --profile minimal --no-self-update + CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} + run: | + if [ -z "$CARGO_REGISTRY_TOKEN" ]; then + echo "The CARGO_REGISTRY_TOKEN repository secret is required." >&2 + exit 1 + fi + cargo +stable publish --locked - name: Install the exact registry version in a standalone project run: | @@ -92,7 +87,7 @@ jobs: if CARGO_TARGET_DIR="$RUNNER_TEMP/registry-consumer-target" cargo +stable test --manifest-path "$consumer/Cargo.toml"; then exit 0 fi - echo "Registry version is not visible yet (attempt $attempt of 18)" >&2 + echo "Registry consumer not ready (attempt $attempt of 18)" >&2 sleep 10 done exit 1 @@ -100,5 +95,13 @@ jobs: - name: Tag the verified commit and create the GitHub release env: GH_TOKEN: ${{ github.token }} - RELEASE_VERSION: ${{ inputs.version }} - run: gh release create "v$RELEASE_VERSION" --target "$GITHUB_SHA" --title "archunit v$RELEASE_VERSION" --generate-notes + RELEASE_VERSION: ${{ steps.prepare.outputs.version }} + RELEASE_SHA: ${{ steps.prepare.outputs.sha }} + run: | + git fetch origin --tags + if git rev-parse --quiet --verify "refs/tags/v$RELEASE_VERSION" >/dev/null; then + test "$(git rev-parse "v$RELEASE_VERSION^{commit}")" = "$RELEASE_SHA" + fi + if ! gh release view "v$RELEASE_VERSION" >/dev/null 2>&1; then + gh release create "v$RELEASE_VERSION" --target "$RELEASE_SHA" --title "archunit v$RELEASE_VERSION" --generate-notes + fi diff --git a/.gitignore b/.gitignore index ac13715..978c0ae 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ /target/ *.rs.bk + +__pycache__/ diff --git a/CHANGELOG.md b/CHANGELOG.md index f96c76b..ee3285d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ Versioning; the `0.0.x` line deliberately signals that the public API is still e ## [Unreleased] -## [0.0.1] - 2026-08-24 +## [0.0.1] - 2026-09-20 ### Added diff --git a/RELEASING.md b/RELEASING.md index 393ca91..126e09e 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -1,53 +1,57 @@ # Releasing ArchUnitRust -Crates.io versions are immutable. A release is complete only when the registry archive can be -installed by a separate project, the matching Git tag and GitHub release exist, and the public -installation instructions name that published version. - -## One-time bootstrap for 0.0.1 - -Crates.io requires a crate's first version to be published manually before a trusted GitHub -publisher can be configured. From a clean, current `main` whose CI is green: - -1. Sign in to crates.io, verify the account email address, and create a short-lived API token that - is permitted to publish a new crate. Never put the token in Git, an issue, a workflow log, or a - chat message. -2. Store it with `cargo login`, run `cargo publish --dry-run --locked`, inspect the reported archive - contents, then run `cargo publish --locked` exactly once. -3. Copy `tests/fixtures/registry_consumer/` to a temporary directory, rename - `Cargo.toml.template` to `Cargo.toml`, and run `cargo test --manifest-path /Cargo.toml`. - Retry briefly if the crates.io index has not propagated yet. This fixture must resolve - `archunit = "=0.0.1"`; do not add a path or Git override. -4. Only after that test passes, create the matching release boundary: - - ```console - gh release create v0.0.1 --target main --title "archunit v0.0.1" --generate-notes - ``` - -5. Remove the local token with `cargo logout` if it is not needed for another crate. -6. In the crate's crates.io Trusted Publishing settings, add the GitHub repository owner - `LukasNiessen`, repository `ArchUnitRust`, workflow `release.yml`, and environment `release`. - -Do not invoke `.github/workflows/release.yml` for 0.0.1: the trusted publisher cannot exist until -that first version has reserved the crate name. - -## Later releases - -Prepare each version in its own reviewed branch and PR: - -1. Update `package.version` in `Cargo.toml` and refresh `Cargo.lock`. -2. Move the relevant changelog entries under a dated version heading and update comparison links. -3. Update the exact `archunit` version in - `tests/fixtures/registry_consumer/Cargo.toml.template` and the constant in - `tests/release_workflow.rs`. -4. Run the complete local gate set and merge only after CI is green. -5. From `main`, manually dispatch the Release workflow with the version number and no leading `v`. - -The publish job rechecks the version, tag absence, formatting, Clippy, all tests, rustdoc, and the -crate archive before obtaining a short-lived crates.io token through OpenID Connect. The verify job -then installs the exact registry version in the standalone fixture. Only after that succeeds does it -create the Git tag and GitHub release. - -If registry propagation delays the fixture, rerun only the failed verify job. The successful publish -job must not be rerun for an immutable version. If publication itself fails before crates.io accepts -the archive, correct the cause in a new PR; never reuse a version that the registry accepted. +The crates.io package and Rust import are both named **archunit**. Every push or merge to main +starts the Release workflow. A manual workflow dispatch on main retries or completes a release. + +## Credentials + +The repository secret CARGO_REGISTRY_TOKEN contains a crates.io API token permitted to publish +archunit. The first publication also needs permission to create this crate, and the account must +have a verified email address. The token is exposed only to the cargo publish step; it is not +stored in Git or passed as a command-line argument. + +Maintainers can replace the secret with GitHub's repository settings or +gh secret set CARGO_REGISTRY_TOKEN --repo LukasNiessen/ArchUnitRust, supplying the token on stdin. + +## Automatic releases + +1. The reusable CI workflow runs formatting, Clippy, documentation, archive validation, the full + Linux/Windows/macOS test matrix, architecture tests, MSRV checks, and release-script tests. +2. The release script checks crates.io. It uses Cargo.toml's version for the first publication. + For a new source commit whose manifest version is already published, it increments the latest + stable patch version. An explicit higher minor or major version in Cargo.toml is honored. +3. The script updates the root manifest and lockfile, current installation examples, changelog, + and exact-version registry-consumer fixture. It commits only those release metadata files. +4. The workflow reruns the quality gates and cargo publish --dry-run on that exact clean commit, + then pushes the metadata commit to main without force. If main advanced in the meantime, the + push fails before uploading; the newer main run will release the combined changes. +5. cargo publish --locked uploads the crate. A separate temporary Cargo project then installs the + exact published version from crates.io and runs an architecture test against its own source. +6. Only after that consumer passes does the workflow create the matching tag and GitHub release. + +Ordinary product changes still follow the issue/branch/PR workflow. The release bot is the explicit +exception for version metadata on main. Its GITHUB_TOKEN push does not trigger another workflow, +so automatic version bumps do not cause a release loop. Release attempts are serialized; GitHub +may replace an older pending run with a newer one, which includes the intervening main changes. + +## Retrying failures + +Use the GitHub Actions rerun controls or dispatch Release on main. Each metadata commit records +the original source SHA in a Release-Source trailer. A rerun recovers that commit, and compares +the archive's .cargo_vcs_info.json commit with the checkout. If that exact version and commit are +already on crates.io, publishing is skipped and registry verification/release creation resume. +A registry or network error fails the job; only an HTTP 404 means the crate does not yet exist. + +Crates.io versions cannot be overwritten, including yanked versions. Never force a release tag +to point at different source. If a published version has a product defect, fix it through a PR; +the next main run publishes a new patch. + +## Local checks + +Run the Cargo gates in CONTRIBUTING.md, plus: + + python -m unittest discover -s .github/scripts -p "test_*.py" + cargo publish --dry-run --locked + +The release script itself is intended for GitHub Actions: it requires GITHUB_SHA and GITHUB_OUTPUT, +reads crates.io, and may create a local metadata commit. Do not run it in a dirty development tree. diff --git a/tests/release_workflow.rs b/tests/release_workflow.rs index 08023d9..7d08fa8 100644 --- a/tests/release_workflow.rs +++ b/tests/release_workflow.rs @@ -1,6 +1,6 @@ use std::fs; -const VERSION: &str = "0.0.1"; +const VERSION: &str = env!("CARGO_PKG_VERSION"); #[test] fn manifest_and_archive_metadata_are_ready_for_crates_io() { @@ -36,19 +36,21 @@ fn manifest_and_archive_metadata_are_ready_for_crates_io() { assert!(license.contains("Permission is hereby granted, free of charge")); let changelog = read("CHANGELOG.md"); - assert!(changelog.contains(&format!("## [{VERSION}] - 2026-08-24"))); + assert!(changelog.contains(&format!("## [{VERSION}] - "))); assert!(changelog.contains("### Known limitations")); } #[test] -fn trusted_release_requires_main_and_revalidates_the_package() { +fn automatic_release_requires_main_and_revalidates_the_package() { let workflow = read(".github/workflows/release.yml"); - assert!(workflow.starts_with("name: Release\n\non:\n workflow_dispatch:\n")); + assert!(workflow.starts_with( + "name: Release\n\non:\n push:\n branches: [main]\n workflow_dispatch:\n" + )); assert!(workflow.contains(" cancel-in-progress: false\n")); assert!(workflow.contains("if: github.ref == 'refs/heads/main'")); assert!(workflow.contains("environment: release")); - assert!(workflow.contains("contents: read\n id-token: write")); + assert!(workflow.contains("needs: checks")); assert!(workflow.contains("persist-credentials: false")); assert!(workflow.contains("cargo +stable fmt --all -- --check")); assert!(workflow.contains( @@ -56,23 +58,26 @@ fn trusted_release_requires_main_and_revalidates_the_package() { )); assert!(workflow.contains("cargo +stable test --workspace --all-features --locked")); assert!(workflow.contains("cargo +stable publish --dry-run --locked")); - assert!(workflow.contains("uses: rust-lang/crates-io-auth-action@v1")); - assert!(workflow.contains("CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }}")); + assert!(workflow.contains("python3 .github/scripts/release.py")); + assert!(workflow.contains("CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}")); assert!(workflow.contains("cargo +stable publish --locked")); } #[test] fn release_is_tagged_only_after_the_registry_consumer_passes() { let workflow = read(".github/workflows/release.yml"); - let publish = position(&workflow, "run: cargo +stable publish --locked"); - let verify = position(&workflow, " verify:\n"); + let publish = position(&workflow, " cargo +stable publish --locked"); + let verify = position( + &workflow, + " - name: Install the exact registry version", + ); let consumer = position(&workflow, "cargo +stable test --manifest-path"); - let release = position(&workflow, "run: gh release create"); + let release = position(&workflow, " gh release create"); assert!(publish < verify); assert!(verify < consumer); assert!(consumer < release); - assert!(workflow.contains("needs: publish")); + assert!(workflow.contains("git push origin HEAD:main")); assert!(workflow.contains("for attempt in $(seq 1 18)")); assert!(workflow.contains("contents: write")); } @@ -97,8 +102,8 @@ fn public_installation_docs_name_the_verified_registry_version() { let plan = read("docs/PORTING_PLAN.md"); for public_entry_point in [&readme, &guide] { - assert!(public_entry_point.contains("cargo add --dev archunit@0.0.1")); - assert!(public_entry_point.contains("archunit = \"0.0.1\"")); + assert!(public_entry_point.contains(&format!("cargo add --dev archunit@{VERSION}"))); + assert!(public_entry_point.contains(&format!("archunit = \"{VERSION}\""))); assert!(!public_entry_point.contains("cargo add --dev --git")); assert!(!public_entry_point.contains("not on crates.io")); assert!(!public_entry_point.contains("not published on"));