diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml new file mode 100644 index 0000000..2155926 --- /dev/null +++ b/.github/workflows/prepare-release.yml @@ -0,0 +1,97 @@ +name: Prepare release + +# Runs scripts/release.py on main and opens a "Release X.Y.Z" pull request from the integrations bot. +# Nothing is published: merge the pull request, then run Publish on main. +on: + workflow_dispatch: + inputs: + version: + description: "patch, minor, major, or an exact version such as 0.7.0" + required: true + default: minor + type: string + +permissions: + contents: read + +concurrency: + group: prepare-release + cancel-in-progress: false + +defaults: + run: + shell: bash + +jobs: + prepare: + runs-on: ubuntu-latest + timeout-minutes: 10 + + steps: + - name: Require main + if: github.ref != 'refs/heads/main' + run: | + echo "::error::Run Prepare release on main; releases are built from main." + exit 1 + + - uses: actions/checkout@v6 + with: + ref: main + persist-credentials: false + + - uses: actions/setup-python@v6 + with: + python-version: "3.12" + + - name: Set the version and date the release notes + id: release + env: + # Passed through the environment, never pasted into the script; release.py validates it. + WANTED: ${{ inputs.version }} + run: python scripts/release.py --notes "$RUNNER_TEMP/notes.md" -- "$WANTED" + + - name: Get an integrations bot token + id: app-token + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + with: + # Public Client ID of the geonode-internal-integrations-bot App; `app-id` is deprecated in this action. + client-id: Iv23liVguZMcHwiYcaIm + private-key: ${{ secrets.INTEGRATIONS_BOT_PRIVATE_KEY }} + permission-contents: write + permission-pull-requests: write + + - name: Open the release pull request + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + BOT_LOGIN: ${{ steps.app-token.outputs.app-slug }}[bot] + PREVIOUS: ${{ steps.release.outputs.previous }} + VERSION: ${{ steps.release.outputs.version }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + branch="release/$VERSION" + git remote set-url origin "https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" + if git ls-remote --exit-code --heads origin "$branch" > /dev/null; then + echo "::error::Branch $branch already exists. Merge its pull request, or close it, delete the branch and run again." + exit 1 + fi + + bot_id=$(gh api "/users/${BOT_LOGIN}" --jq .id) + git config user.name "$BOT_LOGIN" + git config user.email "${bot_id}+${BOT_LOGIN}@users.noreply.github.com" + git checkout -b "$branch" + git commit --quiet -am "Release $VERSION" + git push --quiet origin "$branch" + + { + echo "Releases $VERSION (previous: $PREVIOUS). Made by \`scripts/release.py\` in [this run]($RUN_URL)." + echo + echo "## Release notes" + echo + cat "$RUNNER_TEMP/notes.md" + echo + echo "## After merging" + echo + echo "Run the \`Publish\` workflow on \`main\`. Merging publishes nothing." + } > "$RUNNER_TEMP/body.md" + url=$(gh pr create --base main --head "$branch" --title "Release $VERSION" --body-file "$RUNNER_TEMP/body.md") + echo "Opened $url" >> "$GITHUB_STEP_SUMMARY" diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index abb5bfb..fde65e6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -24,4 +24,6 @@ Every night the `Sync API spec` workflow compares `openapi.json` with production ## Reports and releases -For bugs, include the package version, runtime version, a minimal reproduction and expected behavior. Security reports belong in [SECURITY.md](SECURITY.md), not a public issue. Maintainers publish releases with the `Publish` workflow in GitHub Actions. +For bugs, include the package version, runtime version, a minimal reproduction and expected behavior. Security reports belong in [SECURITY.md](SECURITY.md), not a public issue. + +To release, run the `Prepare release` workflow on `main` with `patch`, `minor`, `major` or an exact version. It runs `scripts/release.py` (kept in step with the one in [geonodecom/sdk-typescript](https://github.com/geonodecom/sdk-typescript)), which sets the version in every file that records it and moves the `[Unreleased]` notes under that version, and opens a `Release X.Y.Z` pull request from the integrations bot. Review the notes, merge it, then run the `Publish` workflow on `main` with `publish_target` set to `pypi`. A release pull request and the nightly sync pull request conflict in `CHANGELOG.md`. If the sync one is merged first, close the release pull request, delete its branch and run `Prepare release` again. If the release is merged first, the next nightly run rebuilds the sync pull request on top of it; if people have pushed to that pull request, resolve the conflict by keeping its entry under `[Unreleased]`. Before 1.0, a release with a breaking change takes a new minor version. `python3 scripts/release.py minor` makes the same edits locally. diff --git a/scripts/release.py b/scripts/release.py new file mode 100755 index 0000000..5fcb609 --- /dev/null +++ b/scripts/release.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python3 +"""Prepare a release: set the version everywhere the SDK records it and turn ``[Unreleased]`` into a version section. + +Usage: ``python3 scripts/release.py 0.7.0`` (or ``patch``, ``minor``, ``major``). The same script is kept in +geonodecom/sdk-python and geonodecom/sdk-typescript; it finds out which SDK it is in from the files present. +It only edits files. The Prepare release workflow runs it on main and opens the "Release X.Y.Z" pull request; +after merging, run the Publish workflow. +""" + +from __future__ import annotations + +import argparse +import datetime +import json +import os +import re +import sys +from dataclasses import dataclass +from pathlib import Path +from typing import Callable + +ROOT = Path(__file__).resolve().parents[1] +UNRELEASED_HEADING = "## [Unreleased]" +# Semver without leading zeros; matched in full, so a trailing newline from a form or the API is refused. +VERSION = re.compile(r"(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)") + + +@dataclass(frozen=True) +class Replace: + """One line holding the version, found with ``pattern`` (``{v}`` stands for the version).""" + + path: str + pattern: str + + def apply(self, text: str, old: str, new: str) -> str: + regex = re.compile(self.pattern.replace("{v}", re.escape(old)), re.MULTILINE) + matches = regex.findall(text) + if len(matches) != 1: + raise SystemExit(f"{self.path}: expected one line matching {self.pattern!r} for {old}, got {len(matches)}") + return regex.sub(lambda m: m.group(0).replace(old, new), text) + + +@dataclass(frozen=True) +class Sdk: + name: str + marker: str + current: Callable[[Path], str] + edits: tuple[Replace, ...] + package_lock: bool + + +def python_version(root: Path) -> str: + match = re.search(r'^version = "([^"]+)"$', (root / "pyproject.toml").read_text(encoding="utf-8"), re.MULTILINE) + if not match: + raise SystemExit('pyproject.toml has no `version = "..."` line') + return match.group(1) + + +def package_version(root: Path) -> str: + return json.loads((root / "package.json").read_text(encoding="utf-8"))["version"] + + +SDKS = ( + Sdk( + name="Python", + marker="geonode_scraper_sdk/__init__.py", + current=python_version, + edits=( + Replace("pyproject.toml", r'^version = "{v}"$'), + Replace("geonode_scraper_sdk/__init__.py", r'^__version__ = "{v}"$'), + # Generated from pyproject.toml by scripts/generate.sh; set here too so a release needs no regeneration. + Replace("geonode_scraper_sdk/api_client.py", r"'geonode-python-sdk/{v}'"), + Replace("geonode_scraper_sdk/configuration.py", r'"SDK Package Version: {v}"'), + ), + package_lock=False, + ), + Sdk( + name="TypeScript", + marker="src/clientHeaders.ts", + current=package_version, + edits=( + Replace("package.json", r'^ "version": "{v}",$'), + Replace("src/clientHeaders.ts", r'^export const SDK_VERSION = "{v}";$'), + ), + package_lock=True, + ), +) + + +def detect(root: Path) -> Sdk: + found = [sdk for sdk in SDKS if (root / sdk.marker).is_file()] + if len(found) != 1: + raise SystemExit(f"Cannot tell which SDK {root} holds") + return found[0] + + +def parse(version: str) -> tuple[int, int, int]: + match = VERSION.fullmatch(version) + if not match: + raise SystemExit(f"Version must look like 1.2.3, got {version!r}") + major, minor, patch = (int(part) for part in match.groups()) + return major, minor, patch + + +def next_version(current: str, wanted: str) -> str: + major, minor, patch = parse(current) + bumped = { + "major": f"{major + 1}.0.0", + "minor": f"{major}.{minor + 1}.0", + "patch": f"{major}.{minor}.{patch + 1}", + } + new = bumped.get(wanted, wanted) + if parse(new) <= (major, minor, patch): + raise SystemExit(f"New version {new} must be greater than the current {current}") + return new + + +def release_changelog(text: str, version: str, date: str) -> str: + """Move the ``[Unreleased]`` notes under a new version heading and leave an empty ``[Unreleased]`` above it.""" + lines = text.splitlines() + if UNRELEASED_HEADING not in lines: + raise SystemExit(f"CHANGELOG.md has no '{UNRELEASED_HEADING}' heading") + if re.search(rf"^## \[{re.escape(version)}\]", text, re.MULTILINE): + raise SystemExit(f"CHANGELOG.md already has a section for {version}") + start = lines.index(UNRELEASED_HEADING) + 1 + end = next((i for i in range(start, len(lines)) if lines[i].startswith("## [")), len(lines)) + if not any(line.strip() for line in lines[start:end]): + raise SystemExit(f"Nothing to release: '{UNRELEASED_HEADING}' in CHANGELOG.md is empty") + heading = lines.index(UNRELEASED_HEADING) + return "\n".join([*lines[: heading + 1], "", f"## [{version}] - {date}", *lines[start:]]) + "\n" + + +def notes(changelog: str, version: str) -> str: + """The release notes under ``## [version]``, without the heading.""" + lines = changelog.splitlines() + start = next(i for i, line in enumerate(lines) if line.startswith(f"## [{version}]")) + 1 + end = next((i for i in range(start, len(lines)) if lines[i].startswith("## [")), len(lines)) + return "\n".join(lines[start:end]).strip() + "\n" + + +def release_package_lock(text: str, old: str, new: str) -> str: + lock = json.loads(text) + if json.dumps(lock, indent=2, ensure_ascii=False) + "\n" != text: + raise SystemExit("package-lock.json is not in npm's own format; run `npm install` first") + if lock.get("version") != old or lock["packages"][""].get("version") != old: + raise SystemExit(f"package-lock.json does not record version {old}; run `npm install` first") + lock["version"] = new + lock["packages"][""]["version"] = new + return json.dumps(lock, indent=2, ensure_ascii=False) + "\n" + + +def version_changes(root: Path, wanted: str) -> tuple[str, str, dict[str, str]]: + """Return the current version, the new one and the new text of every file recording the version.""" + sdk = detect(root) + old = sdk.current(root) + new = next_version(old, wanted) + changes: dict[str, str] = {} + for edit in sdk.edits: + changes[edit.path] = edit.apply((root / edit.path).read_text(encoding="utf-8"), old, new) + if sdk.package_lock: + changes["package-lock.json"] = release_package_lock( + (root / "package-lock.json").read_text(encoding="utf-8"), old, new + ) + if "package.json" in changes: + before = json.loads((root / "package.json").read_text(encoding="utf-8")) + after = json.loads(changes["package.json"]) + if after != {**before, "version": new}: + raise SystemExit("package.json: the edit changed more than the top-level version") + return old, new, changes + + +def plan(root: Path, wanted: str, date: str) -> tuple[str, str, dict[str, str]]: + """Return the current version, the new one and the new text of every file to change, without writing.""" + old, new, changes = version_changes(root, wanted) + changes["CHANGELOG.md"] = release_changelog((root / "CHANGELOG.md").read_text(encoding="utf-8"), new, date) + return old, new, changes + + +def main(argv: list[str] | None = None) -> None: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("version", help="the new version, such as 0.7.0, or patch, minor or major") + parser.add_argument("--date", default=datetime.date.today().isoformat(), help="release date (default: today)") + parser.add_argument("--notes", type=Path, help="also write the release notes to this file") + parser.add_argument("--root", type=Path, default=ROOT, help=argparse.SUPPRESS) + args = parser.parse_args(argv) + + old, new, changes = plan(args.root, args.version, args.date) + for path, text in changes.items(): + (args.root / path).write_text(text, encoding="utf-8") + if args.notes: + args.notes.write_text(notes(changes["CHANGELOG.md"], new), encoding="utf-8") + print(f"{detect(args.root).name} SDK {old} -> {new}. Updated:") + for path in changes: + print(f"- {path}") + print(f'Commit as "Release {new}", open a pull request, merge it, then run the Publish workflow on main.') + # The Prepare release workflow names its branch and pull request after the new version. + if os.environ.get("GITHUB_OUTPUT"): + with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as fh: + fh.write(f"previous={old}\nversion={new}\n") + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/tests/test_release.py b/tests/test_release.py new file mode 100644 index 0000000..684e7c0 --- /dev/null +++ b/tests/test_release.py @@ -0,0 +1,178 @@ +import importlib.util +import json +import sys +from pathlib import Path + +import pytest + +# The same test file lives in sdk-python (tests/) and sdk-typescript (scripts/tests/). +REPO = next(p for p in Path(__file__).resolve().parents if (p / "scripts" / "release.py").is_file()) +SCRIPT = REPO / "scripts" / "release.py" + +CHANGELOG = "# Changelog\n\n## [Unreleased]\n\n- New thing.\n\n## [0.6.2] - 2026-10-28\n\n- Old thing.\n" + + +@pytest.fixture(scope="module") +def release(): + spec = importlib.util.spec_from_file_location("release", SCRIPT) + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + yield module + sys.modules.pop(spec.name, None) + + +@pytest.fixture(autouse=True) +def no_actions_output(monkeypatch): + # CI sets GITHUB_OUTPUT for every step; the tests must not write into the real one. + monkeypatch.delenv("GITHUB_OUTPUT", raising=False) + + +def write(root, files): + for path, text in files.items(): + (root / path).parent.mkdir(parents=True, exist_ok=True) + (root / path).write_text(text, encoding="utf-8") + + +@pytest.fixture +def python_sdk(tmp_path): + write(tmp_path, { + "pyproject.toml": '[project]\nname = "geonode-scraper-sdk"\nversion = "0.6.2"\n', + "geonode_scraper_sdk/__init__.py": '__version__ = "0.6.2"\n', + "geonode_scraper_sdk/api_client.py": " self.user_agent = 'geonode-python-sdk/0.6.2'\n", + "geonode_scraper_sdk/configuration.py": ' "SDK Package Version: 0.6.2".\\\n', + "CHANGELOG.md": CHANGELOG, + }) + return tmp_path + + +@pytest.fixture +def typescript_sdk(tmp_path): + lock = {"name": "sdk", "version": "0.6.2", "lockfileVersion": 3, + "packages": {"": {"name": "sdk", "version": "0.6.2"}, "node_modules/x": {"version": "0.6.2"}}} + write(tmp_path, { + "package.json": '{\n "name": "sdk",\n "version": "0.6.2",\n "files": ["dist"]\n}\n', + "package-lock.json": json.dumps(lock, indent=2) + "\n", + "src/clientHeaders.ts": 'export const SDK_VERSION = "0.6.2";\n', + "CHANGELOG.md": CHANGELOG, + }) + return tmp_path + + +def test_python_release_sets_every_version_and_dates_the_notes(release, python_sdk): + release.main(["minor", "--date", "2026-11-25", "--root", str(python_sdk)]) + + assert 'version = "0.7.0"' in (python_sdk / "pyproject.toml").read_text() + assert '__version__ = "0.7.0"' in (python_sdk / "geonode_scraper_sdk/__init__.py").read_text() + assert "'geonode-python-sdk/0.7.0'" in (python_sdk / "geonode_scraper_sdk/api_client.py").read_text() + assert '"SDK Package Version: 0.7.0"' in (python_sdk / "geonode_scraper_sdk/configuration.py").read_text() + assert (python_sdk / "CHANGELOG.md").read_text() == ( + "# Changelog\n\n## [Unreleased]\n\n## [0.7.0] - 2026-11-25\n\n- New thing.\n\n" + "## [0.6.2] - 2026-10-28\n\n- Old thing.\n" + ) + + +def test_typescript_release_touches_only_the_package_versions(release, typescript_sdk): + release.main(["0.7.0", "--date", "2026-11-25", "--root", str(typescript_sdk)]) + + assert (typescript_sdk / "package.json").read_text() == ( + '{\n "name": "sdk",\n "version": "0.7.0",\n "files": ["dist"]\n}\n' + ) + lock = json.loads((typescript_sdk / "package-lock.json").read_text()) + assert (lock["version"], lock["packages"][""]["version"]) == ("0.7.0", "0.7.0") + assert lock["packages"]["node_modules/x"]["version"] == "0.6.2" + assert 'SDK_VERSION = "0.7.0"' in (typescript_sdk / "src/clientHeaders.ts").read_text() + assert "## [Unreleased]\n\n## [0.7.0] - 2026-11-25\n" in (typescript_sdk / "CHANGELOG.md").read_text() + + +def test_in_actions_it_reports_the_versions_and_writes_the_notes(release, python_sdk, monkeypatch, tmp_path): + output = tmp_path / "github_output" + monkeypatch.setenv("GITHUB_OUTPUT", str(output)) + + release.main(["minor", "--date", "2026-11-25", "--root", str(python_sdk), "--notes", str(tmp_path / "notes.md")]) + + assert output.read_text() == "previous=0.6.2\nversion=0.7.0\n" + assert (tmp_path / "notes.md").read_text() == "- New thing.\n" + + +@pytest.mark.parametrize( + ("current", "wanted", "expected"), + [ + ("0.6.2", "patch", "0.6.3"), + ("0.6.2", "minor", "0.7.0"), + ("0.6.2", "major", "1.0.0"), + ("0.6.2", "0.10.0", "0.10.0"), + ], +) +def test_next_version(release, current, wanted, expected): + assert release.next_version(current, wanted) == expected + + +@pytest.mark.parametrize("wanted", ["0.6.2", "0.6.1", "0.7", "v0.7.0", "0.7.0\n", "0.07.0"]) +def test_next_version_refuses_a_version_that_is_not_newer_or_malformed(release, wanted): + with pytest.raises(SystemExit): + release.next_version("0.6.2", wanted) + + +@pytest.mark.parametrize( + ("changelog", "message"), + [ + ("# Changelog\n\n## [Unreleased]\n\n## [0.6.2]\n\n- Old.\n", "is empty"), + ("# Changelog\n\n## [0.6.2]\n\n- Old.\n", "has no"), + ("# Changelog\n\n## [Unreleased]\n\n- New.\n\n## [0.7.0]\n\n- Old.\n", "already has a section"), + ], +) +def test_changelog_problems_stop_the_release(release, changelog, message): + with pytest.raises(SystemExit, match=message): + release.release_changelog(changelog, "0.7.0", "2026-11-25") + + +def test_nothing_is_written_when_a_file_no_longer_holds_the_version(release, python_sdk): + (python_sdk / "geonode_scraper_sdk/api_client.py").write_text(" self.user_agent = 'something-else'\n") + + with pytest.raises(SystemExit, match="api_client.py"): + release.main(["minor", "--root", str(python_sdk)]) + + assert 'version = "0.6.2"' in (python_sdk / "pyproject.toml").read_text() + assert "## [Unreleased]\n\n- New thing." in (python_sdk / "CHANGELOG.md").read_text() + + +def test_input_after_double_dash_is_a_version_not_an_option(release, python_sdk): + # Prepare release passes the form input as `-- "$WANTED"`, so `-h` must fail as a version, not print help. + with pytest.raises(SystemExit, match="Version must look like"): + release.main(["--root", str(python_sdk), "--", "-h"]) + + assert 'version = "0.6.2"' in (python_sdk / "pyproject.toml").read_text() + + +def test_a_version_line_found_twice_stops_the_release(release, python_sdk): + (python_sdk / "geonode_scraper_sdk/__init__.py").write_text('__version__ = "0.6.2"\n__version__ = "0.6.2"\n') + + with pytest.raises(SystemExit, match="got 2"): + release.version_changes(python_sdk, "minor") + + +def test_package_json_edit_must_change_only_the_top_level_version(release, typescript_sdk): + # The indented line the script edits belongs to a nested object here, not to the package. + (typescript_sdk / "package.json").write_text( + '{\n"name": "sdk",\n"version": "0.6.2",\n"engines": {\n "version": "0.6.2",\n "node": ">=20"\n}\n}\n' + ) + + with pytest.raises(SystemExit, match="more than the top-level version"): + release.version_changes(typescript_sdk, "minor") + + +def test_package_lock_not_written_by_npm_stops_the_release(release, typescript_sdk): + lock = json.loads((typescript_sdk / "package-lock.json").read_text()) + (typescript_sdk / "package-lock.json").write_text(json.dumps(lock, indent=4) + "\n") + + with pytest.raises(SystemExit, match="npm's own format"): + release.version_changes(typescript_sdk, "minor") + + +def test_this_repository_records_its_version_where_the_script_expects(release): + # Fails when regeneration or a hand edit moves a version line, before anyone tries to release. + old, new, changes = release.version_changes(REPO, "patch") + + assert release.parse(new) > release.parse(old) + assert all(text.count(new) for text in changes.values())