Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .github/workflows/sync-openapi.yml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ jobs:

- name: Regenerate the SDK
if: steps.sync.outputs.changed == 'true'
# Postprocessing writes what it could not fix on its own here instead of failing, so a pull request still opens.
env:
SYNC_NOTES: ${{ runner.temp }}/sync-notes.md
run: bash scripts/generate.sh

- name: Classify the change
Expand Down Expand Up @@ -128,6 +131,12 @@ jobs:

{
cat "$RUNNER_TEMP/summary.md"
if [ -s "$RUNNER_TEMP/sync-notes.md" ]; then
echo "## Needs attention"
echo
head -c 10000 "$RUNNER_TEMP/sync-notes.md"
echo
fi
echo "## oasdiff: $KIND"
echo
echo '```text'
Expand Down
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ The tests use local fixtures and mocks; they do not require an API key. Never in

The runtime client is generated from `openapi.json`. Update the contract and generation/postprocessing scripts when changing generated behavior, and add a focused regression test. To regenerate, run `bash scripts/generate.sh`. It uses the included contract and the generator version recorded in `.openapi-generator/VERSION`. Install `uv` (recommended) or the matching `openapi-generator-cli` and a Java runtime first, plus Python 3 for filtering and postprocessing.

Every night the `Sync API spec` workflow compares `openapi.json` with production (`scripts/sync_openapi.py`), regenerates the client and keeps one pull request from the integrations bot up to date, on the `bot/openapi-sync` branch. It is labelled `breaking` or `additive` by oasdiff and adds a changelog entry under `[Unreleased]`. Review it like any other pull request. When a breaking change fails the tests, push the fixes to that branch: the workflow leaves a branch with commits from people alone until its pull request is merged or closed. Merging publishes nothing. To run the same comparison locally, use `python3 scripts/sync_openapi.py` and then `bash scripts/generate.sh`.
Every night the `Sync API spec` workflow compares `openapi.json` with production (`scripts/sync_openapi.py`, kept in step with the one in [geonodecom/sdk-typescript](https://github.com/geonodecom/sdk-typescript)), regenerates the client and keeps one pull request from the integrations bot up to date, on the `bot/openapi-sync` branch. It is labelled `breaking` or `additive` by oasdiff and adds a changelog entry under `[Unreleased]`. Review it like any other pull request; its "Needs attention" section lists what postprocessing could not do on its own, such as a hand edit whose generated code changed. When a breaking change fails the tests, push the fixes to that branch: the workflow leaves a branch with commits from people alone until its pull request is merged or closed. Merging publishes nothing. To run the same comparison locally, use `python3 scripts/sync_openapi.py` and then `bash scripts/generate.sh`.

## Reports and releases

Expand Down
7 changes: 7 additions & 0 deletions scripts/generate.sh
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,13 @@ filtered_spec="$(mktemp)"
trap 'rm -f "$filtered_spec"' EXIT
"${postprocess_cmd[@]}" "$repo_root/openapi-generator/filter_spec.py" "$spec_file" "$filtered_spec"

# The generator never deletes files, so modules the API dropped would linger; both folders are fully generated.
if grep -qE '^/?geonode_scraper_sdk/(api|models)/' "$ignore_file"; then
printf '%s protects files in geonode_scraper_sdk/api or models, which this script deletes.\n' "$ignore_file" >&2
exit 1
fi
rm -rf "$sdk_dir/geonode_scraper_sdk/api" "$sdk_dir/geonode_scraper_sdk/models"

# The API labels each request by the client named here (scraper-api#674); the token must
# stay in the API's allowlist (app/shared/client_label.py).
http_user_agent="geonode-python-sdk/${sdk_version}"
Expand Down
31 changes: 29 additions & 2 deletions scripts/postprocess_generated.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,15 @@

from __future__ import annotations

import os
from functools import partial
from pathlib import Path
from typing import Callable

REPO_ROOT = Path(__file__).resolve().parents[1]
SDK_DIR = REPO_ROOT
# Set by the nightly sync: problems that would stop generation become notes for its pull request instead.
SYNC_NOTES = os.environ.get("SYNC_NOTES")


def text(*parts: str) -> str:
Expand Down Expand Up @@ -156,9 +161,27 @@ def main() -> None:
],
}

notes: list[str] = []

def problem(message: str) -> None:
if not SYNC_NOTES:
raise RuntimeError(message)
print(f"WARNING: {message}")
notes.append(message)

def run(path: Path, edit: Callable[[], bool]) -> None:
relative = path.relative_to(REPO_ROOT)
if not path.exists():
problem(f"`{relative}` is no longer generated; remove its edits from scripts/postprocess_generated.py.")
return
try:
if edit():
changed_files.append(path)
except RuntimeError as exc:
problem(f"`{relative}`: {exc}; the generated code changed, update scripts/postprocess_generated.py.")

for path, replacements in replacement_map.items():
if apply_replacements(path, replacements):
changed_files.append(path)
run(path, partial(apply_replacements, path, replacements))

# The generator leaves trailing spaces and blank lines; trimming them keeps regeneration diffs to real changes.
trimmed = sum(normalize_whitespace(path) for path in sorted((SDK_DIR / "geonode_scraper_sdk").rglob("*.py")))
Expand All @@ -172,6 +195,10 @@ def main() -> None:
else:
print("Generated Python SDK files already normalized.")

if SYNC_NOTES and notes:
with open(SYNC_NOTES, "a", encoding="utf-8") as fh:
fh.writelines(f"- {note}\n" for note in notes)


if __name__ == "__main__":
main()
6 changes: 3 additions & 3 deletions scripts/sync_openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ def compare(old: dict, new: dict) -> SpecDiff:


def changelog_entry(diff: SpecDiff) -> list[str]:
# No date here: the same spec must give the same commit on any night, so an unchanged sync pull request is left alone.
# No date here: the same spec must give the same commit every night, so an open sync PR is left alone.
lines = ["- Synced with the production API spec."]
listed = False
for attr, _, label in _ROWS:
Expand Down Expand Up @@ -224,8 +224,8 @@ def summary_markdown(diff: SpecDiff, source: str, date: str) -> str:
"",
"- CI runs on this pull request. If a breaking change fails the tests, fix them in this branch: "
"the nightly sync does not overwrite commits pushed by people.",
"- Removed parameters or fields can break `geonode-scraper-tools-core`, which calls this SDK. "
"Release a fixed tools-core before releasing this SDK.",
"- Removed parameters or fields break code that calls this SDK, including our packages built on it "
"(for the Python SDK, `geonode-scraper-tools-core`). Release fixed versions of those first.",
"- Merging publishes nothing. A release is a separate version pull request and the manual Publish workflow.",
"",
]
Expand Down
50 changes: 50 additions & 0 deletions tests/test_postprocess.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import importlib.util
import sys
from pathlib import Path

import pytest

SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "postprocess_generated.py"


@pytest.fixture(scope="module")
def pp():
spec = importlib.util.spec_from_file_location("postprocess_generated", 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
def bare_tree(pp, tmp_path, monkeypatch):
# One edited file is generated but no longer matches; the other two are not generated at all.
path = tmp_path / "geonode_scraper_sdk/models/extract_request.py"
path.parent.mkdir(parents=True)
path.write_text("class ExtractRequest:\n pass\n")
monkeypatch.setattr(pp, "REPO_ROOT", tmp_path)
monkeypatch.setattr(pp, "SDK_DIR", tmp_path)
return tmp_path


def test_without_sync_notes_a_problem_is_an_error(pp, bare_tree, monkeypatch):
monkeypatch.setattr(pp, "SYNC_NOTES", None)

with pytest.raises(RuntimeError, match="extract_request.py`: Unable to find expected generated snippet"):
pp.main()


def test_with_sync_notes_problems_become_notes(pp, bare_tree, monkeypatch):
notes = bare_tree / "notes.md"
monkeypatch.setattr(pp, "SYNC_NOTES", str(notes))

pp.main()

text = notes.read_text()
assert "`geonode_scraper_sdk/models/extract_request.py`: Unable to find expected generated snippet" in text
assert "`geonode_scraper_sdk/models/proxy_settings.py` is no longer generated" in text
assert "`geonode_scraper_sdk/api/extraction_api.py` is no longer generated" in text
assert (bare_tree / "geonode_scraper_sdk/models/extract_request.py").read_text() == (
"class ExtractRequest:\n pass\n"
)
Loading