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
173 changes: 173 additions & 0 deletions .github/scripts/trigger_readthedocs.py
Original file line number Diff line number Diff line change
@@ -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())
41 changes: 41 additions & 0 deletions .github/workflows/readthedocs.yml
Original file line number Diff line number Diff line change
@@ -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
26 changes: 25 additions & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
10 changes: 9 additions & 1 deletion .readthedocs.yaml
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# Read the Docs build configuration.
# https://docs.readthedocs.com/platform/stable/config-file/v2.html
version: 2

build:
Expand All @@ -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: .
Empty file added docs/_static/.gitkeep
Empty file.
15 changes: 14 additions & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
1 change: 1 addition & 0 deletions docs/requirements.txt
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading