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
111 changes: 111 additions & 0 deletions .github/docs_root_redirects.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""Keep the docs site's pre-versioning URLs working.

The site is published with mike: each version lives in its own directory (``X.Y/``, ``latest/``,
``main/``). Links from before versioning point at the site root (``/hilda/guides/x/``), in
the README, on PyPI and around the web. Run against a checkout of the gh-pages branch just before it
is deployed, this script

- writes a redirect at each of those addresses to the same page of the default version (``latest``,
or ``main`` before the first versioned release), keeping any ``#anchor``;
- writes a root 404 page that redirects any other unversioned path the same way;
- copies ``llms.txt`` and ``llms-full.txt`` to the root, where agents look for them.

Nothing is committed: the files exist only in the deployed site.

Usage: python3 .github/docs_root_redirects.py SITE_DIR [--base /hilda/]
"""

import argparse
import html
import json
import os
import shutil
from pathlib import Path

DEFAULT_ALIAS = "latest"
ROOT_FILES = ("llms.txt", "llms-full.txt")

REDIRECT_PAGE = """<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Redirecting…</title>
<link rel="canonical" href="{href}">
<meta http-equiv="refresh" content="0; url={href}">
<script>location.replace({js_href} + location.search + location.hash);</script>
</head>
<body><a href="{href}">This page moved to {href}</a></body>
</html>
"""

NOT_FOUND_PAGE = """<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Page not found</title>
<script>
(function () {{
var base = {js_base}, target = {js_target}, versions = {js_versions};
var path = location.pathname;
if (path.indexOf(base) !== 0) return;
var rest = path.slice(base.length);
// A path from before the site was versioned: the same page of the default version.
if (versions.indexOf(rest.split("/")[0]) === -1) {{
location.replace(base + target + "/" + rest + location.search + location.hash);
}}
}})();
</script>
</head>
<body><p>Page not found. <a href="{href}">Go to the documentation.</a></p></body>
</html>
"""


def default_version(versions: list[dict]) -> str:
if any(DEFAULT_ALIAS in entry.get("aliases", []) for entry in versions):
return DEFAULT_ALIAS
# Before the first versioned release only the main branch is published.
return versions[0]["version"]


def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("site", type=Path, help="Checkout of the gh-pages branch")
parser.add_argument("--base", default="/hilda/", help="URL path the site is served under")
args = parser.parse_args()

site: Path = args.site
versions = json.loads((site / "versions.json").read_text())
target = default_version(versions)
names = sorted({entry["version"] for entry in versions} | {a for entry in versions for a in entry["aliases"]})
source = site / target

redirects = 0
for page in source.rglob("index.html"):
relative = page.relative_to(source)
if relative.parts[0] in names:
continue
destination = site / relative
href = os.path.relpath(page.parent, destination.parent).replace(os.sep, "/") + "/"
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_text(REDIRECT_PAGE.format(href=html.escape(href), js_href=json.dumps(href)))
redirects += 1

(site / "404.html").write_text(
NOT_FOUND_PAGE.format(
js_base=json.dumps(args.base),
js_target=json.dumps(target),
js_versions=json.dumps(names),
href=html.escape(f"{args.base}{target}/"),
)
)
for name in ROOT_FILES:
if (source / name).exists():
shutil.copyfile(source / name, site / name)

print(f"{redirects} root redirects to {target}/, plus 404.html and {', '.join(ROOT_FILES)}")


if __name__ == "__main__":
main()
79 changes: 72 additions & 7 deletions .github/workflows/docs.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
name: docs

# The site is versioned with mike, which keeps every published version in the gh-pages branch:
# - a push to main publishes `main`;
# - a release publishes its X.Y series and moves the `latest` alias (the default) to it.
# The whole gh-pages tree is then deployed to GitHub Pages, plus root redirects that keep the
# pre-versioning URLs working (.github/docs_root_redirects.py). The github-pages environment only
# accepts deployments from main, so a release run publishes to gh-pages and then starts this
# workflow on main, which deploys.

on:
push:
branches: [main]
Expand All @@ -8,20 +16,26 @@ on:
- "mkdocs.yml"
- "overrides/**"
- "hilda/**"
- ".github/docs_root_redirects.py"
- ".github/workflows/docs.yml"
pull_request:
paths:
- "docs/**"
- "mkdocs.yml"
- "overrides/**"
- ".github/docs_root_redirects.py"
- ".github/workflows/docs.yml"
release:
types: [published]
workflow_dispatch:

permissions:
contents: read

jobs:
build:
# Pull requests only check that the site builds; publishing builds it again with mike.
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
Expand All @@ -33,18 +47,69 @@ jobs:
- name: Install
run: |
python -m pip install --upgrade pip
python -m pip install "mkdocs-material>=9.5" "mkdocstrings[python]>=0.26" "mkdocs-llmstxt>=0.5"
python -m pip install "mkdocs-material>=9.5" "mkdocstrings[python]>=0.26" "mkdocs-llmstxt>=0.5" "mike>=2.1"
- name: Build (strict)
run: python -m mkdocs build --strict
- name: Upload site artifact
if: github.ref == 'refs/heads/main'
uses: actions/upload-pages-artifact@v3

publish:
if: github.event_name != 'pull_request'
runs-on: ubuntu-latest
# mike pushes to gh-pages: one publish at a time, none cancelled half-way.
concurrency:
group: docs-publish
cancel-in-progress: false
permissions:
contents: write
actions: write
steps:
- uses: actions/checkout@v4
with:
# mike commits on top of the gh-pages branch.
fetch-depth: 0
- uses: actions/setup-python@v5
with:
python-version: "3.12"
# mkdocstrings analyzes the source statically (paths: [.]), so the hilda
# package itself does not need to be installed — only the doc tooling.
- name: Install
run: |
python -m pip install --upgrade pip
python -m pip install "mkdocs-material>=9.5" "mkdocstrings[python]>=0.26" "mkdocs-llmstxt>=0.5" "mike>=2.1"
- name: Build (strict)
run: python -m mkdocs build --strict
- name: Publish with mike
env:
EVENT: ${{ github.event_name }}
TAG: ${{ github.event.release.tag_name }}
run: |
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git fetch origin gh-pages:gh-pages || true
if [ "$EVENT" = "release" ]; then
series="$(echo "${TAG#v}" | cut -d. -f1,2)"
mike deploy --push --update-aliases "$series" latest
mike set-default --push latest
else
mike deploy --push main
fi
- name: Deploy from main
if: github.event_name == 'release'
env:
GH_TOKEN: ${{ github.token }}
run: gh workflow run docs.yml --repo "$GITHUB_REPOSITORY" --ref main
- name: Assemble the site
if: github.event_name != 'release'
run: |
git worktree add --detach "$RUNNER_TEMP/site" gh-pages
python .github/docs_root_redirects.py "$RUNNER_TEMP/site"
- uses: actions/upload-pages-artifact@v3
if: github.event_name != 'release'
with:
path: site
path: ${{ runner.temp }}/site

deploy:
if: github.ref == 'refs/heads/main'
needs: build
needs: publish
if: github.event_name != 'release'
runs-on: ubuntu-latest
permissions:
pages: write
Expand Down
11 changes: 11 additions & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ extra_css:

plugins:
- search
# One site per release series, published by .github/workflows/docs.yml: X.Y for each release,
# `latest` for the newest release (the default), `main` for the main branch.
- mike:
alias_type: copy
canonical_version: latest
- mkdocstrings:
handlers:
python:
Expand Down Expand Up @@ -117,3 +122,9 @@ nav:
- Symbols & Objective-C: api/symbols.md
- Breakpoints & watchpoints: api/breakpoints.md
- Exceptions: api/exceptions.md

extra:
version:
provider: mike
default: latest
alias: true
9 changes: 8 additions & 1 deletion overrides/main.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
{#- Site-wide Open Graph / Twitter card so shared links preview the social card. -#}
{% block extrahead %}
{% set page_title = (page.title ~ " - " ~ config.site_name) if (page and page.title and not page.is_homepage) else config.site_name %}
{% set image = config.site_url ~ "assets/social-card.png" %}
{#- mike's canonical_version leaves site_url without its trailing slash. -#}
{% set image = config.site_url.rstrip("/") ~ "/assets/social-card.png" %}
<meta property="og:type" content="website">
<meta property="og:title" content="{{ page_title }}">
<meta property="og:description" content="{{ config.site_description }}">
Expand All @@ -16,3 +17,9 @@
<meta name="twitter:description" content="{{ config.site_description }}">
<meta name="twitter:image" content="{{ image }}">
{% endblock %}

{#- Shown on every version except the default one (`latest`): `main` and older releases. -#}
{% block outdated %}
This is not the documentation of the latest release.
<a href="{{ '../' ~ base_url }}"><strong>Go to the latest release.</strong></a>
{% endblock %}
Loading