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
1 change: 1 addition & 0 deletions .github/workflows/docs-check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ jobs:
- name: Build the docs in strict mode
env:
UV_NO_SYNC: "true"
READTHEDOCS_CANONICAL_URL: ${{ matrix.python-version == '3.15' && 'https://archipy.readthedocs.io/en/latest/' || '' }}
run: make docs-check

- name: Run documentation examples
Expand Down
107 changes: 107 additions & 0 deletions docs/assets/stylesheets/404.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
.md-tabs,
.md-header__button[for="__drawer"] {
display: none;
}

.md-header__button.md-logo {
display: block;
}

.docs-404 {
--md-typeset-a-color: color-mix(in srgb, var(--md-primary-fg-color) 65%, var(--md-default-fg-color));
max-width: 43rem;
margin: clamp(1rem, 5vw, 3.5rem) auto;
}

.docs-404__hero {
padding: clamp(1.2rem, 4vw, 2.5rem);
background: linear-gradient(
145deg,
color-mix(in srgb, var(--md-primary-fg-color) 10%, var(--md-default-bg-color)),
var(--md-default-bg-color)
);
border: 1px solid var(--md-default-fg-color--lightest);
border-radius: 0.8rem;
}

.md-typeset .docs-404__status {
margin: 0 0 0.55rem;
color: var(--md-default-fg-color--light);
font-family: var(--md-code-font-family);
font-size: 0.68rem;
font-weight: 700;
letter-spacing: 0.07em;
}

.md-typeset .docs-404 h1 {
margin: 0;
color: var(--md-default-fg-color);
font-size: clamp(2rem, 6vw, 3.1rem);
font-weight: 700;
letter-spacing: -0.035em;
line-height: 1.1;
}

.docs-404__hero .md-button {
margin-top: 0.35rem;
border-radius: 0.3rem;
}

.md-typeset .docs-404 .md-button--primary {
color: var(--md-primary-bg-color);
background-color: var(--md-primary-fg-color--dark);
border-color: var(--md-primary-fg-color--dark);
}

.docs-404 a:focus-visible {
outline: 2px solid var(--md-typeset-a-color);
outline-offset: 3px;
}

.md-typeset .docs-404 h2 {
margin: 1.65rem 0 0.65rem;
font-size: 1rem;
font-weight: 700;
}

.md-typeset .docs-404 ul.docs-404__links {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 11rem), 1fr));
gap: 0.6rem;
margin: 0;
padding: 0;
list-style: none;
}

.md-typeset ul.docs-404__links > li {
display: flex;
margin: 0;
}

.docs-404__links a {
display: block;
width: 100%;
padding: 0.7rem 0.8rem;
border: 1px solid var(--md-default-fg-color--lightest);
border-radius: 0.4rem;
}

.docs-404__links a:hover,
.docs-404__links a:focus-visible {
border-color: currentColor;
}

.docs-404__links span {
display: block;
margin-top: 0.15rem;
color: var(--md-default-fg-color);
font-size: 0.72rem;
}

.docs-404__report {
font-size: 0.72rem;
}

.docs-404__report a {
text-decoration: underline;
}
59 changes: 30 additions & 29 deletions overrides/404.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,45 +7,46 @@
{% block extrahead %}
{{ super() }}
<meta name="robots" content="noindex">
<link rel="stylesheet" href="{{ 'assets/stylesheets/404.css' | url }}">
{% endblock %}

{% block content %}
<h1>Page not found</h1>
<p>This page may have moved. Use the site search or choose a destination below.</p>
{% block site_nav %}{% endblock %}

<nav id="docs-recovery" aria-label="Find documentation">
<p><a class="md-button md-button--primary" href="{{ '.' | url }}">Documentation home</a></p>
{% block content %}
<div class="docs-404">
<nav id="docs-recovery" aria-label="Find documentation">
<div class="docs-404__hero">
<p class="docs-404__status">HTTP 404</p>
<h1>Page not found</h1>
<p>The link may be out of date. Try searching the docs.</p>
<a class="md-button md-button--primary" href="{{ '.' | url }}">Documentation home</a>
</div>

<h2>Browse the docs</h2>
<div class="grid cards">
<ul>
<li>
<a href="{{ 'getting-started/installation/' | url }}"><strong>Installation</strong></a>
<p>Install ArchiPy and its optional extras.</p>
</li>
<li>
<a href="{{ 'getting-started/quickstart/' | url }}"><strong>Quickstart</strong></a>
<p>Run a small app with Redis caching.</p>
</li>
<li>
<a href="{{ 'getting-started/concepts/' | url }}"><strong>Concepts</strong></a>
<p>Understand the layers and import rules.</p>
</li>
<h2>Browse the docs</h2>
<ul class="docs-404__links">
<li>
<a href="{{ 'tutorials/' | url }}"><strong>Tutorials</strong></a>
<p>Find examples for adapters and helpers.</p>
<a href="{{ 'getting-started/quickstart/' | url }}">
<strong>Quickstart</strong>
<span>Build your first ArchiPy app.</span>
</a>
</li>
<li>
<a href="{{ 'api_reference/' | url }}"><strong>API Reference</strong></a>
<p>Look up public classes and functions.</p>
<a href="{{ 'tutorials/' | url }}">
<strong>Tutorials</strong>
<span>Work with adapters and helpers.</span>
</a>
</li>
<li>
<a href="{{ 'community/faq/' | url }}"><strong>FAQ</strong></a>
<p>Find answers to common questions.</p>
<a href="{{ 'api_reference/' | url }}">
<strong>API Reference</strong>
<span>Look up classes and functions.</span>
</a>
</li>
</ul>
</div>
</nav>
</nav>

<p>Followed a link here? <a href="{{ config.repo_url }}/issues/new?template=documentation_improvement.yml">Report the broken link</a>.</p>
<p class="docs-404__report">
<a href="{{ config.repo_url }}/issues/new?template=documentation_improvement.yml">Report a broken link</a>
</p>
</div>
{% endblock %}
121 changes: 97 additions & 24 deletions scripts/check_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,22 @@

"""Build the documentation and verify the generated error page and redirects."""

import json
import os
import re
import subprocess
import sys
import tomllib
from contextlib import contextmanager
from html.parser import HTMLParser
from pathlib import Path, PurePosixPath
from tempfile import NamedTemporaryFile
from typing import TYPE_CHECKING
from urllib.parse import unquote, urljoin, urlsplit

if TYPE_CHECKING:
from collections.abc import Generator


class PageLinks(HTMLParser):
"""Collect the links needed to verify a generated page."""
Expand All @@ -28,7 +37,10 @@ def __init__(self, source: Path) -> None:
self.refresh: str | None = None
self.links: set[str] = set()
self.recovery_links: set[str] = set()
self.assets: set[str] = set()
self.theme_config = ""
self._in_recovery_navigation = False
self._in_theme_config = False
self.feed(source.read_text(encoding="utf-8"))

def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
Expand All @@ -42,13 +54,26 @@ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None
self.recovery_links.add(href)
if tag == "link" and attributes.get("rel") == "canonical":
self.canonical = attributes.get("href")
if tag == "link" and attributes.get("rel") in {"icon", "stylesheet"} and (href := attributes.get("href")):
self.assets.add(href)
if tag in {"img", "script"} and (src := attributes.get("src")):
self.assets.add(src)
if tag == "script" and attributes.get("id") == "__config":
self._in_theme_config = True
if tag == "meta" and attributes.get("http-equiv") == "refresh":
self.refresh = (attributes.get("content") or "").partition("url=")[2]

def handle_data(self, data: str) -> None:
"""Capture the generated theme settings used by search."""
if self._in_theme_config:
self.theme_config += data

def handle_endtag(self, tag: str) -> None:
"""Stop collecting links at the end of the recovery navigation."""
"""Stop collecting content when its enclosing element ends."""
if tag == "nav":
self._in_recovery_navigation = False
if tag == "script":
self._in_theme_config = False


def markdown_url(path: str, directory_urls: bool) -> str:
Expand All @@ -68,8 +93,30 @@ def site_file(site: Path, site_url: str, url: str) -> Path:
return site / (f"{path}index.html" if not path or path.endswith("/") else path)


def check_404(site: Path, site_url: str) -> None:
"""Verify the custom 404 works when served at a nested missing URL."""
page = PageLinks(site / "404.html")
missing_url = urljoin(site_url, "missing/deep/page/")
destinations = {urljoin(missing_url, href) for href in page.recovery_links}
if site_url not in destinations:
raise SystemExit("Generated 404.html is missing the documentation home link")
for url in sorted(destinations):
if not site_file(site, site_url, url).is_file():
raise SystemExit(f"Broken recovery link in 404.html: {url}")

theme = json.loads(page.theme_config)
search_base = urljoin(missing_url, f"{theme['base'].rstrip('/')}/")
if search_base != site_url:
raise SystemExit(f"Invalid search base in 404.html: {search_base}")
assets = {urljoin(missing_url, asset) for asset in page.assets if not urlsplit(asset).scheme}
assets.update({urljoin(missing_url, theme["search"]), urljoin(search_base, "search.json")})
for url in sorted(assets):
if not site_file(site, site_url, url).is_file():
raise SystemExit(f"Missing asset in 404.html: {url}")


def check_output(config_path: Path) -> None:
"""Verify each page redirect and the custom 404 recovery links."""
"""Verify each page redirect and the custom 404."""
with config_path.open("rb") as file:
project = tomllib.load(file)["project"]
site = config_path.parent / project.get("site_dir", "site")
Expand Down Expand Up @@ -99,32 +146,58 @@ def check_output(config_path: Path) -> None:
):
raise SystemExit(f"Invalid generated redirect: {old} -> {new}")

recovery = PageLinks(site / "404.html").recovery_links
missing_url = urljoin(site_url, "missing/deep/page/")
destinations = {urljoin(missing_url, href) for href in recovery}
if site_url not in destinations:
raise SystemExit("Generated 404.html is missing the documentation home link")
for url in sorted(destinations):
if not site_file(site, site_url, url).is_file():
raise SystemExit(f"Broken recovery link in 404.html: {url}")
print("Verified generated redirects and custom 404 links.")
check_404(site, site_url)
print(f"Verified generated redirects, 404 links, and 404 assets under {site_url}")


@contextmanager
def build_config() -> Generator[Path]:
"""Use the current Read the Docs version URL when building there."""
config = Path("zensical.toml")
site_url = os.environ.get("READTHEDOCS_CANONICAL_URL")
if not site_url:
yield config
return

# Zensical resolves paths relative to the config and does not expand environment variables.
source, replacements = re.subn(
r"^site_url\s*=[^\n]*",
lambda _: f"site_url = {json.dumps(site_url, ensure_ascii=False)}",
config.read_text(encoding="utf-8"),
count=1,
flags=re.MULTILINE,
)
if not replacements:
raise SystemExit(f"Missing site_url in {config}")
with NamedTemporaryFile(
mode="w",
encoding="utf-8",
dir=config.parent,
prefix=".zensical-",
suffix=".toml",
delete_on_close=False,
) as file:
file.write(source)
file.flush()
yield Path(file.name)


def main() -> None:
"""Run a strict build and fail on Griffe diagnostics."""
result = subprocess.run(
[sys.executable, "-m", "zensical", "build", "--clean", "--strict"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
check=False,
)
print(result.stdout, end="")
if result.returncode:
raise SystemExit(result.returncode)
if any(line.startswith("griffe:") for line in result.stdout.splitlines()):
raise SystemExit("Correct the Griffe docstring diagnostics above.")
check_output(Path("zensical.toml"))
with build_config() as config:
result = subprocess.run(
[sys.executable, "-m", "zensical", "build", "--config-file", str(config), "--clean", "--strict"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
check=False,
)
print(result.stdout, end="")
if result.returncode:
raise SystemExit(result.returncode)
if any(line.startswith("griffe:") for line in result.stdout.splitlines()):
raise SystemExit("Correct the Griffe docstring diagnostics above.")
check_output(config)


if __name__ == "__main__":
Expand Down
Loading