From ff6150d7d5727e4afd6127476995ea7f9835f9e4 Mon Sep 17 00:00:00 2001 From: Hassan Kibirige Date: Fri, 4 Dec 2026 13:55:49 +0300 Subject: [PATCH 1/2] feat: preserve configured section and guide URLs Allow sections and the user guide to choose a published directory. Keep section numbering when requested so existing page URLs continue to work after migration. --- docs/user_guide/05-configuration.qmd | 30 +++++++- great_docs/_build/content.py | 31 +++++---- great_docs/_build/outputs.py | 80 +++++++++++++++++++-- great_docs/_content/naming.py | 11 +++ great_docs/_content/pages.py | 13 ++-- great_docs/_content/sections.py | 41 +++++++---- great_docs/_content/site_root.py | 13 +++- great_docs/_content/user_guide.py | 50 ++++++++----- great_docs/_layout_migration/analyse.py | 89 +++++++++++++++--------- great_docs/_layout_migration/content.py | 17 ++++- great_docs/_website/homepage/landing.py | 12 ++-- great_docs/_website/homepage/page.py | 11 ++- great_docs/_website/navigation/navbar.py | 11 +-- great_docs/_website/page_scan.py | 4 +- great_docs/_website/resources.py | 2 +- great_docs/_website/seo/sitemap.py | 15 ++-- great_docs/config.py | 80 +++++++++++++++++---- tests/test_build_content.py | 58 +++++++++++++++ tests/test_build_outputs.py | 23 ++++++ tests/test_homepage.py | 11 +-- tests/test_layout_migration.py | 26 +++++++ 21 files changed, 496 insertions(+), 132 deletions(-) diff --git a/docs/user_guide/05-configuration.qmd b/docs/user_guide/05-configuration.qmd index d398beb6..62b70c59 100644 --- a/docs/user_guide/05-configuration.qmd +++ b/docs/user_guide/05-configuration.qmd @@ -673,7 +673,18 @@ user_guide: guides The path is relative to the configuration directory. If both the config option and a `user_guide/` directory exist, the config option takes precedence. -See [User Guides](user-guides.qmd) for details on writing and organizing User Guide content. +By default, the guide publishes under `user-guide/`. Set `output` to keep a different URL +prefix, such as `user_guide/` on an existing site. + +```{.yaml filename="docs/great-docs.yml"} +user_guide: + dir: user_guide + output: user_guide +``` + +Omit `dir` to use the conventional source directory. Use `sections` within the mapping +to list pages in an explicit order, using the same entries as the list form of `user_guide`. +See [User Guides](user-guides.qmd) for details on writing and organising guide content. ## Homepage Mode @@ -852,6 +863,23 @@ Default sections can generate a card-grid index and sidebar navigation. Blog-typ native `listing:` directive. Posts are sorted by date and displayed with author, categories, and descriptions. +Great Docs normally lowercases the section's directory name, replaces spaces and underscores +with hyphens, and drops numeric prefixes from page and subdirectory names. To keep an +existing URL such as `Tutorials/01_basics/02-setup.html`, set both options. + +```{.yaml filename="docs/great-docs.yml"} +sections: + - title: Tutorials + dir: Tutorials + output: Tutorials + keep_numeric_prefixes: true +``` + +Each option works on its own. Blog posts already keep their numeric prefixes. Guide and +section outputs are relative to the site root and can contain multiple directories. +Use directory names that begin with a letter or digit. Hyphens, underscores and internal +spaces are allowed. + See [Custom Sections](custom-sections.qmd) and [Blog](blog.qmd) for full details. ## Site Root diff --git a/great_docs/_build/content.py b/great_docs/_build/content.py index 4d695bb8..daff0c18 100644 --- a/great_docs/_build/content.py +++ b/great_docs/_build/content.py @@ -22,7 +22,7 @@ from .._content import sections as authored_sections from .._content import user_guide as authored_guide from .._content.naming import title_from_name -from .._content.pages import PageMap +from .._content.pages import PageMap, output_destination from .._contribution import Contribution, NavbarLink, Sidebar from .._website import page_dates, quarto_yml, social_cards, website_overlay from .._website.ai_agents import llms_txt as llms_files @@ -181,7 +181,9 @@ def homepage( pages=pages, page_authors=page_authors, has_api_reference=run.api_spec is not None, - has_user_guide=lambda: guide is not None, + user_guide_entry=lambda: ( + authored_guide.entry(guide, output=config.user_guide_output) if guide else None + ), llms_txt=llms_files.published(config, run.api_spec), report=print, ) @@ -250,7 +252,7 @@ def user_guide( blend_homepage = False copied_files, resources = _publish_guide_pages(config, layout, guide, page_authors=page_authors) - print(f" Copied {len(copied_files)} file(s) to docs/user-guide/") + print(f" Copied {len(copied_files)} file(s) to {config.user_guide_output}/") blended_first_page = None if blend_homepage: @@ -302,7 +304,7 @@ def _publish_guide_pages( Both are relative to the build directory. """ source_dir = guide["source_dir"] - target_dir = layout.build_dir / authored_guide.SIDEBAR_ID + target_dir = output_destination(layout, config.user_guide_output) strip_prefix = not guide.get("explicit", False) add_dates = partial(page_dates.add_to_page, config=config, authors=page_authors) resources = publish.copy_asset_dirs( @@ -345,7 +347,7 @@ def _promote_first_page( """ Promote the first user guide page to `index.qmd` in blended homepage mode - Remove the original page from `user-guide/` after writing the homepage. + Remove the original page from the guide's directory after writing the homepage. Parameters ---------- @@ -366,14 +368,14 @@ def _promote_first_page( Returns ------- : - The promoted page's former path under `user-guide/`, or `None` when no page was + The promoted page's former path in the guide, or `None` when no page was promoted. """ if not guide["files"]: return None dest_rel = authored_guide.published(guide, guide["files"][0]) - first_ug_path = layout.build_dir / authored_guide.SIDEBAR_ID / dest_rel + first_ug_path = layout.build_dir / config.user_guide_output / dest_rel if not first_ug_path.exists(): print(f" ⚠️ First UG page '{first_ug_path}' not found for blended homepage") @@ -394,7 +396,7 @@ def _promote_first_page( first_ug_path.unlink() print(" 📄 Blended homepage: first UG page → index.qmd") - return f"user-guide/{dest_rel}" + return first_ug_path.relative_to(layout.build_dir).as_posix() def _guide_navigation( @@ -410,7 +412,7 @@ def _guide_navigation( guide The user guide. blended_first_page - The promoted page's former path under `user-guide/`, or `None` when no page was + The promoted page's former path in the guide, or `None` when no page was promoted. Returns @@ -419,7 +421,8 @@ def _guide_navigation( The sidebar and, unless the guide's first page became the homepage, a navbar link to that page. """ - sidebar = authored_guide.sidebar(guide) + output = config.user_guide_output + sidebar = authored_guide.sidebar(guide, output=output) # The sidebar must link to the homepage after the first guide page moves there. if blended_first_page: @@ -429,7 +432,7 @@ def _guide_navigation( navbar: tuple[NavbarLink, ...] = () if not blended_first_page: label = nav_navbar.USER_GUIDE.label(config) - navbar = (NavbarLink(label, authored_guide.entry(guide), kind="user_guide"),) + navbar = (NavbarLink(label, authored_guide.entry(guide, output=output), kind="user_guide"),) return Contribution(navbar=navbar, sidebars=(_sidebar(sidebar),)) @@ -483,7 +486,7 @@ def sections( if not found: return "No sections to process" - section_ids = {section.slug for section in found} + section_ids = {section.output for section in found} generated_ids = { sidebar.id for contribution in run.contributions for sidebar in contribution.sidebars } @@ -510,7 +513,7 @@ def sections( layout, section.source, section.destination, - strip_prefix=not section.blog, + strip_prefix=section.strip_prefix, pages=section.files, ) @@ -523,7 +526,7 @@ def sections( section.files, section.source, section.destination, - strip_prefix=True, + strip_prefix=section.strip_prefix, report=print_warning, ) diff --git a/great_docs/_build/outputs.py b/great_docs/_build/outputs.py index 7e25bc7c..cb3b181f 100644 --- a/great_docs/_build/outputs.py +++ b/great_docs/_build/outputs.py @@ -8,10 +8,12 @@ from __future__ import annotations import shutil -from typing import TYPE_CHECKING +from dataclasses import replace +from pathlib import Path +from typing import TYPE_CHECKING, cast from .._content import sections, site_root -from .._content.naming import strip_numeric_prefix +from .._content.naming import section_strips_prefix, strip_numeric_prefix from .._content.pages import output_destination, section_destination from .._website import quarto_extensions from .._website.ai_agents import llms_txt @@ -19,7 +21,6 @@ if TYPE_CHECKING: from collections.abc import Callable - from pathlib import Path from .._project.layout import Layout from ..config import Config @@ -63,12 +64,83 @@ def validate(config: Config, layout: Layout) -> None: for entry in versions: validate_build_dir(layout.build_dir_for(entry.tag, latest_tag)) _validate_section_claims(config, layout) + _validate_content_outputs(config, layout) site_root.validate(config, layout) _ = llms_txt.project_files(config, layout) _validate_reference_output(config, layout) quarto_extensions.validate(layout) +def _validate_content_outputs(config: Config, layout: Layout) -> None: + """Reject configured output directories that overlap another destination""" + guide = config.user_guide + guide_explicit = isinstance(guide, dict) and guide.get("output") is not None + entries = cast("object", config.sections) + sections_config = ( + [ + cast("dict[str, object]", entry) + for entry in cast("list[object]", entries) + if isinstance(entry, dict) + ] + if isinstance(entries, list) + else [] + ) + if not guide_explicit and not any(entry.get("output") is not None for entry in sections_config): + return + + generated = site_root.generated_names(config, layout, include_content_directories=False) + guide_name = site_root.user_guide_name(config) + reserved = [ + replace(name, path=name.path.casefold()) for name in generated if name != guide_name + ] + build_dir = layout.build_dir.resolve() + destinations = [("user_guide.output", config.user_guide_output, guide_explicit)] + for entry in sections_config: + destination = section_destination(layout, entry) + if destination is not None and destination != build_dir: + destinations.append( + ( + f"sections ({entry['dir']})", + destination.relative_to(build_dir).as_posix(), + entry.get("output") is not None, + ) + ) + + for entry in config.custom_pages: + if config["custom_pages"] is None and not (layout.source_dir / entry["dir"]).is_dir(): + continue + try: + destination = output_destination(layout, entry["output"]) + except ValueError: + continue + if destination != build_dir: + destinations.append( + ( + f"custom_pages ({entry['dir']})", + destination.relative_to(build_dir).as_posix(), + False, + ) + ) + + for index, (key, output, configured) in enumerate(destinations): + if not configured: + continue + if (clash := site_root.find_generated(output.casefold(), reserved)) is not None: + raise ValueError(f"`{key}` publishes to '{output}/', but Great Docs {clash.writer}") + directory = Path(output.casefold()) + for other_index, (other, other_output, _) in enumerate(destinations): + if index == other_index: + continue + other_directory = Path(other_output.casefold()) + if directory.is_relative_to(other_directory) or other_directory.is_relative_to( + directory + ): + raise ValueError( + f"`{key}` publishes to '{output}/', which overlaps " + f"'{other_output}/' from `{other}`" + ) + + def _validate_reference_output(config: Config, layout: Layout) -> None: """ Reject a reference directory that other pages publish into @@ -97,7 +169,7 @@ def _validate_reference_output(config: Config, layout: Layout) -> None: f"sections ({section.get('title') or section.get('dir')})", destination, layout.source_dir / section["dir"], - section.get("type") != "blog", + section_strips_prefix(section), ) for section in config.sections if (destination := section_destination(layout, section)) is not None diff --git a/great_docs/_content/naming.py b/great_docs/_content/naming.py index 5ed7d181..b527ea8a 100644 --- a/great_docs/_content/naming.py +++ b/great_docs/_content/naming.py @@ -4,8 +4,19 @@ import re from pathlib import Path +from typing import TYPE_CHECKING from urllib.parse import unquote +if TYPE_CHECKING: + from collections.abc import Mapping + +DEFAULT_USER_GUIDE_OUTPUT = "user-guide" + + +def section_strips_prefix(section: Mapping[str, object]) -> bool: + """Check whether section page paths drop their numeric prefixes""" + return section.get("type") != "blog" and section.get("keep_numeric_prefixes") is not True + def strip_numeric_prefix(filename: str) -> str: """ diff --git a/great_docs/_content/pages.py b/great_docs/_content/pages.py index 3409be06..934449dd 100644 --- a/great_docs/_content/pages.py +++ b/great_docs/_content/pages.py @@ -8,7 +8,7 @@ from typing import TYPE_CHECKING, cast from . import notebooks, site_root -from .naming import is_private_path, published_path, section_slug +from .naming import is_private_path, published_path, section_slug, section_strips_prefix if TYPE_CHECKING: from collections.abc import Iterable, Mapping @@ -54,8 +54,8 @@ def section_destination(layout: Layout, section: Mapping[str, object]) -> Path | """ Resolve a section's destination directory in the build tree - The destination is the slug of the section's `dir`. If `dir` is absolute or contains - `..`, use its path relative to the package root. This preserves the name of a shared + Use `output` when set. Otherwise slug the section's `dir`. If `dir` is absolute or + contains `..`, use its path relative to the package root. This preserves the name of a shared section when documentation sources are in a subdirectory. For a section outside the package, use only the directory name. @@ -74,6 +74,9 @@ def section_destination(layout: Layout, section: Mapping[str, object]) -> Path | directory = section.get("dir") if not directory or not isinstance(directory, str): return None + output = section.get("output") + if isinstance(output, str): + return output_destination(layout, output) source = Path(directory) if source.is_absolute() or ".." in source.parts: resolved = (layout.source_dir / source).resolve() @@ -171,7 +174,7 @@ def make( roots.append( PageRoot( guide["source_dir"].resolve(), - layout.build_dir / "user-guide", + output_destination(layout, config.user_guide_output), not guide.get("explicit", False), ) ) @@ -185,7 +188,7 @@ def make( PageRoot( (layout.source_dir / str(section["dir"])).resolve(), destination, - section.get("type") != "blog", + section_strips_prefix(section), prefer_markdown_index=True, exclude_private=True, ) diff --git a/great_docs/_content/sections.py b/great_docs/_content/sections.py index fd463645..489f6f06 100644 --- a/great_docs/_content/sections.py +++ b/great_docs/_content/sections.py @@ -21,7 +21,13 @@ from .._yaml import add_body_class, locate_front_matter, set_front_matter_option from . import notebooks from . import publish as page_publish -from .naming import is_private_path, published_path, strip_numeric_prefix, title_from_name +from .naming import ( + is_private_path, + published_path, + section_strips_prefix, + strip_numeric_prefix, + title_from_name, +) from .pages import section_destination if TYPE_CHECKING: @@ -82,13 +88,16 @@ class Section: blog: bool """Whether the section is a blog, whose posts keep their names and front matter""" + strip_prefix: bool + """Whether published paths drop the numeric ordering prefixes""" + files: tuple[Path, ...] """The published pages, in sorted order""" destination: Path """The section's directory in the build""" - slug: str + output: str """The destination relative to the build directory, in POSIX form""" show_sidebar: bool @@ -217,13 +226,16 @@ def read(config: Config, layout: Layout, *, report: Callable[[str], None]) -> li # Only ancestors within the section directory are consulted, since a hidden # directory above the project says nothing about the content inside. blog = options.get("type") == "blog" + strip_prefix = section_strips_prefix(options) files = sorted( file for file in source.rglob("*") if file.suffix in _CONTENT_SUFFIXES and file.name != "README.md" and notebooks.markdown_index(file) is None - and not is_private_path(published_path(file.relative_to(source), strip_prefix=not blog)) + and not is_private_path( + published_path(file.relative_to(source), strip_prefix=strip_prefix) + ) and not any( layout.is_reserved_directory(parent) for parent in file.parents @@ -243,9 +255,10 @@ def read(config: Config, layout: Layout, *, report: Callable[[str], None]) -> li dir=directory, source=source, blog=blog, + strip_prefix=strip_prefix, files=tuple(files), destination=destination, - slug=destination.relative_to(layout.build_dir).as_posix(), + output=destination.relative_to(layout.build_dir).as_posix(), show_sidebar=show_sidebar, index=bool(options.get("index", False)), index_columns=options.get("index_columns", 2), @@ -305,7 +318,7 @@ def publish( if not has_markdown_index and section.source / notebook_index.name in section.files: index = notebook_index has_user_index = has_markdown_index or index == notebook_index - index_href = f"{section.slug}/{index.name}" + index_href = f"{section.output}/{index.name}" section_sidebar = None if section.blog: @@ -336,6 +349,7 @@ def publish( pages=pages, add_dates=add_dates, show_breadcrumbs=config.show_breadcrumbs, + strip_prefix=section.strip_prefix, ) content_pages = [page for page in copied if page["filename"] != index.name] if not has_user_index and section.index: @@ -352,12 +366,12 @@ def publish( index_source = add_body_class(index_source, _NO_SIDEBAR_CLASS) _ = index.write_text(index_source, encoding="utf-8") elif not has_user_index and content_pages: - index_href = f"{section.slug}/{content_pages[0]['filename']}" + index_href = f"{section.output}/{content_pages[0]['filename']}" if section.show_sidebar: section_sidebar = sidebar( section.title, - section.slug, + section.output, copied, has_index=has_user_index or section.index, index_name=index.name, @@ -405,12 +419,11 @@ def copy_pages( pages: PageMap, add_dates: Callable[[str, Path], str], show_breadcrumbs: bool, + strip_prefix: bool = True, ) -> list[Page]: """ Copy a default section's pages into the build - Numeric prefixes are dropped from every part of a page's path. - Parameters ---------- files @@ -428,6 +441,8 @@ def copy_pages( show_breadcrumbs Whether pages show their breadcrumbs. When false, a page that does not set `bread-crumbs` hides them. + strip_prefix + Whether published page paths drop their numeric ordering prefixes. Returns ------- @@ -436,21 +451,21 @@ def copy_pages( """ copied: list[Page] = [] for source in files: - # Copied paths and rewritten links must drop the same numeric prefixes - published = published_path(source.relative_to(source_dir), strip_prefix=True) + published = published_path(source.relative_to(source_dir), strip_prefix=strip_prefix) front_matter = page_publish.page( source, dest_dir / published, layout=layout, pages=pages, add_dates=add_dates, - strip_prefix=True, + strip_prefix=strip_prefix, show_breadcrumbs=show_breadcrumbs, ) copied.append( { "filename": str(published), - "title": front_matter.string("title") or title_from_name(published.stem), + "title": front_matter.string("title") + or title_from_name(strip_numeric_prefix(source.stem)), "description": front_matter.string("description") or "", "image": front_matter.string("image") or "", } diff --git a/great_docs/_content/site_root.py b/great_docs/_content/site_root.py index ba9d4072..2b3b546e 100644 --- a/great_docs/_content/site_root.py +++ b/great_docs/_content/site_root.py @@ -43,6 +43,7 @@ "select_files", "strip_navbar_options", "unmatched_page_patterns", + "user_guide_name", "validate", ] @@ -116,7 +117,6 @@ class GeneratedName: """Files Great Docs may write at the site root in any build, with what writes each""" _DIRECTORIES = { - "user-guide": "writes the user guide under `user-guide/`", "assets": "copies `assets/` beside the configuration to `assets/`", "scripts": "writes its scripts and pre-render scripts under `scripts/`", "tags": "writes the tags index under `tags/`", @@ -200,6 +200,7 @@ def generated_names( ) names.append(reference_name(config)) + names.append(user_guide_name(config)) names.extend(GeneratedName(f"{name}/", writer) for name, writer in _DIRECTORIES.items()) if not include_content_directories: return names @@ -231,6 +232,12 @@ def generated_names( return names +def user_guide_name(config: Config) -> GeneratedName: + """Name the generated user guide directory for output validation""" + directory = f"{config.user_guide_output}/" + return GeneratedName(directory, f"writes the user guide under `{directory}`") + + def reference_name(config: Config) -> GeneratedName: """ Name the directory that the API reference publishes into @@ -501,7 +508,7 @@ def _select_files( } for directory in directories: published = section.destination / published_path( - directory, strip_prefix=not section.blog + directory, strip_prefix=section.strip_prefix ) _ = section_directories.setdefault((section.source / directory).resolve(), published) section_outputs = _section_page_outputs(sections, layout) @@ -565,7 +572,7 @@ def _section_page_outputs(sections: list[Section], layout: Layout) -> dict[str, for section in sections: for page in section.files: relative = published_path( - page.relative_to(section.source), strip_prefix=not section.blog + page.relative_to(section.source), strip_prefix=section.strip_prefix ) path = (section.destination / relative).relative_to(layout.build_dir) for output in (path, path.with_suffix(".html")): diff --git a/great_docs/_content/user_guide.py b/great_docs/_content/user_guide.py index 339ab0d2..c9a10048 100644 --- a/great_docs/_content/user_guide.py +++ b/great_docs/_content/user_guide.py @@ -1,5 +1,5 @@ """ -The user guide: authored pages that the build publishes under `user-guide/` +Discovery, publication and navigation for the user guide A list in the `user_guide` setting defines the page and section order and preserves file names. Otherwise, discovery collects Markdown pages and notebooks from the guide directory, @@ -14,7 +14,12 @@ from .._yaml import split_front_matter from . import notebooks, publish -from .naming import published_path, strip_numeric_prefix, title_from_name +from .naming import ( + DEFAULT_USER_GUIDE_OUTPUT, + published_path, + strip_numeric_prefix, + title_from_name, +) from .sections import source_dirs as section_source_dirs if TYPE_CHECKING: @@ -159,9 +164,9 @@ def discover(config: Config, layout: Layout, *, report: Callable[[str], None]) - if user_guide_dir is None: return None - user_guide_config = config.user_guide - if isinstance(user_guide_config, list): - return _discover_explicit(user_guide_dir, user_guide_config, report=report) + explicit_sections = config.user_guide_sections + if explicit_sections is not None: + return _discover_explicit(user_guide_dir, explicit_sections, report=report) dir_contents = list(user_guide_dir.iterdir()) if not dir_contents: @@ -371,7 +376,7 @@ def read_page(path: Path) -> GuidePage | None: def published(guide: UserGuide, page: GuidePage) -> Path: """ - Find a page's published path relative to `user-guide/` + Find a page's published path relative to the guide's output directory Parameters ---------- @@ -390,7 +395,7 @@ def published(guide: UserGuide, page: GuidePage) -> Path: return published_path(rel_path, strip_prefix=not guide.get("explicit", False)) -def entry(guide: UserGuide) -> str: +def entry(guide: UserGuide, *, output: str = DEFAULT_USER_GUIDE_OUTPUT) -> str: """ Find the navbar target for the guide's first published page @@ -398,6 +403,8 @@ def entry(guide: UserGuide) -> str: ---------- guide The user guide. + output + The guide's published directory relative to the site root. Returns ------- @@ -408,8 +415,8 @@ def entry(guide: UserGuide) -> str: the first section's first page. A sidebar that lists no pages falls back to the guide's first file. """ - hrefs = [f"{SIDEBAR_ID}/{published(guide, page)}" for page in guide["files"]] - listed = set(_hrefs(sidebar(guide)["contents"])) + hrefs = [f"{output}/{published(guide, page).as_posix()}" for page in guide["files"]] + listed = set(_hrefs(sidebar(guide, output=output)["contents"])) return next((href for href in hrefs if href in listed), hrefs[0]) @@ -488,11 +495,11 @@ def copy_pages( show_breadcrumbs=show_breadcrumbs, published=pages.destination(source.resolve()) or dst_path, ) - copied.append(f"{SIDEBAR_ID}/{dest_rel_path}") + copied.append(dst_path.relative_to(layout.build_dir).as_posix()) return copied -def sidebar(guide: UserGuide) -> dict[str, Any]: +def sidebar(guide: UserGuide, *, output: str = DEFAULT_USER_GUIDE_OUTPUT) -> dict[str, Any]: """ Build the guide's sidebar @@ -500,6 +507,8 @@ def sidebar(guide: UserGuide) -> dict[str, Any]: ---------- guide The user guide. + output + The guide's published directory relative to the site root. Returns ------- @@ -508,11 +517,15 @@ def sidebar(guide: UserGuide) -> dict[str, Any]: sections and labels. Automatic guides group pages by `guide-section` when set, or by subdirectory otherwise. A subdirectory's `index.qmd` supplies its title. """ - contents = _explicit_contents(guide) if guide.get("explicit") else _auto_contents(guide) + contents = ( + _explicit_contents(guide, output) + if guide.get("explicit") + else _auto_contents(guide, output) + ) return {"id": SIDEBAR_ID, "title": "User Guide", "contents": contents} -def _explicit_contents(guide: UserGuide) -> list[Any]: +def _explicit_contents(guide: UserGuide, output: str) -> list[Any]: """ List an explicit guide's sidebar entries @@ -520,6 +533,8 @@ def _explicit_contents(guide: UserGuide) -> list[Any]: ---------- guide An explicit user guide. + output + The guide's published directory relative to the site root. Returns ------- @@ -550,7 +565,7 @@ def _explicit_contents(guide: UserGuide) -> list[Any]: if not (source_dir / filename).exists(): continue - href = f"{SIDEBAR_ID}/{filename}" + href = f"{output}/{filename}" text = custom_text or title_lookup.get(filename) items.append({"text": text, "href": href} if text else href) @@ -560,7 +575,7 @@ def _explicit_contents(guide: UserGuide) -> list[Any]: return contents -def _auto_contents(guide: UserGuide) -> list[Any]: +def _auto_contents(guide: UserGuide, output: str) -> list[Any]: """ List a discovered guide's sidebar entries @@ -568,6 +583,8 @@ def _auto_contents(guide: UserGuide) -> list[Any]: ---------- guide A user guide discovered from its directory. + output + The guide's published directory relative to the site root. Returns ------- @@ -582,8 +599,7 @@ def _auto_contents(guide: UserGuide) -> list[Any]: sections = guide["sections"] def link(page: GuidePage) -> Any: - rel_path = page["path"].relative_to(source_dir) - href = f"{SIDEBAR_ID}/{published_path(rel_path, strip_prefix=True)}" + href = f"{output}/{published(guide, page).as_posix()}" if page.get("title"): return {"text": page["title"], "href": href} return href diff --git a/great_docs/_layout_migration/analyse.py b/great_docs/_layout_migration/analyse.py index 25ad13cf..1ff2e7ff 100644 --- a/great_docs/_layout_migration/analyse.py +++ b/great_docs/_layout_migration/analyse.py @@ -13,7 +13,11 @@ from great_docs._build.ownership import is_great_docs_build_dir, recognised_build_dirs from great_docs._content import homepage as homepage_source from great_docs._content import site_root -from great_docs._content.naming import section_slug +from great_docs._content.naming import ( + DEFAULT_USER_GUIDE_OUTPUT, + section_slug, + section_strips_prefix, +) from great_docs._project import manifest as _manifest from great_docs._project.layout import CONVENTIONAL_DOC_DIRS, Layout from great_docs._project.manifest import ManifestError @@ -366,6 +370,24 @@ def _relative_section_dirs(sections: list[YamlValue]) -> list[tuple[int, str, Ya return found +def _guide_source( + config: ConfigMapping, root: Path, section_dirs: set[Path] +) -> tuple[Path, ConfigPath] | None: + """Find the guide's relative source directory and its configuration field""" + guide = config.get("user_guide") + field: ConfigPath = ("user_guide",) + if isinstance(guide, dict): + field = ("user_guide", "dir") + guide = guide.get("dir") + if isinstance(guide, str): + return (root / guide, field) if not Path(guide).is_absolute() else None + for name in ("user_guide", DEFAULT_USER_GUIDE_OUTPUT): + path = root / name + if path not in section_dirs and (path.exists() or path.is_symlink()): + return path, field + return None + + def _dedicated_directories(config: ConfigMapping, root: Path) -> list[tuple[Path, ConfigPath]]: selected: list[tuple[Path, ConfigPath]] = [] sections = config.get("sections") or [] @@ -373,16 +395,8 @@ def _dedicated_directories(config: ConfigMapping, root: Path) -> list[tuple[Path raise MigrationError("Narrative sections must be a list of directory mappings") relative_sections = _relative_section_dirs(sections) section_dirs = {root / directory for _, directory, _ in relative_sections} - guide = config.get("user_guide") - if isinstance(guide, str) and not Path(guide).is_absolute(): - selected.append((root / guide, ("user_guide",))) - elif not isinstance(guide, str): - for name in ("user_guide", "user-guide"): - if root / name in section_dirs: - continue - if (root / name).exists() or (root / name).is_symlink(): - selected.append((root / name, ("user_guide",))) - break + if (guide := _guide_source(config, root, section_dirs)) is not None: + selected.append(guide) for index, directory, _ in relative_sections: selected.append((root / directory, ("sections", index, "dir"))) custom = config.get("custom_pages") @@ -407,32 +421,38 @@ def _dedicated_directories(config: ConfigMapping, root: Path) -> list[tuple[Path return [(absolute_path(path), field) for path, field in selected] -def _content_directories(config: ConfigMapping, root: Path) -> tuple[ContentDirectory, ...]: +def _content_directories( + config: ConfigMapping, root: Path, destination: Path | None = None +) -> tuple[ContentDirectory, ...]: """ Map each recognised content root to its build-time rename and prefix rule - Mirrors `_dedicated_directories`'s reading of the same `user_guide` and - `sections` config fields; keep the two in sync when either changes. + An explicit output is relative to the configuration directory in each layout. """ directories: list[ContentDirectory] = [] sections = config.get("sections") relative_sections = _relative_section_dirs(sections if isinstance(sections, list) else []) section_dirs = {root / directory for _, directory, _ in relative_sections} - guide = config.get("user_guide") - strip = not isinstance(guide, list) - if isinstance(guide, str) and not Path(guide).is_absolute(): - directories.append(ContentDirectory(root / guide, "user-guide", strip)) - elif not isinstance(guide, str): - for name in ("user_guide", "user-guide"): - if root / name in section_dirs: - continue - if (root / name).exists() or (root / name).is_symlink(): - directories.append(ContentDirectory(root / name, "user-guide", strip)) - break + if (guide := _guide_source(config, root, section_dirs)) is not None: + settings = config.get("user_guide") + output = YamlMapping(settings).string("output") if isinstance(settings, dict) else None + order = settings.get("sections") if isinstance(settings, dict) else settings + directories.append( + ContentDirectory( + guide[0], + DEFAULT_USER_GUIDE_OUTPUT, + not isinstance(order, list), + Move(root / output, (destination or root) / output) if output else None, + ) + ) for _, directory, options in relative_sections: + output = options.string("output") directories.append( ContentDirectory( - root / directory, section_slug(directory), options.get("type") != "blog" + root / directory, + section_slug(directory), + section_strips_prefix(options.data), + Move(root / output, (destination or root) / output) if output else None, ) ) return tuple(directories) @@ -827,7 +847,7 @@ def retain_policy(path: Path) -> None: except (OSError, MigrationError) as error: blockers.append(Note(str(error), category="Inputs That Could Not Be Inspected")) selected = [] - content_directories = _content_directories(config, root) + content_directories = _content_directories(config, root, destination) # ("index",), ("config",), ("extensions",) and ("site_root",) are sentinel tags, not real # YAML config paths: none names a field in `content._PATH_FIELDS`, so `exact_match`'s two-entry # allowlist below isn't the only thing keeping them out of `pinned_values`/`pinned_fields`. @@ -950,11 +970,12 @@ def retain_policy(path: Path) -> None: path=source, ) ) - # Leaving the directory where it is means its configured `dir` shortens to a - # path relative to the new configuration location, and a section's published - # directory is that value slugged. Report the resulting URL change, which no - # choice of nested name can avoid here. - if config_field[:1] == ("sections",): + # An in-place directory's source path shortens. Only sections with a + # derived output directory also change their URLs. + if config_field[:1] == ("sections",) and not any( + directory.source == source and directory.output_move is not None + for directory in content_directories + ): old_value = source.relative_to(root).as_posix() new_value = Path(os.path.relpath(source, destination)).as_posix() if old_value != new_value: @@ -968,7 +989,7 @@ def retain_policy(path: Path) -> None: ) elif exact_match: nested_name = ( - "user-guide" + DEFAULT_USER_GUIDE_OUTPUT if config_field[:1] == ("user_guide",) else source.relative_to(root).as_posix() ) @@ -1033,6 +1054,8 @@ def retain_policy(path: Path) -> None: # nor when it is already in place *as that name's own role* — an in-place source # configured under a different field only happens to share this path today. target_role = in_place_sources.get(target) + if target_role == ("user_guide", "dir"): + target_role = ("user_guide",) in_place_as_this_role = target_role is not None and target_role == _DISCOVERY_ROLES.get( name ) diff --git a/great_docs/_layout_migration/content.py b/great_docs/_layout_migration/content.py index d298147e..185b6b18 100644 --- a/great_docs/_layout_migration/content.py +++ b/great_docs/_layout_migration/content.py @@ -45,6 +45,9 @@ class ContentDirectory: output_name: str strip_prefix: bool + output_move: Move | None = None + """The published directory before and after relocation when `output` is set""" + def _denormalize( target: Path, content_directories: tuple[ContentDirectory, ...], moves: tuple[Move, ...] @@ -76,11 +79,18 @@ def _denormalize( match any recognised content directory. """ for directory in content_directories: - root = directory.source.parent - renamed = root / directory.output_name + output = directory.output_move + renamed = ( + output.source if output is not None else directory.source.parent / directory.output_name + ) if target.is_relative_to(renamed): relative = target.relative_to(renamed) - republished_root = moved_path(directory.source, moves).parent / directory.output_name + if output is not None: + republished_root = output.destination if moves else output.source + else: + republished_root = ( + moved_path(directory.source, moves).parent / directory.output_name + ) elif target.is_relative_to(directory.source): relative = target.relative_to(directory.source) republished_root = moved_path(directory.source, moves) @@ -122,6 +132,7 @@ def _denormalize( ) _PATH_FIELDS = ( ("user_guide",), + ("user_guide", "dir"), ("sections", "*", "dir"), ("custom_pages",), ("custom_pages", "dir"), diff --git a/great_docs/_website/homepage/landing.py b/great_docs/_website/homepage/landing.py index 8ee1e44d..67752462 100644 --- a/great_docs/_website/homepage/landing.py +++ b/great_docs/_website/homepage/landing.py @@ -4,6 +4,8 @@ from __future__ import annotations +from urllib.parse import quote + __all__ = ["markdown"] @@ -12,7 +14,7 @@ def markdown( description: str, *, reference_index: str | None, - has_user_guide: bool, + user_guide_entry: str | None, ) -> str: """ Write a landing page from the package's name and description @@ -29,8 +31,8 @@ def markdown( reference_index The API reference index page relative to the project, or `None` when the site has no API reference. - has_user_guide - Whether the site has a user guide. + user_guide_entry + The guide's first published page, or `None` when the site has no guide. Returns ------- @@ -46,8 +48,8 @@ def markdown( links: list[str] = [] if reference_index is not None: links.append(f"- [API Reference]({reference_index}) — Full API documentation") - if has_user_guide: - links.append("- [User Guide](user-guide/index.qmd) — Guides and tutorials") + if user_guide_entry is not None: + links.append(f"- [User Guide]({quote(user_guide_entry)}) — Guides and tutorials") if links: lines += ["### Get Started", "", *links, ""] diff --git a/great_docs/_website/homepage/page.py b/great_docs/_website/homepage/page.py index c35713e5..59a6d055 100644 --- a/great_docs/_website/homepage/page.py +++ b/great_docs/_website/homepage/page.py @@ -130,7 +130,7 @@ def write_readme( pages: PageMap, page_authors: list[dict[str, Any]], has_api_reference: bool, - has_user_guide: Callable[[], bool], + user_guide_entry: Callable[[], str | None], llms_txt: Sequence[str], report: Callable[[str], None], ) -> Path: @@ -162,10 +162,9 @@ def write_readme( The configured authors, with local portrait paths replaced by site URLs. has_api_reference Whether the site has an API reference, which a landing page links to. - has_user_guide - A callback that reports whether the site has a user guide. User guide discovery - reports directory problems, so the callback is called only for a landing page, - which links to the guide when present. + user_guide_entry + Supplies the guide's first published page for a landing page link, or `None` if + the site has no guide. llms_txt The `llms.txt` files the site publishes, which the sidebar links to. report @@ -196,7 +195,7 @@ def write_readme( package_name, metadata.get("description", ""), reference_index=f"{config.reference_output}/index.qmd" if has_api_reference else None, - has_user_guide=has_user_guide(), + user_guide_entry=user_guide_entry(), ) else: source_file = sources[0] diff --git a/great_docs/_website/navigation/navbar.py b/great_docs/_website/navigation/navbar.py index ee6aaf33..5358ac06 100644 --- a/great_docs/_website/navigation/navbar.py +++ b/great_docs/_website/navigation/navbar.py @@ -45,8 +45,8 @@ class OwnItem: target: str | None """ - The item's exact `href`, a directory prefix ending in `/`, or `None` for the reference - directory + The item's exact `href`, a directory prefix ending in `/`, or `None` for a + directory named by the site's configuration """ def label(self, config: Config) -> str: @@ -83,13 +83,16 @@ def owns(self, href: object, config: Config) -> bool: """ if not isinstance(href, str): return False - target = self.target if self.target is not None else f"{config.reference_output}/" + target = self.target + if target is None: + directory = config.user_guide_output if self is USER_GUIDE else config.reference_output + target = f"{directory}/" if target.endswith("/"): return href.startswith(target) return href == target -USER_GUIDE = OwnItem("User Guide", "user_guide", "user-guide/") +USER_GUIDE = OwnItem("User Guide", "user_guide", None) RECIPES = OwnItem("Recipes", "recipes", "recipes/") REFERENCE = OwnItem("Reference", "reference", None) CHANGELOG = OwnItem("Changelog", "changelog", "changelog.qmd") diff --git a/great_docs/_website/page_scan.py b/great_docs/_website/page_scan.py index 4dfc6e96..cd1f6282 100644 --- a/great_docs/_website/page_scan.py +++ b/great_docs/_website/page_scan.py @@ -55,7 +55,7 @@ def content_dirs(config: Config, layout: Layout, *, reference: bool) -> list[Con """ List the build directory's authored page directories - Directories appear in this order: `user-guide/`, `recipes/`, the reference directory + Directories appear in this order: the user guide, `recipes/`, the reference directory when requested, then each custom section's destination. Missing directories and duplicate paths are excluded. @@ -77,7 +77,7 @@ def content_dirs(config: Config, layout: Layout, *, reference: bool) -> list[Con """ build_dir = layout.build_dir candidates = [ - ContentDir(build_dir / "user-guide", "User Guide"), + ContentDir(build_dir / config.user_guide_output, "User Guide"), ContentDir(build_dir / "recipes", "Recipes"), ] if reference: diff --git a/great_docs/_website/resources.py b/great_docs/_website/resources.py index e37514de..ab8d66b9 100644 --- a/great_docs/_website/resources.py +++ b/great_docs/_website/resources.py @@ -61,7 +61,7 @@ def register(quarto_config: dict[str, Any], config: Config, layout: Layout) -> N build_dir = layout.build_dir resources = [ *_marimo(config, build_dir), - *_asset_dirs(build_dir / "user-guide", build_dir), + *_asset_dirs(build_dir / config.user_guide_output, build_dir), *(["assets/**"] if (build_dir / "assets").is_dir() else []), "_shared/**", *_section_asset_dirs(config, layout), diff --git a/great_docs/_website/seo/sitemap.py b/great_docs/_website/seo/sitemap.py index 35162743..1973ddaf 100644 --- a/great_docs/_website/seo/sitemap.py +++ b/great_docs/_website/seo/sitemap.py @@ -9,6 +9,9 @@ import re from datetime import datetime from typing import TYPE_CHECKING +from urllib.parse import quote + +from ..._content.naming import DEFAULT_USER_GUIDE_OUTPUT if TYPE_CHECKING: from collections.abc import Callable @@ -29,7 +32,7 @@ """ -def page_type(path: str, reference_dir: str) -> str: +def page_type(path: str, reference_dir: str, guide_dir: str = DEFAULT_USER_GUIDE_OUTPUT) -> str: """ Classify a rendered page for its sitemap settings @@ -40,6 +43,8 @@ def page_type(path: str, reference_dir: str) -> str: backslashes are accepted as separators. reference_dir The directory of the API, CLI and MCP references. + guide_dir + The directory of the user guide. Returns ------- @@ -53,7 +58,7 @@ def page_type(path: str, reference_dir: str) -> str: return "homepage" elif path.startswith(f"{reference_dir}/"): return "reference" - elif path.startswith("user-guide/"): + elif path.startswith(f"{guide_dir}/"): return "user_guide" elif path == "changelog.html": return "changelog" @@ -117,7 +122,7 @@ def write( entries: list[tuple[float, str, str, str]] = [] for html_file in site_dir.rglob("*.html"): rel_path = html_file.relative_to(site_dir).as_posix() - kind = page_type(rel_path, config.reference_output) + kind = page_type(rel_path, config.reference_output, config.user_guide_output) # Keep internal site files and the page for missing addresses out of search-engine # discovery. @@ -141,9 +146,9 @@ def write( if rel_path == "index.html": loc = base_url elif rel_path.endswith("/index.html"): - loc = base_url + rel_path[: -len("index.html")] + loc = base_url + quote(rel_path[: -len("index.html")]) else: - loc = base_url + rel_path + loc = base_url + quote(rel_path) lastmod = datetime.fromtimestamp(html_file.stat().st_mtime).strftime("%Y-%m-%d") entries.append( diff --git a/great_docs/config.py b/great_docs/config.py index 4c6882c1..01b83951 100644 --- a/great_docs/config.py +++ b/great_docs/config.py @@ -37,6 +37,7 @@ from yaml12 import read_yaml from ._config_compat import normalise_member_placement +from ._content.naming import DEFAULT_USER_GUIDE_OUTPUT from ._yaml import YamlMapping if TYPE_CHECKING: @@ -83,6 +84,7 @@ def _load_default_config() -> ConfigDict: # A directory name visible to Quarto and safe to use in a URL. _REFERENCE_OUTPUT_SEGMENT = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_-]*") +_CONTENT_OUTPUT_SEGMENT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_ -]*") class ConfigError(ValueError): @@ -184,6 +186,7 @@ def _load_config(self) -> ConfigDict: raise ConfigError(f"{self.config_path}: reference.{key} must be true or false.") self._validate_reference_output(options.get("output"), self.config_path) + self._validate_content_paths(config) config = self._normalize_shorthands(config) self._validate_repository(config) extension = config["api_reference_extension"] @@ -388,6 +391,45 @@ def _validate_quarto(value: object, config_path: Path) -> None: f"{FULL_PREFIX!r}, which Great Docs reserves for its own sidebars." ) + def _validate_content_paths(self, config: ConfigDict) -> None: + """Validate the configured paths of guides and sections""" + guide = config["user_guide"] + if isinstance(guide, dict): + options = cast("ConfigDict", guide) + self._validate_content_output(options.get("output"), "user_guide.output") + if options.get("dir") is not None and not isinstance(options["dir"], str): + raise ConfigError(f"{self.config_path}: user_guide.dir must be a directory path.") + if options.get("sections") is not None and not isinstance(options["sections"], list): + raise ConfigError(f"{self.config_path}: user_guide.sections must be a list.") + entries = config["sections"] + if isinstance(entries, list): + for index, entry in enumerate(cast("list[object]", entries), start=1): + if not isinstance(entry, dict): + continue + section = cast("ConfigDict", entry) + key = f"sections[{index}]" + self._validate_content_output(section.get("output"), f"{key}.output") + if "keep_numeric_prefixes" in section and not isinstance( + section["keep_numeric_prefixes"], bool + ): + raise ConfigError( + f"{self.config_path}: {key}.keep_numeric_prefixes must be true or false." + ) + + def _validate_content_output(self, value: object, key: str) -> None: + """Require a relative path Quarto can discover through its render globs""" + if value is None: + return + if not isinstance(value, str) or not all( + _CONTENT_OUTPUT_SEGMENT.fullmatch(part) and part == part.rstrip() + for part in value.split("/") + ): + raise ConfigError( + f"{self.config_path}: {key}: {value!r} must be a relative directory path. " + "Each directory name must start with a letter or digit and may contain " + "letters, digits, hyphens, underscores and internal spaces." + ) + @staticmethod def _validate_reference_output(value: object, config_path: Path) -> None: """ @@ -1447,29 +1489,43 @@ def homepage(self) -> str: return value @property - def user_guide(self) -> str | list[Any] | None: + def user_guide(self) -> str | list[Any] | ConfigDict | None: """ Get the user guide configuration - Returns - ------- - : - - None: auto-discover from conventional directories - - str: custom directory path for user guide files - - list: explicit section ordering (list of section dicts) + A string selects the source directory. A list orders the sections and pages. + A mapping can set both and name the published directory. A null value finds + pages in the conventional source directory. """ return self["user_guide"] @property def user_guide_is_explicit(self) -> bool: - """Check if user guide uses explicit section ordering.""" - return isinstance(self["user_guide"], list) + """Check whether the user guide lists its pages""" + return self.user_guide_sections is not None @property def user_guide_dir(self) -> str | None: - """Get the user guide directory path (only when it's a string).""" - val = self["user_guide"] - return val if isinstance(val, str) else None + """Get the configured source directory of the user guide""" + guide = self.user_guide + if isinstance(guide, dict): + return guide.get("dir") + return guide if isinstance(guide, str) else None + + @property + def user_guide_sections(self) -> list[Any] | None: + """Get the configured user guide sections in reading order""" + guide = self.user_guide + if isinstance(guide, dict): + return guide.get("sections") + return guide if isinstance(guide, list) else None + + @property + def user_guide_output(self) -> str: + """Get the published directory of the user guide""" + guide = self.user_guide + output = guide.get("output") if isinstance(guide, dict) else None + return output if isinstance(output, str) else DEFAULT_USER_GUIDE_OUTPUT @property def reference_enabled(self) -> bool: diff --git a/tests/test_build_content.py b/tests/test_build_content.py index d3e431d0..62128711 100644 --- a/tests/test_build_content.py +++ b/tests/test_build_content.py @@ -2468,6 +2468,64 @@ def test_notebooks_publish_with_saved_outputs_and_navigation(tmp_path: Path) -> assert {"text": "Root notebook", "href": "root.ipynb"} in website["navbar"]["left"] +def test_configured_guide_and_section_outputs_keep_numbered_urls(tmp_path: Path) -> None: + notebook = _notebook("# Notebook\n[Guide](../../user_guide/01-intro.qmd)\n") + docs = _project( + tmp_path, + { + "great-docs.yml": """user_guide: + dir: user_guide + output: Manual/Quick Start + sections: + - section: Introduction + contents: [01-intro.qmd] +sections: + - title: Examples + dir: examples + output: Example Pages + keep_numeric_prefixes: true + index: true +site_root: + files: [examples/01-nested/download.csv] +""", + "user_guide/01-intro.qmd": "[Example](../examples/01-nested/007-demo.ipynb)\n", + "examples/01-nested/007-demo.ipynb": json.dumps(notebook), + "examples/01-nested/download.csv": "value\n17\n", + "examples/01-nested/_metadata.yml": "freeze: auto", + }, + ) + run = make_run(docs, user_guide=discover_user_guide(docs)) + config = docs._config + layout = docs.layout + content.user_guide(run, config, layout, page_authors=run.page_authors, remote=StubRemote()) + content.sections(run, config, layout, page_authors=run.page_authors) + content.site_root_files(run, config, layout) + apply_contributions(docs, run) + + build = layout.build_dir + guide = "Manual/Quick Start/01-intro.qmd" + section = "Example Pages/01-nested" + assert ( + "[Example](../../Example%20Pages/01-nested/007-demo.ipynb)" in (build / guide).read_text() + ) + published = json.loads((build / section / "007-demo.ipynb").read_text()) + assert ( + published["cells"][0]["source"][1] == "[Guide](../../Manual/Quick%20Start/01-intro.qmd)\n" + ) + assert published["cells"][1] == notebook["cells"][1] + assert (build / section / "_metadata.yml").read_text() == "freeze: auto" + assert (build / section / "download.csv").read_text() == "value\n17\n" + + quarto = read_quarto_yml(build) + website = quarto["website"] + guide_sidebar = next(sidebar for sidebar in website["sidebar"] if sidebar["id"] == "user-guide") + assert guide_sidebar["contents"][0]["contents"][0]["href"] == guide + assert {"text": "User Guide", "href": guide} in website["navbar"]["left"] + assert {"text": "Examples", "href": "Example Pages/index.qmd"} in website["navbar"]["left"] + assert 'href="01-nested/007-demo.ipynb"' in (build / "Example Pages/index.qmd").read_text() + assert f"/{section}/download.csv" in run.quarto_config["project"]["resources"] + + def test_markdown_page_directories_copy_linked_assets_and_leave_unlisted_files( tmp_path: Path, ) -> None: diff --git a/tests/test_build_outputs.py b/tests/test_build_outputs.py index 78e4bea6..947027fd 100644 --- a/tests/test_build_outputs.py +++ b/tests/test_build_outputs.py @@ -137,6 +137,29 @@ def test_validate_allows_content_beside_nested_reference( outputs.validate(config, layout) +@pytest.mark.parametrize( + ("settings", "message"), + [ + ("user_guide: {output: Assets/guide}\n", "great docs.*assets"), + ( + "user_guide: {output: Manuals/start}\nsections: [{title: Manuals, dir: manuals}]\n", + "overlaps 'manuals/'", + ), + ( + "sections: [{title: One, dir: one, output: Manuals}, " + "{title: Two, dir: two, output: manuals}]\n", + "overlaps 'manuals/'", + ), + ], +) +def test_validate_rejects_conflicting_authored_outputs( + tmp_path: Path, settings: str, message: str +) -> None: + config = write_config(tmp_path, settings) + with pytest.raises(ValueError, match=f"(?i){message}"): + outputs.validate(config, Layout.make(tmp_path)) + + def test_validate_rejects_file_where_a_reference_parent_is_created(tmp_path: Path) -> None: config = write_config(tmp_path, "reference: {output: pkg/api}\nsite_root: {files: [pkg]}\n") (tmp_path / "pkg").write_text("A raw site file.\n", encoding="utf-8") diff --git a/tests/test_homepage.py b/tests/test_homepage.py index dc262305..ab433ffe 100644 --- a/tests/test_homepage.py +++ b/tests/test_homepage.py @@ -276,7 +276,9 @@ def find_executable(cmd: str) -> str | None: def test_landing_page_shows_name_description_and_install(): - page = landing.markdown("fancy-lib", "Fancy things", reference_index=None, has_user_guide=False) + page = landing.markdown( + "fancy-lib", "Fancy things", reference_index=None, user_guide_entry=None + ) assert page.startswith("## fancy-lib\n\nFancy things\n") assert "pip install fancy-lib" in page @@ -284,7 +286,7 @@ def test_landing_page_shows_name_description_and_install(): def test_landing_page_without_a_name_or_description(): - page = landing.markdown(None, "", reference_index=None, has_user_guide=False) + page = landing.markdown(None, "", reference_index=None, user_guide_entry=None) assert page.startswith("## Package\n\n### Installation") @@ -292,11 +294,12 @@ def test_landing_page_without_a_name_or_description(): @pytest.mark.parametrize(("api", "guide"), [(True, False), (False, True), (True, True)]) def test_landing_page_links_the_sections_the_site_has(api: bool, guide: bool): index = "api/index.qmd" if api else None - page = landing.markdown("pkg", "", reference_index=index, has_user_guide=guide) + entry = "manual/Quick Start/intro.qmd" if guide else None + page = landing.markdown("pkg", "", reference_index=index, user_guide_entry=entry) assert "### Get Started" in page assert ("(api/index.qmd)" in page) == api - assert ("user-guide/index.qmd" in page) == guide + assert ("manual/Quick%20Start/intro.qmd" in page) == guide def test_extract_takes_badges_after_the_heading(): diff --git a/tests/test_layout_migration.py b/tests/test_layout_migration.py index 028ae3f9..23e8ab6a 100644 --- a/tests/test_layout_migration.py +++ b/tests/test_layout_migration.py @@ -892,6 +892,32 @@ def test_section_dir_under_destination_stays_in_place(project: Path) -> None: ) +def test_layout_move_keeps_configured_published_paths(project: Path) -> None: + put( + project, + "great-docs.yml", + """user_guide: {dir: docs/guide, output: manuals/start} +sections: + - dir: docs/examples + output: Archived Examples + keep_numeric_prefixes: true +""", + ) + put(project, "docs/guide/notes.qmd", "[Example](../../Archived%20Examples/01-example.html)\n") + put(project, "docs/examples/01-example.qmd", "# Example\n") + result = analyse(Layout.make(project), Path("docs")) + assert not result.blockers + edit = next(edit for edit in result.edits if edit.path == project / "great-docs.yml") + config = read_yaml(io.StringIO(edit.after.decode())) + assert config["user_guide"] == {"dir": "guide", "output": "manuals/start"} + assert config["sections"] == [ + {"dir": "examples", "output": "Archived Examples", "keep_numeric_prefixes": True} + ] + assert not any("Published path for this section changes" in note for note in result.follow_up) + note = next(edit for edit in result.edits if edit.path.name == "notes.qmd") + assert note.after.decode() == "[Example](../Archived%20Examples/01-example.html)\n" + + def test_destination_nested_inside_source_still_blocks(project: Path) -> None: put(project, "great-docs.yml", "user_guide: docs\n") put(project, "docs/guide.md", "# Guide\n") From 215b27995a6c7e3d106c6367d379ade842f5a52b Mon Sep 17 00:00:00 2001 From: Hassan Kibirige Date: Fri, 4 Dec 2026 14:26:56 +0300 Subject: [PATCH 2/2] fix: preserve sidebar IDs when section URLs change --- great_docs/_build/content.py | 2 +- great_docs/_content/sections.py | 23 ++++++++++++++++------- tests/test_build_content.py | 13 +++++++++++++ 3 files changed, 30 insertions(+), 8 deletions(-) diff --git a/great_docs/_build/content.py b/great_docs/_build/content.py index daff0c18..14c091aa 100644 --- a/great_docs/_build/content.py +++ b/great_docs/_build/content.py @@ -486,7 +486,7 @@ def sections( if not found: return "No sections to process" - section_ids = {section.output for section in found} + section_ids = {section.sidebar_id for section in found} generated_ids = { sidebar.id for contribution in run.contributions for sidebar in contribution.sidebars } diff --git a/great_docs/_content/sections.py b/great_docs/_content/sections.py index 489f6f06..a4f2c558 100644 --- a/great_docs/_content/sections.py +++ b/great_docs/_content/sections.py @@ -100,6 +100,9 @@ class Section: output: str """The destination relative to the build directory, in POSIX form""" + sidebar_id: str + """The navigation ID based on the source directory's default output""" + show_sidebar: bool """Whether the section can generate a sidebar for multiple pages""" @@ -249,6 +252,8 @@ def read(config: Config, layout: Layout, *, report: Callable[[str], None]) -> li # Tag and status scanning find pages at the same destination destination = section_destination(layout, options) assert destination is not None + default_destination = section_destination(layout, {"dir": directory}) + assert default_destination is not None sections.append( Section( title=title, @@ -259,6 +264,7 @@ def read(config: Config, layout: Layout, *, report: Callable[[str], None]) -> li files=tuple(files), destination=destination, output=destination.relative_to(layout.build_dir).as_posix(), + sidebar_id=default_destination.relative_to(layout.build_dir).as_posix(), show_sidebar=show_sidebar, index=bool(options.get("index", False)), index_columns=options.get("index_columns", 2), @@ -374,6 +380,7 @@ def publish( section.output, copied, has_index=has_user_index or section.index, + sidebar_id=section.sidebar_id, index_name=index.name, dir_titles=section.dir_titles, sidebar_groups=section.sidebar_groups, @@ -936,10 +943,11 @@ def _card_text(entry: Page, title_style: str, desc_style: str) -> list[str]: def sidebar( title: str, - slug: str, + output: str, pages: Sequence[Page], *, has_index: bool, + sidebar_id: str | None = None, index_name: str = "index.qmd", dir_titles: dict[str, str] | None = None, sidebar_groups: list[dict[str, Any]] | None = None, @@ -957,12 +965,14 @@ def sidebar( ---------- title The section's title. - slug + output The section's directory relative to the build directory. pages The section's pages. has_index Whether the section has an index page. + sidebar_id + The ID users can refer to in navigation settings. Defaults to the section's output. index_name The file name of the section's index, when it has one. dir_titles @@ -973,8 +983,7 @@ def sidebar( Returns ------- : - The sidebar, with `slug` as its `id`, or `None` if the section has at most one - page, including its index. + The sidebar, or `None` if the section has at most one page, including its index. """ by_filename = {page["filename"]: page for page in pages if page["filename"] != index_name} # Count pages, including the index: one top-level subdirectory can contain @@ -987,10 +996,10 @@ def sidebar( label = title if index_name.endswith(notebooks.SUFFIX): label = next(page["title"] for page in pages if page["filename"] == index_name) - contents.append({"text": label, "href": f"{slug}/{index_name}"}) + contents.append({"text": label, "href": f"{output}/{index_name}"}) def link(page: Page) -> dict[str, Any]: - return {"text": page["title"], "href": f"{slug}/{page['filename']}"} + return {"text": page["title"], "href": f"{output}/{page['filename']}"} for group in _page_groups(pages, dir_titles=dir_titles, sidebar_groups=sidebar_groups): links = [link(page) for page in group.pages] @@ -999,7 +1008,7 @@ def link(page: Page) -> dict[str, Any]: else: contents.extend(links) - return {"id": slug, "title": title, "contents": contents} + return {"id": sidebar_id or output, "title": title, "contents": contents} def add_no_sidebar_class( diff --git a/tests/test_build_content.py b/tests/test_build_content.py index 62128711..fe534c8c 100644 --- a/tests/test_build_content.py +++ b/tests/test_build_content.py @@ -20,6 +20,7 @@ from great_docs._build.ownership import QUARTO_YML_HEADER from great_docs._build.steps import Outcome, Skipped from great_docs._contribution import Contribution, NavbarLink +from great_docs._website import website_overlay from great_docs._website.quarto_yml import apply as apply_contribution from great_docs._website.quarto_yml import edit as edit_quarto_yml from great_docs._website.quarto_yml import read as read_quarto_yml @@ -2487,6 +2488,12 @@ def test_configured_guide_and_section_outputs_keep_numbered_urls(tmp_path: Path) index: true site_root: files: [examples/01-nested/download.csv] +quarto: + website: + sidebar: + - id: examples + title: Example archive + contents: ["{{ contents }}"] """, "user_guide/01-intro.qmd": "[Example](../examples/01-nested/007-demo.ipynb)\n", "examples/01-nested/007-demo.ipynb": json.dumps(notebook), @@ -2517,9 +2524,15 @@ def test_configured_guide_and_section_outputs_keep_numbered_urls(tmp_path: Path) assert (build / section / "download.csv").read_text() == "value\n17\n" quarto = read_quarto_yml(build) + website_overlay.apply( + quarto, config, layout, content.page_map(config, layout, run.user_guide), report=pytest.fail + ) website = quarto["website"] guide_sidebar = next(sidebar for sidebar in website["sidebar"] if sidebar["id"] == "user-guide") assert guide_sidebar["contents"][0]["contents"][0]["href"] == guide + section_sidebar = next(sidebar for sidebar in website["sidebar"] if sidebar["id"] == "examples") + assert section_sidebar["title"] == "Example archive" + assert section_sidebar["contents"][1]["contents"][0]["href"] == f"{section}/007-demo.ipynb" assert {"text": "User Guide", "href": guide} in website["navbar"]["left"] assert {"text": "Examples", "href": "Example Pages/index.qmd"} in website["navbar"]["left"] assert 'href="01-nested/007-demo.ipynb"' in (build / "Example Pages/index.qmd").read_text()