diff --git a/.github/workflows/upgrade-release-tools.yaml b/.github/workflows/upgrade-release-tools.yaml index 1bd74e2..fe267c1 100644 --- a/.github/workflows/upgrade-release-tools.yaml +++ b/.github/workflows/upgrade-release-tools.yaml @@ -69,8 +69,6 @@ jobs: version: latest-known python-version: "3.15" enable-cache: false - - name: 📅 Check cutoff exception expiry - uses: $/check-nab-exceptions - name: 🔒 Refresh release lock id: lock uses: $/refresh-release-lock @@ -83,6 +81,9 @@ jobs: additional-matrix-implementations: ${{ inputs.additional-matrix-implementations }} exclude-newer: ${{ inputs.exclude-newer }} exclude-newer-package: ${{ inputs.exclude-newer-package }} + drop-redundant-exceptions: true + - name: 📅 Check cutoff exception expiry + uses: $/check-nab-exceptions - name: 📤 Upload maintenance patch id: upload uses: actions/upload-artifact@v7.0.2 @@ -103,6 +104,8 @@ jobs: artifact-id: ${{ needs.generate-lock.outputs.artifact-id }} allowed-paths: | pylock.toml + pyproject.toml + nab.toml ${{ inputs.additional-lock }} branch: automation/update-release-tools title: ${{ inputs.pull-request-title }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 11a59f5..1f36d27 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -304,6 +304,10 @@ - `upgrade-release-tools.yaml` checks cutoff exceptions before it refreshes the lock. A scheduled run now fails on an expired or undated exception and names the package, even when no release input changed ([#46](https://github.com/tox-dev/github-workflows/pull/46)) by [@gaborbernat](https://github.com/gaborbernat). +- `upgrade-release-tools.yaml` no longer takes `commit-message`; the pull request title is the commit subject. Remove + the input from callers: GitHub refuses to start a run that still passes it, with + `Invalid input, commit-message is not defined in the referenced workflow` + ([#46](https://github.com/tox-dev/github-workflows/pull/46)) by [@gaborbernat](https://github.com/gaborbernat). diff --git a/changelog.d/+drop-redundant-exceptions.bugfix.md b/changelog.d/+drop-redundant-exceptions.bugfix.md new file mode 100644 index 0000000..fb08fe6 --- /dev/null +++ b/changelog.d/+drop-redundant-exceptions.bugfix.md @@ -0,0 +1,4 @@ +`upgrade-release-tools.yaml` no longer fails on an expired cutoff exception that its own refresh makes redundant: it +deletes that exception in the refresh pull request, keeps the refreshed lock's `created-at`, and then fails only on an +undated exception or an expired one the new lock still needs. `refresh-release-lock` gains `drop-redundant-exceptions` +for this. diff --git a/changelog.d/+exception-expiry-guidance.doc.md b/changelog.d/+exception-expiry-guidance.doc.md new file mode 100644 index 0000000..52d7449 --- /dev/null +++ b/changelog.d/+exception-expiry-guidance.doc.md @@ -0,0 +1,2 @@ +Explain that a cutoff exception stays needed until a refresh re-anchors the lock, how to pick its expiry date, and how +to fix the `Invalid input, commit-message is not defined in the referenced workflow` startup failure. diff --git a/docs/locked-tools.md b/docs/locked-tools.md index 8a74244..59b55a4 100644 --- a/docs/locked-tools.md +++ b/docs/locked-tools.md @@ -53,7 +53,7 @@ A `[tool.nab]` exception that admits one package past the cutoff, `packages..uploaded-prior-to` + exception in `pyproject.toml` and `nab.toml` that the refreshed lock no longer needs: one dated at or before the + project's cutoff counted from now. The exception goes with the comment block directly above it, or only the value and + its `# expires` line when the package table holds other settings. An exception with a date but no time admits that + whole day, and one without a time zone, a relative exception, a cutoff other than `PD` or a date, and an inline + table are left alone. The patch then also holds the changed file, and the lock keeps its new `created-at`, since + without the exception only that anchor keeps the pinned releases under the cutoff. - `mode: check` first runs [`check-nab-exceptions`](#expire-cutoff-exceptions), then regenerates the locks without upgrading and fails if anything other than Nab's recorded command line differs. The committed lock must carry a valid `created-at` that is not in the future. Check mode installs the Nab version that the committed `pylock.toml` records @@ -174,17 +189,18 @@ token. Every Nab run unsets `SSL_CERT_FILE` and `SSL_CERT_DIR`, so Nab uses its own certificate store. -| Input | Default | Purpose | -| ----------------------------------- | ----------------- | ---------------------------------------------------------------- | -| `mode` | `refresh` | `refresh` or `check`. | -| `additional-lock` | empty | Basename of a secondary Nab lock for a separate build matrix. | -| `additional-lock-groups` | empty | Groups for the secondary lock; empty selects build requirements. | -| `additional-lock-selection` | `build-or-groups` | `project` selects the project's runtime dependencies instead. | -| `additional-matrix-python` | empty | Python range for the secondary lock. | -| `additional-matrix-platforms` | empty | Space-separated Nab platform IDs. | -| `additional-matrix-implementations` | empty | Space-separated Python implementations. | -| `exclude-newer` | `7 days` | Cutoff for Nab in refresh mode and the other tools. | -| `exclude-newer-package` | empty | Newline-separated `name=date` overrides. | +| Input | Default | Purpose | +| ----------------------------------- | ----------------- | ---------------------------------------------------------------------- | +| `mode` | `refresh` | `refresh` or `check`. | +| `drop-redundant-exceptions` | `false` | In refresh mode, delete exceptions the refreshed lock no longer needs. | +| `additional-lock` | empty | Basename of a secondary Nab lock for a separate build matrix. | +| `additional-lock-groups` | empty | Groups for the secondary lock; empty selects build requirements. | +| `additional-lock-selection` | `build-or-groups` | `project` selects the project's runtime dependencies instead. | +| `additional-matrix-python` | empty | Python range for the secondary lock. | +| `additional-matrix-platforms` | empty | Space-separated Nab platform IDs. | +| `additional-matrix-implementations` | empty | Space-separated Python implementations. | +| `exclude-newer` | `7 days` | Cutoff for Nab in refresh mode and the other tools. | +| `exclude-newer-package` | empty | Newline-separated `name=date` overrides. | Output `changed`: `true` only when refresh produces a patch. The resulting pull request's normal formatting job runs prek, and the writer checks patch paths and modes. diff --git a/docs/maintenance.md b/docs/maintenance.md index a07d7f2..910ea71 100644 --- a/docs/maintenance.md +++ b/docs/maintenance.md @@ -22,14 +22,17 @@ All three need the same setup: ## Refresh the release lock: `upgrade-release-tools.yaml` -The read-only job first runs [`check-nab-exceptions`](locked-tools.md#expire-cutoff-exceptions), so every scheduled run -fails on an expired or undated cutoff exception even when no release input changed. It then runs -[`refresh-release-lock`](locked-tools.md#refresh-release-lock) in `refresh` mode, which rebuilds the universal -`pylock.toml` with `nab lock --all-groups --all-extras --no-cache --upgrade`: runtime dependencies, all extras, and all -dependency groups. The project's `[tool.nab]` table sets the cutoff and any per-package exception; the caller adds and -removes those exceptions itself. uv only installs tools and never resolves the lock. - -When the lock changes, the job uploads a patch that may change only `pylock.toml` and the configured secondary lock. +The read-only job runs [`refresh-release-lock`](locked-tools.md#refresh-release-lock) in `refresh` mode with +`drop-redundant-exceptions: true`. It deletes the cutoff exceptions that a lock anchored now no longer needs, then +rebuilds the universal `pylock.toml` with `nab lock --all-groups --all-extras --no-cache --upgrade`: runtime +dependencies, all extras, and all dependency groups. The project's `[tool.nab]` table sets the cutoff and any +per-package exception; the caller adds them, and the refresh removes them once they are redundant. uv only installs +tools and never resolves the lock. The job then runs [`check-nab-exceptions`](locked-tools.md#expire-cutoff-exceptions) +on what is left, so a scheduled run fails on an undated exception or an expired one the refreshed lock still needs, even +when no release input changed. An expired exception the refresh makes redundant no longer blocks that refresh. + +When the lock changes, the job uploads a patch that may change only `pylock.toml`, the configured secondary lock, and +the `pyproject.toml` or `nab.toml` exceptions it dropped. [`open-maintenance-pr`](#open-a-maintenance-pull-request-open-maintenance-pryaml) checks it before minting the App token and opens or updates one pull request from `automation/update-release-tools` to `main`, labelled `dependencies` and `skip news`. Create both labels and allow the App to push that branch. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index d62dfa8..eb45803 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -3,6 +3,16 @@ Errors the shared workflows and Actions report, keyed by the text in the job log. Search this page for a phrase from the `Error:` annotation. +## Any shared workflow + +**`Invalid input, is not defined in the referenced workflow`** + +The run ends in `startup_failure` with no jobs and no logs; the message shows only on the run's page, under +`Invalid workflow file`. The caller passes an input the pinned release of the shared workflow does not declare, usually +after bumping the pin past a release that removed it. `upgrade-release-tools.yaml` dropped `commit-message` in 6.5.0, +since the pull request title is the commit subject: delete the `commit-message:` line from the caller's `with:` block. +For any other input, compare the caller's `with:` keys with the `workflow_call` inputs of the release it pins. + ## Any writer job **A dispatched check workflow prepared a real release.** The dry-run input was derived from `github.event_name`. A @@ -29,9 +39,11 @@ An `allow-skipped` entry of `required-checks` is not a job ID in the gate's `nee **`... uploaded-prior-to exception needs a '# expires YYYY-MM-DD' comment directly above it`** -A `[tool.nab]` cutoff exception has passed its date or has none. Delete the exception once the package is a week old, or -add or extend the `# expires` comment. See [Expire cutoff exceptions](locked-tools.md#expire-cutoff-exceptions). -Scheduled `upgrade-release-tools` runs fail on this even when nothing else changed. +A `[tool.nab]` cutoff exception has passed its date or has none. Add or extend the `# expires` comment. A package being +a week old is not enough to delete the exception: the relative cutoff counts from the committed lock's `created-at`, so +the exception stays needed until a refresh re-anchors the lock, and `upgrade-release-tools` drops it in that refresh's +pull request. See [Expire cutoff exceptions](locked-tools.md#expire-cutoff-exceptions). Scheduled +`upgrade-release-tools` runs fail on an expired exception that the refreshed lock still needs. **`check mode needs the Nab version in pylock.toml [tool.nab] nab-version`** diff --git a/refresh-release-lock/action.yml b/refresh-release-lock/action.yml index e2268b2..41f1624 100644 --- a/refresh-release-lock/action.yml +++ b/refresh-release-lock/action.yml @@ -22,6 +22,9 @@ inputs: mode: description: Refresh the lock or check that the committed lock is current default: refresh + drop-redundant-exceptions: + description: In refresh mode, delete the cutoff exceptions the refreshed lock no longer needs + default: "false" exclude-newer: description: Upload cutoff for the tools this Action installs from PyPI default: 7 days @@ -38,6 +41,16 @@ runs: - name: 📅 Check cutoff exception expiry if: inputs.mode == 'check' uses: $/check-nab-exceptions + - name: ✂️ Drop cutoff exceptions the refresh no longer needs + id: drop + if: inputs.mode == 'refresh' && inputs.drop-redundant-exceptions == 'true' + shell: bash + run: | + set -euo pipefail + files=(pyproject.toml) + if [[ -f nab.toml ]]; then files+=(nab.toml); fi + changed=$(python3 "$GITHUB_ACTION_PATH/../tools/drop_nab_exceptions.py" "${files[@]}") + echo "files=${changed//$'\n'/ }" >>"$GITHUB_OUTPUT" - name: 📦 Install Nab shell: bash env: @@ -154,6 +167,7 @@ runs: env: MODE: ${{ inputs.mode }} ADDITIONAL_LOCK: ${{ inputs.additional-lock }} + DROPPED: ${{ steps.drop.outputs.files }} run: | set -euo pipefail paths=(pylock.toml) @@ -162,7 +176,12 @@ runs: else echo 'Secondary lock skipped: additional-lock input is empty' fi - if [[ "$MODE" != check ]]; then + read -ra dropped_files <<<"$DROPPED" + if ((${#dropped_files[@]})); then + # Without the exceptions, only the refreshed created-at keeps the pinned releases under the cutoff. + echo "Lock created-at kept: ${dropped_files[*]} dropped cutoff exceptions" + paths+=("${dropped_files[@]}") + elif [[ "$MODE" != check ]]; then for lock in "${paths[@]}"; do git diff --quiet -- "$lock" && continue # Nab stamps created-at on every run; a lock that differs only there carries no dependency change. diff --git a/tests/bash32_arrays/test_empty_arrays.py b/tests/bash32_arrays/test_empty_arrays.py index 3821974..925f094 100644 --- a/tests/bash32_arrays/test_empty_arrays.py +++ b/tests/bash32_arrays/test_empty_arrays.py @@ -15,6 +15,8 @@ def test_unguarded_array_expansions_are_provably_non_empty() -> None: ("prepare-towncrier/action.yml", "args"): "set to three options before the call", ("publish-github-release/action.yml", "request"): "starts with two -f pairs", ("publish-post-release-pr/action.yml", "paths"): "checked non-empty before any other use", + ("refresh-release-lock/action.yml", "dropped_files"): "used only inside the non-empty check", + ("refresh-release-lock/action.yml", "files"): "starts with pyproject.toml", ("refresh-release-lock/action.yml", "paths"): "starts with pylock.toml", ("refresh-release-lock/action.yml", "requirements"): "set to one requirement in every mode", ("refresh-release-lock/action.yml", "selected_groups"): "used only inside the non-empty check", diff --git a/tests/refresh_release_lock/test_drop_nab_exceptions.py b/tests/refresh_release_lock/test_drop_nab_exceptions.py new file mode 100644 index 0000000..84b53db --- /dev/null +++ b/tests/refresh_release_lock/test_drop_nab_exceptions.py @@ -0,0 +1,169 @@ +import subprocess +import sys +from pathlib import Path +from typing import Final + +import pytest + +_SCRIPT: Final = Path(__file__).resolve().parents[2] / "tools/drop_nab_exceptions.py" +_OLD: Final = "2000-01-01T00:00:00Z" +_NEW: Final = "2999-01-01T00:00:00Z" + + +@pytest.mark.parametrize( + ("filename", "content", "expected"), + [ + pytest.param( + "pyproject.toml", + '[tool.nab]\nuploaded-prior-to = "P7D"\n# release-creator needs one.\n# expires 2000-01-02\n' + f"packages.release-creator.uploaded-prior-to = {_OLD}\n# expires 2999-01-02\n" + f"packages.ty.uploaded-prior-to = {_NEW}\n", + f'[tool.nab]\nuploaded-prior-to = "P7D"\n# expires 2999-01-02\npackages.ty.uploaded-prior-to = {_NEW}\n', + id="dotted-key-with-comments", + ), + pytest.param( + "pyproject.toml", + '[tool.nab]\nuploaded-prior-to = "P7D"\n\n# release-creator needs one.\n# expires 2000-01-02\n' + f'[tool.nab.packages."release-creator"]\nuploaded-prior-to = {_OLD}\n\n# python-sbom needs one.\n' + f'# expires 2999-01-02\n[tool.nab.packages."python-sbom"]\nuploaded-prior-to = {_NEW}\n', + '[tool.nab]\nuploaded-prior-to = "P7D"\n\n# python-sbom needs one.\n' + f'# expires 2999-01-02\n[tool.nab.packages."python-sbom"]\nuploaded-prior-to = {_NEW}\n', + id="table-before-another-table", + ), + pytest.param( + "pyproject.toml", + f'[tool.nab]\nuploaded-prior-to = "P7D"\n\n# expires 2000-01-02\n[tool.nab.packages.six]\n' + f"uploaded-prior-to = {_OLD}\n", + '[tool.nab]\nuploaded-prior-to = "P7D"\n', + id="last-table", + ), + pytest.param( + "pyproject.toml", + '[tool.nab]\nuploaded-prior-to = "P7D"\n# six needs universal dependencies.\n# expires 2000-01-02\n' + f"[tool.nab.packages.six]\nassume-universal-deps = true\nuploaded-prior-to = {_OLD}\n", + '[tool.nab]\nuploaded-prior-to = "P7D"\n# six needs universal dependencies.\n' + "[tool.nab.packages.six]\nassume-universal-deps = true\n", + id="table-with-other-settings", + ), + pytest.param( + "nab.toml", + f'uploaded-prior-to = "P7D"\n[packages.six]\nassume-universal-deps = true\nuploaded-prior-to = {_OLD}\n', + 'uploaded-prior-to = "P7D"\n[packages.six]\nassume-universal-deps = true\n', + id="nab-toml-table-without-expiry", + ), + pytest.param( + "pyproject.toml", + f'tool.nab.packages.six.uploaded-prior-to = {_OLD}\ntool.nab.uploaded-prior-to = "P7D"\n', + 'tool.nab.uploaded-prior-to = "P7D"\n', + id="first-line", + ), + pytest.param( + "pyproject.toml", + '[tool.nab]\nuploaded-prior-to = "P7D"\n# expires 2000-01-02\npackages.six.uploaded-prior-to = 2000-01-01\n', + '[tool.nab]\nuploaded-prior-to = "P7D"\n', + id="date-value", + ), + pytest.param( + "pyproject.toml", + "[tool.nab]\nuploaded-prior-to = 2026-10-01\n# expires 2000-01-02\n" + "packages.six.uploaded-prior-to = 2026-09-30T23:59:59Z\n# expires 2000-01-02\n" + "packages.ty.uploaded-prior-to = 2026-10-01\n", + "[tool.nab]\nuploaded-prior-to = 2026-10-01\n# expires 2000-01-02\n" + "packages.ty.uploaded-prior-to = 2026-10-01\n", + id="absolute-cutoff", + ), + ], +) +def test_drop_removes_exceptions_under_the_refresh_cutoff( + tmp_path: Path, filename: str, content: str, expected: str +) -> None: + path = tmp_path / filename + path.write_text(content) + + result = subprocess.run([sys.executable, str(_SCRIPT), str(path)], text=True, capture_output=True, check=False) + + assert (result.returncode, path.read_text(), result.stdout) == (0, expected, f"{path}\n") + assert "Cutoff exception dropped:" in result.stderr + + +@pytest.mark.parametrize( + "content", + [ + pytest.param( + f'[tool.nab]\nuploaded-prior-to = "P7D"\n# expires 2999-01-02\npackages.six.uploaded-prior-to = {_NEW}\n', + id="young-exception", + ), + pytest.param(f"[tool.nab]\n# expires 2000-01-02\npackages.six.uploaded-prior-to = {_OLD}\n", id="no-cutoff"), + pytest.param( + f'[tool.nab]\nuploaded-prior-to = "PT12H"\n# expires 2000-01-02\npackages.six.uploaded-prior-to = {_OLD}\n', + id="unsupported-relative-cutoff", + ), + pytest.param( + '[tool.nab]\nuploaded-prior-to = "P7D"\n# expires 2000-01-02\n' + "packages.six.uploaded-prior-to = 2000-01-01T00:00:00\n", + id="exception-without-time-zone", + ), + pytest.param( + '[tool.nab]\nuploaded-prior-to = "P7D"\n# expires 2000-01-02\npackages.six.uploaded-prior-to = "P3D"\n', + id="relative-exception", + ), + pytest.param( + f'[tool.nab]\nuploaded-prior-to = "P7D"\npackages = {{ six = {{ uploaded-prior-to = {_OLD} }} }}\n', + id="inline-table", + ), + pytest.param( + '[tool.nab]\nuploaded-prior-to = "P7D"\n[tool.nab.packages.six]\nassume-universal-deps = true\n', + id="override-without-cutoff", + ), + ], +) +def test_drop_keeps_exceptions_it_cannot_prove_redundant(tmp_path: Path, content: str) -> None: + path = tmp_path / "pyproject.toml" + path.write_text(content) + + result = subprocess.run([sys.executable, str(_SCRIPT), str(path)], text=True, capture_output=True, check=False) + + assert (result.returncode, result.stdout, result.stderr, path.read_text()) == (0, "", "", content) + + +def test_drop_prints_only_changed_files(tmp_path: Path) -> None: + (tmp_path / "pyproject.toml").write_text( + f'[tool.nab]\nuploaded-prior-to = "P7D"\npackages.six.uploaded-prior-to = {_OLD}\n' + ) + (tmp_path / "nab.toml").write_text('uploaded-prior-to = "P7D"\n') + + result = subprocess.run( + [sys.executable, str(_SCRIPT), str(tmp_path / "pyproject.toml"), str(tmp_path / "nab.toml")], + text=True, + capture_output=True, + check=False, + ) + + assert (result.returncode, result.stdout) == (0, f"{tmp_path / 'pyproject.toml'}\n") + + +@pytest.mark.parametrize( + ("content", "message"), + [ + pytest.param("[tool.nab\n", "Expected ']' at the end of a table declaration (at line 1, column 10)", id="toml"), + pytest.param(None, "No such file or directory", id="missing"), + ], +) +def test_drop_reports_unreadable_files(tmp_path: Path, content: str | None, message: str) -> None: + path = tmp_path / "pyproject.toml" + if content is not None: + path.write_text(content) + + result = subprocess.run([sys.executable, str(_SCRIPT), str(path)], text=True, capture_output=True, check=False) + + assert result.returncode == 1 + assert result.stderr.startswith("::error::") + assert message in result.stderr + + +def test_drop_import_has_no_cli_side_effect() -> None: + importer = f"import runpy, sys; sys.path.insert(0, {str(_SCRIPT.parent)!r}); runpy.run_path({str(_SCRIPT)!r}, run_name='imported')" + + result = subprocess.run([sys.executable, "-c", importer], text=True, capture_output=True, check=False) + + assert (result.returncode, result.stdout, result.stderr) == (0, "", "") diff --git a/tests/refresh_release_lock/test_refresh.py b/tests/refresh_release_lock/test_refresh.py index b6850a2..b59d1ba 100644 --- a/tests/refresh_release_lock/test_refresh.py +++ b/tests/refresh_release_lock/test_refresh.py @@ -205,6 +205,41 @@ def test_refresh_writes_patch_for_stale_lock( assert "diff --git a/pyproject.toml" not in patch +@pytest.mark.parametrize( + ("drop", "patched"), + [ + pytest.param("false", ["pylock.toml"], id="kept-by-default"), + pytest.param("true", ["pylock.toml", "pyproject.toml"], id="dropped"), + ], +) +def test_refresh_drops_exceptions_the_refreshed_lock_no_longer_needs( + lock_project: Path, nab_executable: Path, tmp_path: Path, action_scripts: Path, drop: str, patched: list[str] +) -> None: + project = lock_project / "pyproject.toml" + project.write_text( + project.read_text() + + "# expires 2000-01-01\n[tool.nab.packages.packaging]\nuploaded-prior-to = 2025-01-01T00:00:00Z\n" + ) + _commit_lock(lock_project, nab_executable) + outputs: dict[str, str] = {} + + result = action( + lock_project, + tmp_path, + action_scripts, + "refresh-release-lock", + outputs, + version="", + MODE="refresh", + DROP_REDUNDANT_EXCEPTIONS=drop, + ) + + assert result.returncode == 0, result.stderr + assert outputs["changed"] == "true" + patch = (tmp_path / "maintenance.patch").read_text() + assert [line.split(" b/")[1] for line in patch.splitlines() if line.startswith("diff --git")] == patched + + def test_refresh_installs_nab_under_cutoff(lock_project: Path, tmp_path: Path, action_scripts: Path) -> None: run(lock_project, "git", "add", ".") run(lock_project, "git", "commit", "-m", "Add the project") diff --git a/tests/upgrade_release_tools/test_upgrade.py b/tests/upgrade_release_tools/test_upgrade.py index 76da4ae..0c6ba8a 100644 --- a/tests/upgrade_release_tools/test_upgrade.py +++ b/tests/upgrade_release_tools/test_upgrade.py @@ -60,7 +60,7 @@ def test_upgrade_hands_the_patch_to_the_maintenance_writer(workflow: JsonObject) "uses": "$/.github/workflows/open-maintenance-pr.yaml", "with": { "artifact-id": "${{ needs.generate-lock.outputs.artifact-id }}", - "allowed-paths": "pylock.toml\n${{ inputs.additional-lock }}\n", + "allowed-paths": "pylock.toml\npyproject.toml\nnab.toml\n${{ inputs.additional-lock }}\n", "branch": "automation/update-release-tools", "title": "${{ inputs.pull-request-title }}", "body": "${{ inputs.pull-request-body }}", @@ -70,11 +70,67 @@ def test_upgrade_hands_the_patch_to_the_maintenance_writer(workflow: JsonObject) } -def test_upgrade_checks_cutoff_exceptions_before_refreshing_the_lock(workflow: JsonObject) -> None: +def test_upgrade_checks_cutoff_exceptions_after_dropping_the_redundant_ones(workflow: JsonObject) -> None: names = [item["name"] for item in steps(workflow, "generate-lock")] assert step(workflow, "generate-lock", "📅 Check cutoff exception expiry")["uses"] == "$/check-nab-exceptions" - assert names.index("📅 Check cutoff exception expiry") < names.index("🔒 Refresh release lock") + assert at(step(workflow, "generate-lock", "🔒 Refresh release lock"), "with", "drop-redundant-exceptions") == "true" + assert ( + names.index("🔒 Refresh release lock") + < names.index("📅 Check cutoff exception expiry") + < names.index("📤 Upload maintenance patch") + ) + + +def test_upgrade_restores_a_lock_whose_only_change_is_its_anchor( + anchored_lock: Path, tmp_path: Path, action_scripts: Path +) -> None: + result = execute( + anchored_lock, + refresh_script(action_scripts, "lock"), + tmp_path, + MODE="refresh", + GITHUB_OUTPUT=str(tmp_path / "output"), + ) + + assert result.returncode == 0, result.stderr + assert (tmp_path / "output").read_text() == "changed=false\n" + assert run(anchored_lock, "git", "status", "--porcelain").stdout == "" + + +def test_upgrade_keeps_the_lock_anchor_that_dropped_exceptions_need( + anchored_lock: Path, tmp_path: Path, action_scripts: Path +) -> None: + project = anchored_lock / "pyproject.toml" + project.write_text(project.read_text() + "\n") + + result = execute( + anchored_lock, + refresh_script(action_scripts, "lock"), + tmp_path, + MODE="refresh", + DROPPED="pyproject.toml", + GITHUB_OUTPUT=str(tmp_path / "output"), + ) + + assert result.returncode == 0, result.stderr + assert (tmp_path / "output").read_text() == "changed=true\n" + patch = (tmp_path / "maintenance.patch").read_text() + assert [line for line in patch.splitlines() if line.startswith("diff --git")] == [ + "diff --git a/pylock.toml b/pylock.toml", + "diff --git a/pyproject.toml b/pyproject.toml", + ] + assert "+created-at = 2026-11-17T00:00:00Z" in patch + + +@pytest.fixture +def anchored_lock(lock_repository: Path) -> Path: + lock = lock_repository / "pylock.toml" + lock.write_text('lock-version = "1.0"\n[tool.nab]\ncreated-at = 2026-11-03T00:00:00Z\n') + run(lock_repository, "git", "add", ".") + run(lock_repository, "git", "commit", "-m", "Add lock") + lock.write_text(lock.read_text().replace("2026-11-03", "2026-11-17")) + return lock_repository def execute(repository: Path, script: Path, tmp_path: Path, **environment: str) -> subprocess.CompletedProcess[str]: @@ -91,6 +147,7 @@ def execute(repository: Path, script: Path, tmp_path: Path, **environment: str) "MATRIX_PYTHON": "", "MATRIX_PLATFORMS": "", "MATRIX_IMPLEMENTATIONS": "", + "DROPPED": "", } | environment, text=True, diff --git a/tools/check_nab_exceptions.py b/tools/check_nab_exceptions.py index e2fb994..48856ff 100644 --- a/tools/check_nab_exceptions.py +++ b/tools/check_nab_exceptions.py @@ -6,6 +6,7 @@ import tomllib from datetime import UTC, date, datetime from pathlib import Path +from typing import Any def main() -> None: @@ -30,8 +31,7 @@ class _Options(argparse.Namespace): def _problems(path: Path, today: date) -> list[str]: text = path.read_text(encoding="utf-8") - document = tomllib.loads(text) - config = document.get("tool", {}).get("nab", {}) if path.name == "pyproject.toml" else document + config = nab_config(path, text) problems = [ f"{path}: [[package-rules]] {rule.get('match')} sets uploaded-prior-to, which expiry is not checked for;" " move it to a packages. table" @@ -45,9 +45,14 @@ def _problems(path: Path, today: date) -> list[str]: return problems +def nab_config(path: Path, text: str) -> dict[str, Any]: + document = tomllib.loads(text) + return document.get("tool", {}).get("nab", {}) if path.name == "pyproject.toml" else document + + def _exception_problems(lines: list[str], path: Path, name: str, today: date) -> list[str]: where = f"{path}: packages.{name}" - start = _start_line(lines, name) + start = exception_line(lines, name) if start is None: return [f"{where} is not a table or dotted key that the expiry check can locate"] above = lines[start - 1] if start else "" @@ -62,7 +67,7 @@ def _exception_problems(lines: list[str], path: Path, name: str, today: date) -> return [] -def _start_line(lines: list[str], name: str) -> int | None: +def exception_line(lines: list[str], name: str) -> int | None: selector = rf'(?:"{re.escape(name)}"|{re.escape(name)})' header = re.compile(rf"\[\s*(?:tool\.nab\.)?packages\.{selector}\s*\]") dotted = re.compile(rf"(?:tool\.nab\.)?packages\.{selector}\.uploaded-prior-to\s*=") @@ -77,5 +82,7 @@ def _start_line(lines: list[str], name: str) -> int | None: __all__ = [ + "exception_line", "main", + "nab_config", ] diff --git a/tools/drop_nab_exceptions.py b/tools/drop_nab_exceptions.py new file mode 100644 index 0000000..01e6d58 --- /dev/null +++ b/tools/drop_nab_exceptions.py @@ -0,0 +1,107 @@ +"""Drop the Nab cutoff exceptions that a lock refreshed now no longer needs, and print each file it changed.""" + +import argparse +import re +import sys +import tomllib +from datetime import UTC, date, datetime, time, timedelta +from pathlib import Path + +from check_nab_exceptions import exception_line, nab_config + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("paths", nargs="+", type=Path) + paths = parser.parse_args(namespace=_Options()).paths + now = datetime.now(UTC) + try: + changed = [path for path in paths if _drop(path, now)] + except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as error: + print(f"::error::{error}", file=sys.stderr) + sys.exit(1) + for path in changed: + print(path) + + +class _Options(argparse.Namespace): + paths: list[Path] + + +def _drop(path: Path, now: datetime) -> bool: + text = path.read_text(encoding="utf-8") + config = nab_config(path, text) + if (cutoff := _cutoff(config.get("uploaded-prior-to"), now)) is None: + return False + lines = text.splitlines(keepends=True) + dropped = False + for name, body in config.get("packages", {}).items(): + # A date admits that whole day, so it is redundant only once the day after it is under the cutoff. + if (until := _moment(body.get("uploaded-prior-to"), timedelta(days=1))) is None or until > cutoff: + continue + if (remaining := _without(lines, name)) is None: + continue + lines = remaining + dropped = True + print( + f"Cutoff exception dropped: {path}: packages.{name} uploaded-prior-to is at or before the refresh cutoff" + f" {cutoff:%Y-%m-%dT%H:%M:%SZ}", + file=sys.stderr, + ) + if dropped: + path.write_text("".join(lines), encoding="utf-8") + return dropped + + +def _cutoff(value: object, now: datetime) -> datetime | None: + if isinstance(value, str): + return now - timedelta(days=int(days[1])) if (days := re.fullmatch(r"P(\d+)D", value)) else None + return _moment(value, timedelta()) + + +def _moment(value: object, date_offset: timedelta) -> datetime | None: + if isinstance(value, datetime): + return value if value.tzinfo is not None else None + if isinstance(value, date): + return datetime.combine(value + date_offset, time(), UTC) + return None + + +def _without(lines: list[str], name: str) -> list[str] | None: + if (start := exception_line(lines, name)) is None: + return None + if not lines[start].lstrip().startswith("["): + return _collapse(lines, _comment_start(lines, start), start + 1) + end = next((index for index in range(start + 1, len(lines)) if lines[index].lstrip().startswith("[")), len(lines)) + keys = [index for index in range(start + 1, end) if lines[index].strip() and not _is_comment(lines[index])] + if len(keys) == 1: + return _collapse(lines, _comment_start(lines, start), keys[0] + 1) + value = next(index for index in keys if re.match(r"uploaded-prior-to\s*=", lines[index].lstrip())) + expiry = [start - 1] if start and re.fullmatch(r"#\s*expires\s+\S+", lines[start - 1].strip()) else [] + return [line for index, line in enumerate(lines) if index not in {value, *expiry}] + + +def _comment_start(lines: list[str], start: int) -> int: + while start and _is_comment(lines[start - 1]): + start -= 1 + return start + + +def _is_comment(line: str) -> bool: + return line.lstrip().startswith("#") + + +def _collapse(lines: list[str], first: int, last: int) -> list[str]: + remaining = [*lines[:first], *lines[last:]] + if first and not remaining[first - 1].strip() and (first == len(remaining) or not remaining[first].strip()): + del remaining[first - 1] + return remaining + + +if __name__ == "__main__": + main() + + +__all__ = [ + "main", +]