diff --git a/.coderabbit.yaml b/.coderabbit.yaml index e16b260..8497fb9 100644 --- a/.coderabbit.yaml +++ b/.coderabbit.yaml @@ -16,6 +16,26 @@ reviews: auto_review: enabled: true drafts: false + path_instructions: + - path: "**" + instructions: | + Outside .github/workflows/ (see the next entry): build tooling for a static docs site. It runs on a developer machine or in this + repo's CI, never as a service, and has no consumers outside this repo. Its inputs are + trusted (see SECURITY.md): etc/docsite.yaml, INFRA_* environment overrides, and the + llm-works package repositories it fetches. Do not flag missing validation of those + inputs (paths, names, refs, symlinks, renames), and do not ask for backward + compatibility of the config or CLI. Report bugs that break the build or the published + site for the content it actually publishes; skip Markdown edge cases that do not occur + in the package docs. Keep suggestions proportionate: no new validation layers or tests + for hypothetical inputs. + - path: ".github/workflows/**" + instructions: | + Workflows are the exception to the trusted-inputs scope above: they run on GitHub with + tokens and publish the site to GitHub Pages. Review them for security: triggers (no + pull_request_target, no deploy from pull requests), least-privilege permissions per job, + persist-credentials: false, and untrusted values (PR titles, branch names) reaching run: + scripts. Actions are pinned by version tag, not commit SHA, as .github/zizmor.yml sets + on purpose; do not ask for SHA pins. chat: auto_reply: true diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3b7ae33..7b83c34 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -67,8 +67,94 @@ jobs: run: appinfra cq spdx test: + name: Test (unit, integration) + runs-on: ubuntu-latest + needs: lint + timeout-minutes: 10 + + steps: + - name: Checkout code + uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@v7 + with: + python-version: '3.12' + cache: 'pip' + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + # TODO: remove after appinfra is released to PyPI + python -m pip install "appinfra[check] @ git+https://github.com/llm-works/appinfra.git@develop" + python -m pip install -e ".[dev]" + + - name: Run unit and integration tests + run: python -m pytest tests/ -m "unit or integration" -v --tb=short + + # Builds the site as the deploy does and loads it in a browser: the pages render the header, + # tree and search without a script error. + smoke-site: + name: Smoke (built site) + runs-on: ubuntu-latest + needs: lint + timeout-minutes: 10 + + steps: + - name: Checkout code + uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@v7 + with: + python-version: '3.12' + cache: 'pip' + + - name: Install dependencies and the browser + run: | + python -m pip install --upgrade pip + # TODO: remove after appinfra is released to PyPI + python -m pip install "appinfra[check] @ git+https://github.com/llm-works/appinfra.git@develop" + python -m pip install -e ".[dev]" + python -m playwright install --with-deps chromium + + - name: Build the site + run: | + python -m docsite build + zensical build --clean + + - name: Run the browser smoke test + run: python -m pytest tests/e2e -m e2e -v --tb=short + + # Summary job: the required check, passing when the tests and the site smoke test both do. + test-summary: name: Test runs-on: ubuntu-latest + needs: [test, smoke-site] + if: always() + steps: + - name: Check aggregate status + env: + TEST: ${{ needs.test.result }} + SMOKE: ${{ needs.smoke-site.result }} + run: | + if [[ "$TEST" != "success" ]]; then + echo "Unit and integration tests failed" + exit 1 + fi + if [[ "$SMOKE" != "success" ]]; then + echo "Site smoke test failed" + exit 1 + fi + echo "All tests passed" + + coverage: + name: Coverage + runs-on: ubuntu-latest needs: lint timeout-minutes: 10 @@ -91,7 +177,7 @@ jobs: python -m pip install "appinfra[check] @ git+https://github.com/llm-works/appinfra.git@develop" python -m pip install -e ".[dev]" - - name: Run unit and integration tests with coverage + - name: Run tests with coverage run: >- - python -m pytest tests/ -m "unit or integration" -v --tb=short - --cov=docsite --cov-fail-under=95 --cov-report=term + python -m pytest tests/ -m "unit or integration" --tb=short + --cov=docsite --cov-fail-under=90 --cov-report=term diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..dcec137 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,73 @@ +name: Deploy + +# Builds the site from the committed config and publishes it to GitHub Pages. A push to main +# deploys; a manual run builds the chosen branch and deploys only when that branch is main. +on: + push: + branches: [main] + workflow_dispatch: + +# One run per ref at a time; a running deploy finishes before the next starts. Per ref, so a +# manual build of another branch cannot replace a main run waiting in the queue. +concurrency: + group: pages-${{ github.ref }} + cancel-in-progress: false + +permissions: {} + +jobs: + build: + name: Build + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + + steps: + - name: Checkout code + uses: actions/checkout@v7 + with: + persist-credentials: false + + # No dependency cache: a cache shared with other workflows could feed this publishing build + - name: Set up Python + uses: actions/setup-python@v7 + with: + python-version: '3.12' + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + # appinfra is not on PyPI; a release tag here, never a branch + python -m pip install "appinfra[validation] @ git+https://github.com/llm-works/appinfra.git@v0.15.0" + # editable: the build reads etc/docsite.yaml relative to the docsite sources + python -m pip install -e . + + # The committed etc/docsite.yaml only: each package at its release tag, no INFRA_* overrides + - name: Build the site + run: | + python -m docsite build + zensical build --clean + + - name: Upload the site + uses: actions/upload-pages-artifact@v5 + with: + path: site + + deploy: + name: Deploy + needs: build + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v5 diff --git a/docsite/build.py b/docsite/build.py index 51baf56..baf8ee2 100644 --- a/docsite/build.py +++ b/docsite/build.py @@ -17,7 +17,7 @@ from .reference import reference_modules, reference_nav, reference_pages from .siteconf import render_site_config from .sitenav import render_header -from .stage import DocsStager, Source, StageError, merge, sync_tree +from .stage import DocsStager, Source, StageError, merge, sync_tree, text_pages NAV_SOURCE = "nav.html" # Where fetch saves the brand stylesheets in build_dir, and where stage puts them in docs_dir @@ -69,7 +69,7 @@ def stage(self) -> None: def _stage_package(self, pkg: Package, stager: DocsStager, plan: dict[str, Source]) -> None: """Add a package's docs, its reference and its generated section pages to `plan`.""" checkout = self._cfg.site.build_dir / pkg.name - files = link_to_repo(self._lg, pkg, checkout, stager.files(pkg, checkout)) + files = text_pages(link_to_repo(self._lg, pkg, checkout, stager.files(pkg, checkout))) merge(plan, {f"{pkg.name}/{path}": src for path, src in files.items()}, pkg.name) modules = self._reference_modules(pkg) if modules is not None: diff --git a/docsite/links.py b/docsite/links.py index 328d2ab..6b34f82 100644 --- a/docsite/links.py +++ b/docsite/links.py @@ -33,6 +33,7 @@ # An inline code span: a run of backticks to the next run of the same length _CODE_SPAN = re.compile(r"(`+).+?(? str | None: @@ -91,7 +92,11 @@ def _url(self, target: str, doc_dir: str) -> str | None: inside = path == self.docs_root or path.startswith(self.docs_root + "/") if inside or path.startswith("../") or path == ".." or path not in self.paths: return None - return f"{self.base}/{quote(path)}{raw[cut:]}" + rest = raw[cut:] + if path.lower().endswith(_IMAGES): + # A blob URL is GitHub's page for the file; raw=true redirects to the image itself + rest = "?raw=true" + ("&" + rest[1:] if rest.startswith("?") else rest) + return f"{self.base}/{quote(path)}{rest}" def link_to_repo( diff --git a/docsite/stage.py b/docsite/stage.py index b931c8c..12cd228 100644 --- a/docsite/stage.py +++ b/docsite/stage.py @@ -5,7 +5,7 @@ from collections.abc import Iterable, Mapping, Sequence from dataclasses import dataclass -from pathlib import Path +from pathlib import Path, PurePosixPath from appinfra.log import Logger @@ -59,6 +59,23 @@ def files(self, pkg: Package, checkout: Path) -> dict[str, Path]: return {pkg.site_path(path): source / path for path in sel.copy} +def text_pages(files: Mapping[str, Source]) -> dict[str, Source]: + """`files`, with each plain-text file staged under a .md name (a rename, e.g. LICENSE to + license.md) made a page: its name as the title, its text unchanged in a code block.""" + pages: dict[str, Source] = {} + for path, src in files.items(): + if path.endswith(".md") and isinstance(src, Path) and src.suffix != ".md": + title = PurePosixPath(path).stem.replace("-", " ").capitalize() + src = text_page(title, src.read_text(encoding="utf-8")) + pages[path] = src + return pages + + +def text_page(title: str, text: str) -> str: + """Markdown for a page that shows `text` as it is, under the heading `title`.""" + return f"# {title}\n\n```text\n{text.rstrip()}\n```\n" + + def merge(plan: dict[str, Source], files: Mapping[str, Source], owner: str) -> None: """Add `files` to `plan`; a path that is already taken is an error, never an overwrite.""" taken = sorted(plan.keys() & files.keys()) diff --git a/etc/docsite.yaml b/etc/docsite.yaml index 429a54d..c1f54be 100644 --- a/etc/docsite.yaml +++ b/etc/docsite.yaml @@ -57,6 +57,8 @@ packages: # Zensical takes a README.md as the folder's index, which is the landing page here rename: README.md: user-guide.md + # A plain-text file renamed to .md is published as a page, its text in a code block + LICENSE: license.md # Generated from the docstrings at the ref: one page per top-level module of appinfra/ reference: package: appinfra diff --git a/pyproject.toml b/pyproject.toml index 91238b9..eaf7082 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,6 +39,11 @@ dependencies = [ dev = [ # check: ruff, mypy, pytest, pytest-cov, pytest-xdist and the make check tooling "appinfra[check]>=0.14.0", + # the browser smoke test of the built site (tests/e2e); its browser is installed separately + "pytest-playwright>=0.7", + # gives pytest-playwright its base_url fixture; without it the plugin's own fallback warns + # under pytest 9 (session fixture defined as an instance method) + "pytest-base-url>=2.1", ] [project.urls] diff --git a/tests/e2e/__init__.py b/tests/e2e/__init__.py new file mode 100644 index 0000000..7bd7114 --- /dev/null +++ b/tests/e2e/__init__.py @@ -0,0 +1,2 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors diff --git a/tests/e2e/test_site_smoke.py b/tests/e2e/test_site_smoke.py new file mode 100644 index 0000000..5a2054c --- /dev/null +++ b/tests/e2e/test_site_smoke.py @@ -0,0 +1,52 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""The built site in a browser: pages load without script errors, with header, tree and search. + +Runs against site/ from `make build`; skipped without it or without Playwright installed +(`python -m playwright install chromium` gets the browser). +""" + +import threading +from collections.abc import Iterator +from functools import partial +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +import pytest + +pytest.importorskip("pytest_playwright") + +from playwright.sync_api import Page, expect # noqa: E402 + +SITE = Path(__file__).resolve().parents[2] / "site" + + +class _QuietHandler(SimpleHTTPRequestHandler): + def log_message(self, format: str, *args: object) -> None: + """No request log on stderr.""" + + +@pytest.fixture(scope="module") +def site_url() -> Iterator[str]: + """site/ served on a free local port for the module's tests.""" + if not (SITE / "index.html").is_file(): + pytest.skip("site/ is not built; run `make build`") + server = ThreadingHTTPServer(("127.0.0.1", 0), partial(_QuietHandler, directory=str(SITE))) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + yield f"http://127.0.0.1:{server.server_address[1]}" + server.shutdown() + thread.join() + + +@pytest.mark.parametrize("path", ["", "appinfra/"]) +def test_page_loads_with_header_tree_and_search(page: Page, site_url: str, path: str) -> None: + """The home page and a package page render the shell without a script error.""" + errors: list[str] = [] + page.on("pageerror", lambda error: errors.append(str(error))) + page.goto(f"{site_url}/{path}") + expect(page.locator("nav.site-nav")).to_be_visible() + expect(page.locator("nav.md-nav--primary")).to_be_attached() + expect(page.locator(".md-search")).to_be_attached() + assert errors == [] diff --git a/tests/integration/test_stage_files.py b/tests/integration/test_stage_files.py index d2b8e98..fc69083 100644 --- a/tests/integration/test_stage_files.py +++ b/tests/integration/test_stage_files.py @@ -11,7 +11,7 @@ from appinfra.log import Logger from docsite.config import Package -from docsite.stage import DocsStager, Source, StageError, merge, sync_tree +from docsite.stage import DocsStager, Source, StageError, merge, sync_tree, text_pages def _checkout(root: Path, files: dict[str, str], docs_root: str = "docs") -> Path: @@ -45,6 +45,15 @@ def test_missing_allowlisted_file_fails(lg: Logger, tmp_path: Path) -> None: DocsStager(lg).files(_package("INTRO.md", "gone.md"), checkout) +def test_plain_text_file_renamed_to_markdown_becomes_a_page(tmp_path: Path) -> None: + """LICENSE staged as license.md shows its text as it is, in a code block under a title.""" + (tmp_path / "LICENSE").write_text("Apache License\n 1. Definitions.\n", encoding="utf-8") + (tmp_path / "a.md").write_text("# A\n", encoding="utf-8") + pages = text_pages({"license.md": tmp_path / "LICENSE", "a.md": tmp_path / "a.md"}) + assert pages["license.md"] == "# License\n\n```text\nApache License\n 1. Definitions.\n```\n" + assert pages["a.md"] == tmp_path / "a.md" + + def test_merge_refuses_a_taken_path() -> None: """Two sources for one docs path is an error, never an overwrite.""" plan: dict[str, Source] = {"pkg/index.md": "landing"} diff --git a/tests/unit/test_links.py b/tests/unit/test_links.py index 49ef587..7134992 100644 --- a/tests/unit/test_links.py +++ b/tests/unit/test_links.py @@ -15,6 +15,7 @@ "CHANGELOG.md", "examples", "examples/demo.py", + "examples/demo.png", "pkg", "pkg/docs", "pkg/docs/a.md", @@ -34,6 +35,10 @@ def _rewrite(text: str) -> tuple[str, int]: ("See [it](../../../README.md#install).", f"See [it]({BASE}/README.md#install)."), # Image, and a directory (GitHub redirects a blob URL of a directory to its tree) ("![d](../../../examples/)", f"![d]({BASE}/examples)"), + # An image file: the raw file, not GitHub's page for it + ("![d](../../../examples/demo.png)", f"![d]({BASE}/examples/demo.png?raw=true)"), + # ... joined to a query the link has + ("![d](../../../examples/demo.png?v=2)", f"![d]({BASE}/examples/demo.png?raw=true&v=2)"), # Reference definition ("[readme]: ../../../README.md", f"[readme]: {BASE}/README.md"), ],