diff --git a/.github/scripts/trigger_readthedocs.py b/.github/scripts/trigger_readthedocs.py new file mode 100644 index 0000000..5a992f6 --- /dev/null +++ b/.github/scripts/trigger_readthedocs.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +"""Trigger a Read the Docs build for the gnews project. + +Master pushes build the ``latest`` version. Published releases and git tags +build the matching version slug. Exits 0 when ``READTHEDOCS_TOKEN`` is unset +so forks and unconfigured checkouts do not fail CI. +""" + +from __future__ import annotations + +import json +import os +import re +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + +PROJECT_SLUG = "gnews" +API_ROOT = f"https://readthedocs.org/api/v3/projects/{PROJECT_SLUG}" +# RTD syncs versions in the background. A public repo usually shows up well +# inside this window; past it, the GitHub integration needs a manual resync. +VERSION_SYNC_ATTEMPTS = 18 +VERSION_SYNC_INTERVAL_SECONDS = 5 + + +def version_slug(source: str) -> str: + """Approximate Read the Docs' version slug for a tag or branch name. + + Slashes and a few other URL-breaking characters become dashes, the result + is lowercased, and dots/underscores are preserved (``0.8.3`` stays + ``0.8.3``, ``release/1.0`` becomes ``release-1.0``). + """ + normalized = re.sub(r"[/%!?]", "-", source).lower() + slug = re.sub(r"[^a-z0-9._-]+", "-", normalized) + slug = re.sub(r"-{2,}", "-", slug).strip("-._") + return slug or "unknown" + + +def resolve_slug( + event: str, + ref_type: str, + ref_name: str, + release_tag: str, + requested_version: str = "", +) -> str: + """Return the RTD version slug this GitHub event should build.""" + # workflow_dispatch passes an explicit slug. GITHUB_REF_NAME is the branch + # the workflow was run from (usually master), which is not a docs version. + if event == "workflow_dispatch": + name = requested_version.strip() or "latest" + return "latest" if name == "latest" else version_slug(name) + if event == "push" and ref_type != "tag": + return "latest" + if event == "release": + name = release_tag or ref_name + elif event == "push" and ref_type == "tag": + name = ref_name + else: + raise SystemExit(f"Unsupported GitHub event {event!r}; not triggering a build.") + + if not name: + raise SystemExit("No tag name on this event; not triggering a build.") + return version_slug(name) + + +def _request(token: str, method: str, path: str, body: dict | None = None) -> tuple[int, object]: + url = API_ROOT + path + data = None if body is None else json.dumps(body).encode() + request = urllib.request.Request(url, data=data, method=method) + request.add_header("Authorization", f"Token {token}") + request.add_header("Accept", "application/json") + if data is not None: + request.add_header("Content-Type", "application/json") + try: + with urllib.request.urlopen(request, timeout=60) as response: + raw = response.read().decode() + payload: object = json.loads(raw) if raw else None + return response.status, payload + except urllib.error.HTTPError as exc: + raw = exc.read().decode(errors="replace") + try: + payload = json.loads(raw) if raw else None + except json.JSONDecodeError: + payload = raw + return exc.code, payload + + +def _version_path(slug: str) -> str: + return "/versions/" + urllib.parse.quote(slug, safe="._-") + "/" + + +def trigger_build(token: str, slug: str) -> tuple[int, object]: + return _request(token, "POST", _version_path(slug) + "builds/") + + +def wait_for_version(token: str, slug: str) -> dict | None: + path = _version_path(slug) + for attempt in range(1, VERSION_SYNC_ATTEMPTS + 1): + status, payload = _request(token, "GET", path) + if status == 200 and isinstance(payload, dict): + return payload + if status != 404: + print(f"Unexpected response looking up {slug} (HTTP {status}): {payload}") + return None + print(f"Version {slug} not visible yet (attempt {attempt}/{VERSION_SYNC_ATTEMPTS}).") + if attempt != VERSION_SYNC_ATTEMPTS: + time.sleep(VERSION_SYNC_INTERVAL_SECONDS) + return None + + +def _report_trigger(slug: str, status: int, payload: object) -> int: + if status == 202: + build_id = None + if isinstance(payload, dict): + build = payload.get("build") + if isinstance(build, dict): + build_id = build.get("id") + if build_id is not None: + print(f"Triggered Read the Docs build {build_id} for version {slug}.") + else: + print(f"Triggered Read the Docs build for version {slug}.") + return 0 + print(f"Failed to trigger version {slug} (HTTP {status}): {payload}") + return 1 + + +def main() -> int: + token = os.environ.get("READTHEDOCS_TOKEN", "").strip() + if not token: + print("READTHEDOCS_TOKEN is not set; skipping Read the Docs build trigger.") + return 0 + + slug = resolve_slug( + os.environ.get("GITHUB_EVENT_NAME", ""), + os.environ.get("GITHUB_REF_TYPE", ""), + os.environ.get("GITHUB_REF_NAME", ""), + os.environ.get("RELEASE_TAG", ""), + os.environ.get("RTD_VERSION", ""), + ) + print(f"Read the Docs target version: {slug}") + + if slug != "latest": + # A new tag is not a version until RTD syncs the repo. The webhook that + # normally does this is what we are replacing, so sync explicitly. + status, payload = _request(token, "POST", "/sync-versions/") + if status != 202: + print(f"Version sync failed (HTTP {status}): {payload}") + return 1 + version = wait_for_version(token, slug) + if version is None: + print( + f"Version {slug!r} did not appear after syncing. Reconnect the " + "GitHub integration on the Read the Docs project and resync versions." + ) + return 1 + if not version.get("active"): + # Activating an inactive version queues its build. POSTing a build + # against an inactive version returns 400. + status, payload = _request(token, "PATCH", _version_path(slug), {"active": True}) + if status not in (200, 204): + print(f"Activating version {slug} failed (HTTP {status}): {payload}") + return 1 + print(f"Activated {slug}; Read the Docs builds a version when it is activated.") + return 0 + + status, payload = trigger_build(token, slug) + return _report_trigger(slug, status, payload) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/workflows/readthedocs.yml b/.github/workflows/readthedocs.yml new file mode 100644 index 0000000..0ae6566 --- /dev/null +++ b/.github/workflows/readthedocs.yml @@ -0,0 +1,41 @@ +# Build https://gnews.readthedocs.io when master or a release tag moves. +# The GitHub → Read the Docs webhook has stopped firing, so this calls the +# RTD API directly. It does nothing when READTHEDOCS_TOKEN is not configured. +name: Trigger Read the Docs + +on: + push: + branches: + - master + tags: + - "**" + release: + types: + - published + # Manual run after the READTHEDOCS_TOKEN secret is added. + workflow_dispatch: + inputs: + version: + description: Read the Docs version slug to build + required: false + default: latest + type: string + +permissions: + contents: read + +jobs: + trigger: + name: Trigger documentation build + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Trigger Read the Docs build + env: + READTHEDOCS_TOKEN: ${{ secrets.READTHEDOCS_TOKEN }} + # Empty on push events. On release events this is the published tag. + RELEASE_TAG: ${{ github.event.release.tag_name }} + RTD_VERSION: ${{ github.event_name == 'workflow_dispatch' && inputs.version || '' }} + run: python3 .github/scripts/trigger_readthedocs.py diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index ad66e71..544940d 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -34,4 +34,28 @@ jobs: - name: Run test cases run: | - python -m pytest tests/test_gnews.py tests/test_searchapi_backend.py tests/test_exceptions.py tests/test_export.py tests/test_logging.py tests/test_fulltext.py -v + python -m pytest tests/test_gnews.py tests/test_searchapi_backend.py tests/test_exceptions.py tests/test_export.py tests/test_logging.py tests/test_fulltext.py tests/test_readthedocs_trigger.py -v + + docs: + name: Build documentation + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + # Same interpreter as .readthedocs.yaml. + python-version: "3.11" + + - name: Install documentation dependencies + run: | + python -m pip install --upgrade pip + pip install -r docs/requirements.txt + pip install . + + - name: Build docs + run: | + sphinx-build -W --keep-going -b html docs docs/_build/html + test -f docs/_build/html/usage/proxies.html diff --git a/.readthedocs.yaml b/.readthedocs.yaml index 469cc64..5da0440 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -1,3 +1,5 @@ +# Read the Docs build configuration. +# https://docs.readthedocs.com/platform/stable/config-file/v2.html version: 2 build: @@ -7,8 +9,14 @@ build: sphinx: configuration: docs/conf.py + # Match a local `sphinx-build -W` run so broken references fail the hosted build. + fail_on_warning: true python: install: + # Sphinx, the RTD theme, and MyST (required for the Markdown pages). - requirements: docs/requirements.txt - - requirements: requirements.txt + # Install the package itself so autodoc/viewcode can import gnews. + # setup.py pulls runtime dependencies from requirements.txt. + - method: pip + path: . diff --git a/docs/_static/.gitkeep b/docs/_static/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/docs/conf.py b/docs/conf.py index 3db40a2..769617e 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,7 +1,20 @@ +from pathlib import Path + project = "GNews" copyright = "2026, Muhammad Abdullah" author = "Muhammad Abdullah" -release = "0.8.2" + +# Keep the docs version aligned with the package so a release bump cannot +# leave /en/latest/ advertising an older release. +_setup_py = Path(__file__).resolve().parent.parent.joinpath("setup.py").read_text(encoding="utf-8") +release = None +for _line in _setup_py.splitlines(): + _stripped = _line.strip() + if _stripped.startswith("version=") or _stripped.startswith("version ="): + release = _stripped.split("=", 1)[1].strip().strip(",").strip("'\"") + break +if not release: + raise RuntimeError("Could not read version from setup.py") extensions = [ "myst_parser", diff --git a/docs/requirements.txt b/docs/requirements.txt index 60f5e99..03874d7 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -1,3 +1,4 @@ sphinx>=7.0 sphinx-rtd-theme>=2.0 +# MyST parses the Markdown sources under docs/ (including usage/proxies.md). myst-parser>=2.0 diff --git a/tests/test_readthedocs_trigger.py b/tests/test_readthedocs_trigger.py new file mode 100644 index 0000000..544587d --- /dev/null +++ b/tests/test_readthedocs_trigger.py @@ -0,0 +1,120 @@ +"""Decision table for the Read the Docs trigger script.""" + +import importlib.util +from pathlib import Path + +import pytest + +_SCRIPT = Path(__file__).resolve().parents[1] / ".github" / "scripts" / "trigger_readthedocs.py" + + +def _load(): + spec = importlib.util.spec_from_file_location("trigger_readthedocs", _SCRIPT) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_version_slug_matches_readthedocs_rules(): + module = _load() + assert module.version_slug("0.8.3") == "0.8.3" + assert module.version_slug("v0.8.3") == "v0.8.3" + assert module.version_slug("docs/readthedocs") == "docs-readthedocs" + assert module.version_slug("Asto7-master") == "asto7-master" + assert module.version_slug("release/1.0") == "release-1.0" + + +def test_master_push_targets_latest(): + module = _load() + assert module.resolve_slug("push", "branch", "master", "") == "latest" + + +def test_tag_and_release_target_the_tag_slug(): + module = _load() + assert module.resolve_slug("push", "tag", "0.8.3", "") == "0.8.3" + assert module.resolve_slug("release", "tag", "ignored", "v1.2.3") == "v1.2.3" + + +def test_workflow_dispatch_uses_the_requested_version_not_the_branch(): + module = _load() + assert module.resolve_slug("workflow_dispatch", "branch", "master", "", "latest") == "latest" + assert module.resolve_slug("workflow_dispatch", "branch", "master", "", "0.8.3") == "0.8.3" + + +def test_missing_token_skips(monkeypatch, capsys): + monkeypatch.delenv("READTHEDOCS_TOKEN", raising=False) + module = _load() + assert module.main() == 0 + assert "skipping" in capsys.readouterr().out.lower() + + +def test_latest_only_posts_a_build(monkeypatch): + monkeypatch.setenv("READTHEDOCS_TOKEN", "token") + monkeypatch.setenv("GITHUB_EVENT_NAME", "push") + monkeypatch.setenv("GITHUB_REF_TYPE", "branch") + monkeypatch.setenv("GITHUB_REF_NAME", "master") + module = _load() + calls = [] + + def fake_request(token, method, path, body=None): + calls.append((method, path, body)) + return 202, {"build": {"id": 42}} + + monkeypatch.setattr(module, "_request", fake_request) + assert module.main() == 0 + assert calls == [("POST", "/versions/latest/builds/", None)] + + +def test_inactive_tag_is_activated_instead_of_posted(monkeypatch): + monkeypatch.setenv("READTHEDOCS_TOKEN", "token") + monkeypatch.setenv("GITHUB_EVENT_NAME", "release") + monkeypatch.setenv("RELEASE_TAG", "0.8.3") + module = _load() + calls = [] + responses = [ + (202, {}), + (200, {"active": False}), + (200, {"active": True}), + ] + + def fake_request(token, method, path, body=None): + calls.append((method, path, body)) + return responses.pop(0) + + monkeypatch.setattr(module, "_request", fake_request) + assert module.main() == 0 + assert calls == [ + ("POST", "/sync-versions/", None), + ("GET", "/versions/0.8.3/", None), + ("PATCH", "/versions/0.8.3/", {"active": True}), + ] + + +def test_active_tag_posts_a_build(monkeypatch): + monkeypatch.setenv("READTHEDOCS_TOKEN", "token") + monkeypatch.setenv("GITHUB_EVENT_NAME", "push") + monkeypatch.setenv("GITHUB_REF_TYPE", "tag") + monkeypatch.setenv("GITHUB_REF_NAME", "v0.8.3") + module = _load() + calls = [] + responses = [ + (202, {}), + (200, {"active": True}), + (202, {"build": {"id": 7}}), + ] + + def fake_request(token, method, path, body=None): + calls.append((method, path, body)) + return responses.pop(0) + + monkeypatch.setattr(module, "_request", fake_request) + assert module.main() == 0 + assert calls[-1] == ("POST", "/versions/v0.8.3/builds/", None) + + +def test_unsupported_event_exits(monkeypatch): + monkeypatch.setenv("READTHEDOCS_TOKEN", "token") + monkeypatch.setenv("GITHUB_EVENT_NAME", "issues") + module = _load() + with pytest.raises(SystemExit): + module.main()