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
4 changes: 3 additions & 1 deletion docs/user_guide/09-custom-sections.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -437,9 +437,11 @@ Other files beside the configuration publish only when `site_root.files` lists t

```{.yaml filename="docs/great-docs.yml"}
site_root:
files: [CNAME, api.json, "downloads/*.csv"]
files: [CNAME, api.json, "downloads/*.csv", "scripts/*.py"]
```

For example, `docs/scripts/diff.py` publishes at `/scripts/diff.py`.

List support files beside section pages when code in those pages opens them. For a section
with `dir: examples`, list `examples/01-setup/settings.yml` to publish
`/examples/setup/settings.yml` beside the rendered setup pages. Globs such as
Expand Down
14 changes: 10 additions & 4 deletions great_docs/_build/content.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import shutil
from functools import partial
from glob import has_magic
from typing import TYPE_CHECKING, Any, cast

from .._content import custom_pages as authored_pages
Expand All @@ -31,6 +32,7 @@
from .._website.project_pages import citation, licence, package_info
from . import site
from .facts import source_ref
from .ownership import RENDER_SCRIPTS_DIR
from .steps import Outcome, Skipped, print_warning

if TYPE_CHECKING:
Expand Down Expand Up @@ -784,16 +786,20 @@ def site_root_files(run: Run, config: Config, layout: Layout) -> Outcome:
f"Cannot publish {path} from site_root.files: the build already wrote a "
"different file there. Remove it from the list or rename the file"
) from error
if not files.resources:
paths = files.resources
if not paths:
return Skipped("no files")
# Quarto searches at every depth unless the resource path starts with `/`.
resources = tuple(f"/{path}" for path in files.resources)
resources = [f"/{path}" for path in paths]
# Quarto's resource globs also match private directories.
if any(has_magic(path) for path in paths):
resources.append(f"!/{RENDER_SCRIPTS_DIR}/**")
quarto_yml.apply(
run.quarto_config,
Contribution(resources=resources, render_excludes=tuple(files.render_excludes)),
Contribution(resources=tuple(resources), render_excludes=tuple(files.render_excludes)),
config,
)
return f"{len(files.resources)} file(s) published at the site root"
return f"{len(paths)} file(s) published at the site root"


def assets(run: Run, config: Config, layout: Layout, *, remote: Remote) -> Outcome:
Expand Down
4 changes: 2 additions & 2 deletions great_docs/_build/freeze.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from .._website import page_metadata
from .._yaml import split_front_matter
from . import quarto
from .ownership import recognised_build_dirs, validate_tree_symlinks
from .ownership import RENDER_SCRIPTS_DIR, recognised_build_dirs, validate_tree_symlinks
from .steps import count_listed, run_steps

if TYPE_CHECKING:
Expand Down Expand Up @@ -120,7 +120,7 @@ def _missing_resources(
relative = target.relative_to(project_dir)
if authored_dir is not None and (authored_dir / relative).exists():
continue
if relative.parts[0] in {"_freeze", "_site", ".quarto", "scripts"} or (
if relative.parts[0] in {"_freeze", "_site", ".quarto", RENDER_SCRIPTS_DIR} or (
relative.name.startswith(("_", "."))
or relative.suffix.lower() in {".qmd", ".md", ".rmd", ".ipynb"}
):
Expand Down
3 changes: 3 additions & 0 deletions great_docs/_build/ownership.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
"# Configure settings in great-docs.yml instead.\n\n"
)

RENDER_SCRIPTS_DIR = "_gd_scripts"
"""The private Quarto project directory containing staged render hooks"""


GITIGNORE_CONTENT = """# Great Docs build directory
# This directory is ephemeral and regenerated on each build
Expand Down
3 changes: 2 additions & 1 deletion great_docs/_build/parallel_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
from .._website import quarto_yml
from .._website.homepage.aliases import root_alias_sources
from . import quarto
from .ownership import RENDER_SCRIPTS_DIR

JOBS_ENV = "GREAT_DOCS_RENDER_JOBS"
"""Environment variable giving the number of render processes (`auto` or a number)"""
Expand Down Expand Up @@ -101,7 +102,7 @@

# Pre-render scripts Great Docs adds that change neither the project's inputs nor
# `_quarto.yml`
_KNOWN_PRE_RENDER = {"scripts/restore-freeze.py"}
_KNOWN_PRE_RENDER = {f"{RENDER_SCRIPTS_DIR}/restore-freeze.py"}

# Keys of `_quarto.yml` that only Great Docs reads, before the render
_NOT_FOR_QUARTO = ("api-reference",)
Expand Down
4 changes: 2 additions & 2 deletions great_docs/_build/prepare.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from .._website import page_dates, quarto_extensions, quarto_yml, repo_links, scripts
from .._website.navigation import shared_sidebar
from . import content, outputs, reference
from .ownership import GITIGNORE_CONTENT
from .ownership import GITIGNORE_CONTENT, RENDER_SCRIPTS_DIR
from .steps import Outcome, print_warning

if TYPE_CHECKING:
Expand Down Expand Up @@ -101,7 +101,7 @@ def build_directory(
build_dir.mkdir(parents=True, exist_ok=True)
run.quarto_config = quarto_yml.write_initial(build_dir)

scripts_dir = build_dir / "scripts"
scripts_dir = build_dir / RENDER_SCRIPTS_DIR
scripts_dir.mkdir(exist_ok=True)

reference_dir = build_dir / config.reference_output
Expand Down
3 changes: 2 additions & 1 deletion great_docs/_content/site_root.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

from yaml12 import format_yaml

from .._build.ownership import RENDER_SCRIPTS_DIR
from .._yaml import locate_front_matter
from . import homepage as homepage_source
from . import notebooks
Expand Down Expand Up @@ -120,7 +121,7 @@ class GeneratedName:

_DIRECTORIES = {
"assets": "copies `assets/` beside the configuration to `assets/`",
"scripts": "writes its scripts and pre-render scripts under `scripts/`",
RENDER_SCRIPTS_DIR: f"stages render scripts under `{RENDER_SCRIPTS_DIR}/`",
"tags": "writes the tags index under `tags/`",
"termshow": "writes rendered terminal recordings under `termshow/`",
"notebooks": "writes marimo notebooks under `notebooks/`",
Expand Down
10 changes: 6 additions & 4 deletions great_docs/_website/navigation/shared_sidebar.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,15 @@

from yaml12 import format_yaml, parse_yaml

from ..._build.ownership import RENDER_SCRIPTS_DIR
from ..._yaml import YamlValue, split_front_matter
from ..page_metadata import rendered_pages

SIDEBAR_IDS = ("reference", "cli-reference", "mcp-reference")
"""The sidebars Great Docs generates for its reference sections"""

SCRIPT = "share-sidebars.py"
"""The post-render script, copied from the package assets into `scripts/`"""
"""The post-render script that restores shared sidebars on rendered pages"""

MANIFEST = "_gd_sidebars.json"
"""What the post-render script needs, written to the build directory"""
Expand Down Expand Up @@ -103,16 +104,17 @@ def prepare(build_dir: Path, quarto_config: dict[str, Any]) -> list[str]:
_write_template(build_dir / plan.template, plan)

project_config = quarto_config.setdefault("project", {})
entry = f"scripts/{SCRIPT}"
entry = f"{RENDER_SCRIPTS_DIR}/{SCRIPT}"
post_render: YamlValue = project_config.get("post-render")
if post_render is None:
project_config["post-render"] = entry
else:
scripts: list[YamlValue] = post_render if isinstance(post_render, list) else [post_render]
project_config["post-render"] = [*scripts, entry]

(build_dir / "scripts").mkdir(exist_ok=True)
_ = shutil.copy2(Path(__file__).parents[2] / "assets" / SCRIPT, build_dir / "scripts" / SCRIPT)
scripts_dir = build_dir / RENDER_SCRIPTS_DIR
scripts_dir.mkdir(exist_ok=True)
_ = shutil.copy2(Path(__file__).parents[2] / "assets" / SCRIPT, scripts_dir / SCRIPT)

_ = (build_dir / MANIFEST).write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
return [plan.id for plan in plans]
Expand Down
7 changes: 4 additions & 3 deletions great_docs/_website/quarto_defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from typing import TYPE_CHECKING, Any, cast
from urllib.parse import urlsplit

from .._build.ownership import RENDER_SCRIPTS_DIR
from .._content import publish
from .._content.naming import is_private_path
from .._interlinks.sphinx_inventory import INVENTORY_FILENAME
Expand Down Expand Up @@ -90,15 +91,15 @@ def register(quarto_config: dict[str, Any], config: Config, layout: Layout) -> N

pre_render: list[str] = []
if config.freeze is not None or layout.freeze_dir.is_dir():
pre_render.append("scripts/restore-freeze.py")
pre_render.append(f"{RENDER_SCRIPTS_DIR}/restore-freeze.py")
for script in config.pre_render:
entry = f"scripts/{Path(script).name}"
entry = f"{RENDER_SCRIPTS_DIR}/{Path(script).name}"
if entry not in pre_render:
pre_render.append(entry)
if pre_render:
project["pre-render"] = pre_render[0] if len(pre_render) == 1 else pre_render

post_render = [f"scripts/{Path(path).name}" for path in config.post_render]
post_render = [f"{RENDER_SCRIPTS_DIR}/{Path(path).name}" for path in config.post_render]
if post_render:
entries = [f'"{entry}"' if " " in entry else entry for entry in post_render]
project["post-render"] = entries[0] if len(entries) == 1 else entries
Expand Down
10 changes: 6 additions & 4 deletions great_docs/_website/repo_links.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from pathlib import Path
from typing import TYPE_CHECKING, Any

from .._build.ownership import RENDER_SCRIPTS_DIR
from .._yaml import YamlValue

if TYPE_CHECKING:
Expand All @@ -26,7 +27,7 @@
__all__ = ["MANIFEST", "SCRIPT", "prepare"]

SCRIPT = "repo-links.py"
"""The post-render script, copied from the package assets into `scripts/`"""
"""The post-render script that corrects links to authored pages"""

MANIFEST = "_gd_page_sources.json"
"""The authored source of each page, written to the build directory for the script"""
Expand Down Expand Up @@ -78,7 +79,7 @@ def prepare(
}

project: dict[str, Any] = quarto_config.setdefault("project", {})
entry = f"scripts/{SCRIPT}"
entry = f"{RENDER_SCRIPTS_DIR}/{SCRIPT}"
post_render: YamlValue = project.get("post-render")
if post_render is None:
project["post-render"] = entry
Expand All @@ -87,8 +88,9 @@ def prepare(
if entry not in scripts:
project["post-render"] = [*scripts, entry]

(build_dir / "scripts").mkdir(exist_ok=True)
_ = shutil.copy2(Path(__file__).parents[1] / "assets" / SCRIPT, build_dir / "scripts" / SCRIPT)
scripts_dir = build_dir / RENDER_SCRIPTS_DIR
scripts_dir.mkdir(exist_ok=True)
_ = shutil.copy2(Path(__file__).parents[1] / "assets" / SCRIPT, scripts_dir / SCRIPT)
_ = (build_dir / MANIFEST).write_text(
json.dumps(dict(sorted(sources.items())), indent=2) + "\n", encoding="utf-8"
)
Expand Down
2 changes: 1 addition & 1 deletion tests/test_build_outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def test_validate_rejects_pages_published_into_the_reference_output(tmp_path: Pa


@pytest.mark.parametrize(
"output", ["user-guide", "site_libs", "termshow", "assets/python", "scripts/python"]
"output", ["user-guide", "site_libs", "termshow", "assets/python", "_gd_scripts/python"]
)
def test_validate_rejects_a_reference_output_that_great_docs_fills(
tmp_path: Path, output: str
Expand Down
6 changes: 6 additions & 0 deletions tests/test_content_site_root.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,11 @@ def test_files_outside_the_configuration_directory_are_rejected(tmp_path: Path,
"reserves `llms-full.txt` for `llms_txt.full`",
),
("site_root:\n files: [reference/extra.json]\n", {}, "API reference"),
(
'site_root:\n files: ["_gd_scripts/*.py"]\n',
{"_gd_scripts/restore-freeze.py": ""},
"stages render scripts",
),
(
"reference:\n output: api\nsite_root:\n files: [api/extra.json]\n",
{},
Expand Down Expand Up @@ -351,6 +356,7 @@ def test_listed_files_are_copied_and_published_as_resources(tmp_path: Path):
"/data/b.csv",
"/generated/**",
"/raw.md",
"!/_gd_scripts/**",
]
assert "!raw.md" in project["render"]

Expand Down
5 changes: 2 additions & 3 deletions tests/test_great_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -7416,7 +7416,7 @@ def test_prepare_build_directory_creates_structure():

# Check directory structure
assert docs.layout.build_dir.exists()
assert (docs.layout.build_dir / "scripts").is_dir()
assert (docs.layout.build_dir / "_gd_scripts").is_dir()
assert (docs.layout.build_dir / "reference").is_dir()

# Check .gitignore
Expand Down Expand Up @@ -21664,8 +21664,7 @@ def test_prepare_build_dir_pre_render_script_exists(tmp_path):
with patch("great_docs._build.reference.add_api_block"):
prepare_build_directory(docs, make_run(docs))

# Script should be copied to scripts/ in the build dir
assert (docs.layout.build_dir / "scripts" / "prerender.py").exists()
assert (docs.layout.build_dir / "_gd_scripts" / "prerender.py").exists()


def test_prepare_build_dir_css_file_warning(tmp_path):
Expand Down
24 changes: 20 additions & 4 deletions tests/test_layout_sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -397,17 +397,28 @@ def test_post_render_scripts_publish_owned_files(
monkeypatch.setattr(parallel_render, "render", partial(parallel_render.render, min_pages=1))
docs = tmp_path / "docs"
hooks = docs / "hooks"
scripts = docs / "scripts"
hooks.mkdir(parents=True)
scripts.mkdir()
(tmp_path / "pyproject.toml").write_text('[project]\nname = "sample"\nversion = "1.0"\n')
(docs / "great-docs.yml").write_text(
"freeze: false\nquarto:\n project:\n"
"freeze: auto\npre_render: hooks/prepare.py\nsite_root:\n"
' files: ["scripts/*.py", "**/restore-freeze.py", "**/prepared*.txt"]\n'
"quarto:\n project:\n"
" post-render: [hooks/write schema.py, hooks/append.py]\n"
)
(docs / "index.qmd").write_text("---\ntitle: Home\n---\n\nHome page.\n")
(docs / "details.qmd").write_text("---\ntitle: Details\n---\n\nDetails page.\n")
downloads = {"diff.py": b"# Public download\n", "prepare.py": b"# Public example\n"}
for name, source in downloads.items():
(scripts / name).write_bytes(source)
(hooks / "prepare.py").write_text(
'from pathlib import Path\nPath("prepared.txt").write_text("prepared")\n'
)
(hooks / "write schema.py").write_text(
"import os\nfrom pathlib import Path\n"
'site = Path(os.environ["QUARTO_PROJECT_OUTPUT_DIR"])\n'
'assert Path("prepared.txt").read_text() == "prepared"\n'
'assert (site / "index.html").is_file()\n'
'assert (site / "details.html").is_file()\n'
'target = site / "schema/brand.yml"\n'
Expand All @@ -425,8 +436,13 @@ def test_post_render_scripts_publish_owned_files(
for _ in range(2):
gd.build(jobs=jobs)
assert (site / "schema/brand.yml").read_text() == "schema completed"
assert (site / "prepared.txt").read_text() == "prepared"
assert not (site / "_gd_scripts").exists()
manifest = json.loads((site / ".great-docs-site.json").read_text())
assert {"schema", "schema/brand.yml"} <= set(manifest["paths"])
for name, source in downloads.items():
assert (site / "scripts" / name).read_bytes() == source
assert f"scripts/{name}" in manifest["paths"]
if jobs > 1:
timings = json.loads((site / "build-timings.json").read_text())
assert timings["render"]["processes"] == jobs
Expand Down Expand Up @@ -464,7 +480,7 @@ def test_freeze_custom_config_name(tmp_path: Path, monkeypatch: pytest.MonkeyPat
gd = GreatDocs(str(tmp_path), config_path=str(config))
prepare_build_directory(gd, make_run(gd))
monkeypatch.chdir(gd.layout.build_dir)
runpy.run_path(str(gd.layout.build_dir / "scripts/restore-freeze.py"))
runpy.run_path(str(gd.layout.build_dir / "_gd_scripts/restore-freeze.py"))
assert (gd.layout.build_dir / "_freeze/result.json").read_text() == "cached"


Expand Down Expand Up @@ -521,7 +537,7 @@ def test_documentation_sources(source_project: tuple[Path, Path], explicit: bool
"references.bib",
"citation.csl",
"style.css",
"scripts/prepare.py",
"_gd_scripts/prepare.py",
"assets/logo.svg",
"recipes/start.qmd",
"custom/about.qmd",
Expand All @@ -534,7 +550,7 @@ def test_documentation_sources(source_project: tuple[Path, Path], explicit: bool
assert (build / "user-guide" / guide_name).is_file()
config = run.quarto_config
assert config["project"]["output-dir"] == "_site"
assert "scripts/prepare.py" in config["project"]["pre-render"]
assert "_gd_scripts/prepare.py" in config["project"]["pre-render"]
assert config["bibliography"] == "references.bib"
assert {"file": "_includes/header.html"} in config["format"]["html"]["include-in-header"]
assert gd.layout.package_root == root
Expand Down
8 changes: 4 additions & 4 deletions tests/test_quarto_defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def test_freeze_mode_restores_the_cache_before_rendering(self, tmp_path: Path):
config = write_config(tmp_path)
quarto_defaults.register(quarto_config, config, Layout.make(tmp_path))
assert quarto_config["project"]["output-dir"] == "_site"
assert quarto_config["project"]["pre-render"] == "scripts/restore-freeze.py"
assert quarto_config["project"]["pre-render"] == "_gd_scripts/restore-freeze.py"
assert quarto_config["execute"] == {"freeze": "auto"}

def test_freeze_cache_alone_restores_without_freezing(self, tmp_path: Path):
Expand All @@ -43,9 +43,9 @@ def test_freeze_cache_alone_restores_without_freezing(self, tmp_path: Path):
)
quarto_defaults.register(quarto_config, config, Layout.make(tmp_path))
assert quarto_config["project"]["pre-render"] == [
"scripts/restore-freeze.py",
"scripts/a.py",
"scripts/b.py",
"_gd_scripts/restore-freeze.py",
"_gd_scripts/a.py",
"_gd_scripts/b.py",
]
assert "execute" not in quarto_config

Expand Down
Loading
Loading