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
86 changes: 50 additions & 36 deletions great_docs/_versions/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@


_UNSAFE_TAG_CHARS = re.compile(r"[^A-Za-z0-9._-]")
_PAGE_SUFFIXES = (".qmd", ".md", ".ipynb")


def _safe_tag_dirname(tag: str) -> str:
Expand Down Expand Up @@ -446,7 +447,7 @@ def _prune_missing_sidebar_pages(quarto_config: dict[str, Any], dest_dir: Path)
"""
Remove sidebar entries whose pages are missing from the version

Version scoping can delete `.qmd` files still listed in the sidebars.
Version scoping can delete page sources still listed in the sidebars.
Quarto displays these entries as raw paths instead of links. Remove the
entries and any sections left empty.

Expand All @@ -468,33 +469,35 @@ def _prune_missing_sidebar_pages(quarto_config: dict[str, Any], dest_dir: Path)


def _prune_sidebar_contents(contents: list, dest_dir: Path) -> list:
"""Recursively prune sidebar entries whose target files are missing."""
"""
Remove sidebar links to missing local page sources and any empty groups
"""
result = []
for item in contents:
if isinstance(item, str):
# Bare href like "user-guide/scale-to-fit.qmd"
if item.endswith((".qmd", ".md")) and not (dest_dir / item).exists():
continue
result.append(item)
elif isinstance(item, dict):
if "section" in item:
# Section group — recurse into contents
inner = _prune_sidebar_contents(item.get("contents", []), dest_dir)
if inner:
result.append({**item, "contents": inner})
# else: drop the empty section entirely
elif "href" in item:
href = item["href"]
if href.endswith((".qmd", ".md")) and not (dest_dir / href).exists():
continue
result.append(item)
else:
result.append(item)
else:
result.append(item)
if isinstance(item, dict) and "section" in item:
inner = _prune_sidebar_contents(item.get("contents", []), dest_dir)
if inner:
result.append({**item, "contents": inner})
continue
href = item.get("href") if isinstance(item, dict) else item
if isinstance(href, str) and _missing_sidebar_page(href, dest_dir):
continue
result.append(item)
return result


def _missing_sidebar_page(href: str, dest_dir: Path) -> bool:
"""
Check whether a local link names a page source missing from this version
"""
target = href.split("#", 1)[0].split("?", 1)[0]
if not target.endswith(_PAGE_SUFFIXES) or target.startswith("//"):
return False
if ":" in target.split("/", 1)[0]:
return False
return not (dest_dir / target.lstrip("/")).exists()


def _prune_cli_pages_for_version(
dest_dir: Path,
project_root: Path,
Expand Down Expand Up @@ -570,8 +573,8 @@ def preprocess_version(
Copy `source_dir` to `dest_dir` unless they are the same directory. Then:

1. Remove pages whose front matter excludes the version.
2. Remove sections whose configuration excludes the version, along with
their navbar links.
2. Remove pages and notebooks in sections whose configuration excludes
the version, along with their navbar links.
3. Process version fences in the remaining `.qmd` files.
4. Expand version badges and callouts.
5. Generate API reference pages from a configured snapshot, and rebuild
Expand Down Expand Up @@ -614,8 +617,7 @@ def preprocess_version(
Returns
-------
:
Page paths relative to `dest_dir`, with `.qmd` extensions replaced by
`.html`.
HTML paths for retained Markdown sources relative to `dest_dir`.
"""
# Build a set of directories excluded by section-level version scoping
excluded_dirs = _compute_excluded_section_dirs(entry.tag, all_versions, section_configs, layout)
Expand All @@ -631,22 +633,26 @@ def preprocess_version(
upcoming_pages: list[tuple[str, str | None]] = []
reference_dir = Path(_reference_dir(config))

for qmd_file in _collect_qmd_files(dest_dir):
rel = qmd_file.relative_to(dest_dir)
page_files = sorted([*_collect_qmd_files(dest_dir), *dest_dir.rglob("*.ipynb")])
for page_file in page_files:
rel = page_file.relative_to(dest_dir)

if _is_private_page(rel, reference_dir):
continue

# 0. Section-level version scoping
if _in_excluded_section(rel, excluded_dirs):
qmd_file.unlink()
page_file.unlink()
continue

content = qmd_file.read_text(encoding="utf-8", errors="replace")
if rel.suffix == ".ipynb":
continue

content = page_file.read_text(encoding="utf-8", errors="replace")

# 1. Page-level version scoping
if not page_matches_version(content, entry.tag, all_versions):
qmd_file.unlink()
page_file.unlink()
continue

# 2. Process version fences
Expand All @@ -671,7 +677,7 @@ def preprocess_version(
upcoming_pages.append((page_href, upcoming_val))

if processed != content:
qmd_file.write_text(processed, encoding="utf-8")
page_file.write_text(processed, encoding="utf-8")

# Track included page (convert .qmd → .html for the manifest)
html_rel = str(rel).replace(".qmd", ".html").replace(".md", ".html")
Expand Down Expand Up @@ -2296,11 +2302,12 @@ def run_versioned_build(
continue
if not any(
not _is_private_page(page.relative_to(ver_dir), reference_dir)
for page in ver_dir.rglob("*.qmd")
for suffix in _PAGE_SUFFIXES
for page in ver_dir.rglob(f"*{suffix}")
):
tag = dir_to_tag_pre.get(str(ver_dir), str(ver_dir))
errors.append(
f"Version {tag}: No .qmd files found in build directory after preprocessing. "
f"Version {tag}: No page sources found in build directory after preprocessing. "
f"All pages may have been excluded by version scoping."
)

Expand Down Expand Up @@ -2340,7 +2347,8 @@ def run_versioned_build(
# Quarto may exit 0 without rendering anything (e.g. if it cannot find
# renderable files or has a configuration issue). Detect this and report
# a meaningful error instead of silently producing an empty site.
site_dir = Path(build_dir) / "_site"
version_dir = Path(build_dir)
site_dir = version_dir / "_site"
html_files = list(site_dir.rglob("*.html")) if site_dir.exists() else []
if not html_files:
# Gather diagnostic info
Expand All @@ -2363,6 +2371,12 @@ def run_versioned_build(
errors_render.append("\n".join(diag_parts))
else:
versions_built.append(tag)
# Notebooks excluded from rendering can still be present as downloads.
pages = pages_by_version[tag]
for notebook in sorted(version_dir.rglob("*.ipynb")):
page = notebook.relative_to(version_dir).with_suffix(".html").as_posix()
if page not in pages and (site_dir / page).is_file():
pages.append(page)
if page_timings:
timings_by_version[tag] = page_timings
else:
Expand Down
77 changes: 68 additions & 9 deletions tests/test_versioned_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -905,6 +905,65 @@ def test_preprocess_excludes_sections_by_published_directory(self, tmp_path: Pat

assert sorted(pages) == ["guides/intro.html", "user-guide/recipes/basic.html"]

def test_preprocess_scopes_notebooks_by_section(self, tmp_path: Path) -> None:
layout = Layout.make(tmp_path)
source = layout.build_dir
notebook = '{"cells": [], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}\n'
_make_source_tree(
source,
{
"guide/start.ipynb": notebook,
"examples/start.ipynb": notebook,
},
)
versions = parse_versions_config(["2.0", "1.0"])
sections = [{"dir": "guide", "versions": ["2.0"]}]
historical = tmp_path / "build-1.0"
version_config = {
"website": {
"navbar": {"left": [{"text": "Guide", "href": "guide/start.ipynb"}]},
"sidebar": [
{
"contents": [
"guide/start.ipynb",
{"text": "Guide", "href": "guide/start.ipynb"},
"examples/start.ipynb",
"https://example.org/example.ipynb",
]
}
],
}
}

preprocess_version(
source,
historical,
versions[1],
versions,
section_configs=sections,
layout=layout,
quarto_config=version_config,
)
_prune_missing_sidebar_pages(version_config, historical)
preprocess_version(
source,
source,
versions[0],
versions,
section_configs=sections,
layout=layout,
quarto_config={},
)

assert not (historical / "guide/start.ipynb").exists()
assert (historical / "examples/start.ipynb").is_file()
assert (source / "guide/start.ipynb").read_text(encoding="utf-8") == notebook
assert version_config["website"]["navbar"]["left"] == []
assert version_config["website"]["sidebar"][0]["contents"] == [
"examples/start.ipynb",
"https://example.org/example.ipynb",
]

def test_preprocess_removes_navbar_links_into_excluded_sections(self, tmp_path: Path):
# Navbar links to excluded sections lead to missing pages. Menu links
# must also be removed, along with menus emptied by those removals.
Expand Down Expand Up @@ -3583,15 +3642,15 @@ def test_non_latest_navbar_title_gets_version_suffix(self, navbar_title, expecte


class TestRunVersionedBuild:
def test_full_build_with_mocked_render(self, tmp_path: Path):
from unittest.mock import MagicMock, patch
@pytest.mark.parametrize("suffix", [".qmd", ".ipynb"])
def test_full_build_with_mocked_render(self, tmp_path: Path, suffix: str) -> None:
from unittest.mock import patch

# Set up source tree
layout = _make_project(
tmp_path,
{
"index.qmd": "---\ntitle: Home\n---\nHi",
"guide.qmd": "---\ntitle: Guide\n---\nContent",
f"index{suffix}": "---\ntitle: Home\n---\nHi" if suffix == ".qmd" else "{}",
"download.ipynb": "{}",
},
)
source, project_root = layout.build_dir, layout.package_root
Expand Down Expand Up @@ -3623,7 +3682,8 @@ def mock_render(build_dirs, **kwargs):
assert "0.3" in result["versions_built"]
assert "0.2" in result["versions_built"]
assert (source / "_site" / "index.html").exists()
assert (source / "_site" / "_version_map.json").exists()
manifest = json.loads((source / "_site" / "_version_map.json").read_text(encoding="utf-8"))
assert manifest["pages"] == {"index.html": ["0.3", "0.2"]}

def test_latest_only_builds_single_version(self, tmp_path: Path):
from unittest.mock import patch
Expand Down Expand Up @@ -4615,8 +4675,7 @@ def mock_render_empty_site(build_dirs, **kwargs):
for err in result["errors"]:
assert "no HTML pages" in err

def test_pre_render_check_no_qmd_files(self, tmp_path: Path):
"""When preprocessing removes all .qmd files, abort before render."""
def test_pre_render_check_no_pages(self, tmp_path: Path) -> None:
from unittest.mock import patch

# Only _quarto.yml, no .qmd files
Expand All @@ -4642,7 +4701,7 @@ def mock_render(build_dirs, **kwargs):
)

assert result["success"] is False
assert "No .qmd files" in result["errors"][0]
assert "No page sources" in result["errors"][0]

# Render should NOT have been called
assert render_called == []
Expand Down
Loading