From c66ac95b1d007e640766d6acee7e5588181f535b Mon Sep 17 00:00:00 2001 From: Hassan Kibirige Date: Fri, 4 Dec 2026 15:20:44 +0300 Subject: [PATCH] fix: build documentation from sibling package directories Let a documentation configuration select its package directory so monorepo sites keep package metadata and API discovery. Keep the generated site, Quarto project and cache alongside the configuration. --- docs/user_guide/05-configuration.qmd | 14 +++++++ great_docs/_build/facts.py | 6 +-- great_docs/_build/from_repo.py | 4 +- great_docs/_build/outputs.py | 5 ++- great_docs/_build/passes.py | 21 +++++++++- great_docs/_build/prepare.py | 2 +- great_docs/_checks/lint.py | 2 + great_docs/_cli/build.py | 18 +++++---- great_docs/_cli/project.py | 13 +++--- great_docs/_project/layout.py | 50 ++++++++++++++++++------ great_docs/_project/scaffold.py | 41 +++++++++++++------ great_docs/assets/great-docs.default.yml | 7 ++++ great_docs/config.py | 49 ++++++++++++----------- great_docs/core.py | 5 ++- tests/test_cli.py | 18 +++++++++ tests/test_config_defaults.py | 1 + tests/test_great_docs.py | 6 +-- tests/test_layout.py | 48 +++++++++++++++++++++++ 18 files changed, 233 insertions(+), 77 deletions(-) diff --git a/docs/user_guide/05-configuration.qmd b/docs/user_guide/05-configuration.qmd index 5c7032731..b6c3f634d 100644 --- a/docs/user_guide/05-configuration.qmd +++ b/docs/user_guide/05-configuration.qmd @@ -38,6 +38,20 @@ To generate a starter configuration file with all options documented: great-docs config ``` +### Documentation in a monorepo + +Set `package_root` when the documentation and package live in separate directories. +For example, if your repository contains `docs/great-docs.yml` and +`python/my_package/pyproject.toml`, add: + +```{.yaml filename="docs/great-docs.yml"} +package_root: ../python/my_package +``` + +Run `great-docs build --config docs/great-docs.yml` from the repository root. +Great Docs reads the package metadata and API from the selected package directory. +Documentation paths remain relative to `docs/`, and the site is built into `docs/_site/`. + ## Display Name By default, Great Docs uses your package name exactly as-is for the site title and navbar. For diff --git a/great_docs/_build/facts.py b/great_docs/_build/facts.py index 24951f17b..bf29ce52f 100644 --- a/great_docs/_build/facts.py +++ b/great_docs/_build/facts.py @@ -25,7 +25,7 @@ from .._project.repository import Repository from ..config import Config -__all__ = ["Facts", "exact_tag", "source_links", "source_ref"] +__all__ = ["Facts", "checkout_root", "exact_tag", "source_links", "source_ref"] @dataclass(frozen=True) @@ -110,11 +110,11 @@ def source_links( ref=source_ref(config, package_root, warn=warn), package_root=package_root, path=config.source_path, - repository_root=None if config.source_path else _checkout_root(package_root), + repository_root=None if config.source_path else checkout_root(package_root), ) -def _checkout_root(package_root: Path) -> Path | None: +def checkout_root(package_root: Path) -> Path | None: """ Find the Git checkout that contains the package diff --git a/great_docs/_build/from_repo.py b/great_docs/_build/from_repo.py index 96b45e5f7..280f4802a 100644 --- a/great_docs/_build/from_repo.py +++ b/great_docs/_build/from_repo.py @@ -121,7 +121,7 @@ def build( else Path.cwd() / layout.site_dir.relative_to(checkout.resolve()) ) _check_replaceable(output_path) - scripts = _install(checkout, Path(temporary) / "venv", report=report) + scripts = _install(layout.package_root, Path(temporary) / "venv", report=report) report("🔨 Building documentation...") command = [str(scripts / _executable("great-docs")), "build"] @@ -293,7 +293,7 @@ def _clone( selected = (checkout / config_path).resolve() if config_path else None if selected is not None and not selected.is_relative_to(checkout.resolve()): raise LayoutError("Remote configuration must remain inside the checkout") - layout = Layout.make(checkout, selected) + layout = Layout.make(checkout, selected, checkout=checkout) # Fetch failures leave the shallow history, which builds with fewer features if not shallow: diff --git a/great_docs/_build/outputs.py b/great_docs/_build/outputs.py index cb3b181ff..7eacdf68f 100644 --- a/great_docs/_build/outputs.py +++ b/great_docs/_build/outputs.py @@ -7,6 +7,7 @@ from __future__ import annotations +import os import shutil from dataclasses import replace from pathlib import Path @@ -299,12 +300,12 @@ def remove(layout: Layout, *, report: Callable[[str], None]) -> None: config_path = layout.config_path if config_path.exists(): config_path.unlink() - report(f"Removed {config_path.relative_to(layout.package_root)}") + report(f"Removed {os.path.relpath(config_path, layout.package_root)}") for build_dir in builds: if build_dir.exists(): shutil.rmtree(build_dir) - report(f"Removed {build_dir.relative_to(layout.package_root)}/ directory") + report(f"Removed {os.path.relpath(build_dir, layout.package_root)}/ directory") if layout.source_dir != layout.package_root: if layout.site_dir.exists(): shutil.rmtree(layout.site_dir) diff --git a/great_docs/_build/passes.py b/great_docs/_build/passes.py index f569eb7b2..d828ade35 100644 --- a/great_docs/_build/passes.py +++ b/great_docs/_build/passes.py @@ -8,13 +8,16 @@ from __future__ import annotations +import os +from pathlib import Path from typing import TYPE_CHECKING from .._term_player import prerender as term_prerender from .._website import prerender, quarto_yml, repo_links from .._website.homepage import aliases from .._website.navigation import shared_sidebar -from . import content, freeze +from .._yaml import YamlValue +from . import content, facts, freeze from .steps import Outcome, Skipped if TYPE_CHECKING: @@ -205,7 +208,21 @@ def repository_links(run: Run, config: Config, layout: Layout, log: BuildLog) -> `None`; the result is a detail line of the previous step. """ pages = content.page_map(config, layout, run.user_guide) - count = repo_links.prepare(layout.build_dir, run.quarto_config, pages, layout.package_root) + root = layout.package_root + if not layout.source_dir.is_relative_to(root): + checkout = facts.checkout_root(root) + root = ( + checkout + if checkout is not None and layout.source_dir.is_relative_to(checkout) + else Path(os.path.commonpath((root, layout.source_dir))) + ) + website: YamlValue = run.quarto_config.get("website") + if isinstance(website, dict) and isinstance(subdir := website.get("repo-subdir"), str): + # Quarto already includes this directory in the URL before the page path. + subdir_path = (root / subdir).resolve() + if subdir_path.is_relative_to(root) and layout.source_dir.is_relative_to(subdir_path): + root = subdir_path + count = repo_links.prepare(layout.build_dir, run.quarto_config, pages, root) if count: log.detail(f"Linking {count} page(s) to their authored sources") return None diff --git a/great_docs/_build/prepare.py b/great_docs/_build/prepare.py index ecd173588..2fa453903 100644 --- a/great_docs/_build/prepare.py +++ b/great_docs/_build/prepare.py @@ -78,7 +78,7 @@ def build_directory( If distinct scripts share a filename or a script uses a reserved filename. """ build_dir = layout.build_dir - print(f"Preparing build directory: {build_dir.relative_to(layout.package_root)}/") + print(f"Preparing build directory: {os.path.relpath(build_dir, layout.package_root)}/") outputs.validate(config, layout) diff --git a/great_docs/_checks/lint.py b/great_docs/_checks/lint.py index e902f5441..4651f3452 100644 --- a/great_docs/_checks/lint.py +++ b/great_docs/_checks/lint.py @@ -154,6 +154,8 @@ def run_lint( # Discovery and introspection print their progress; quiet mode discards it. with contextlib.redirect_stdout(io.StringIO()) if quiet else contextlib.nullcontext(): layout = Layout.make(project_root, Path(config_path) if config_path else None) + if not layout.source_dir.is_relative_to(layout.package_root): + project_root = layout.source_dir if fix: from .config_fix import fix_config_file diff --git a/great_docs/_cli/build.py b/great_docs/_cli/build.py index bce7b7a09..b91fd566a 100644 --- a/great_docs/_cli/build.py +++ b/great_docs/_cli/build.py @@ -538,7 +538,7 @@ def _extract_frontmatter(text: str) -> str: frontmatter = _extract_frontmatter(content) match = freeze_re.search(frontmatter) or exec_freeze_re.search(frontmatter) if match: - rel_path = str(qmd_file.relative_to(project_root)) + rel_path = os.path.relpath(qmd_file, project_root) per_page_modes[rel_path] = match.group(1).strip() if per_page_modes: @@ -635,9 +635,9 @@ def freeze( survive future builds. PAGES are paths to .qmd files relative to your project root (e.g., - 'docs/user_guide/benchmarks.qmd'). Quarto always executes code when rendering - individual files, even with freeze enabled (this is how you update - frozen outputs). + 'docs/user_guide/benchmarks.qmd'). If your documentation is outside the package + root, give paths relative to the configuration directory. Quarto always executes + code when rendering individual files, even with freeze enabled. Use '--clean' to wipe the entire '_freeze/' cache before re-executing. This forces a full refresh of all specified pages from scratch. @@ -672,7 +672,10 @@ def freeze( click.echo("Error: Specify at least one PAGE, or use --info.", err=True) sys.exit(1) - missing = [p for p in pages if not (project_root / p).is_file()] + page_root = ( + project_root if layout.source_dir.is_relative_to(project_root) else layout.source_dir + ) + missing = [p for p in pages if not (page_root / p).is_file()] if missing: for page in missing: click.echo(f"Error: Page not found: {page}", err=True) @@ -753,7 +756,8 @@ def freeze( build_freeze = build_dir / "_freeze" if build_freeze.is_dir() and rendered: click.echo() - click.echo(f"Persisting _freeze/ → {persist_dir.relative_to(project_root)}/") + cache_path = os.path.relpath(persist_dir, project_root) + click.echo(f"Persisting _freeze/ → {cache_path}/") updated_files = freeze_cache.merge( build_freeze, persist_dir, rendered_pages=rendered.values() ) @@ -762,7 +766,7 @@ def freeze( # Show git status hint click.echo() click.echo("To commit the updated freeze cache:") - click.echo(f" git add {persist_dir.relative_to(project_root)}/") + click.echo(f" git add {cache_path}/") click.echo(f' git commit -m "Update freeze cache for {", ".join(rendered)}"') elif not rendered: click.echo() diff --git a/great_docs/_cli/project.py b/great_docs/_cli/project.py index bd59a64f8..b5d251a51 100644 --- a/great_docs/_cli/project.py +++ b/great_docs/_cli/project.py @@ -14,7 +14,7 @@ from .._project import Project from .._project.layout import CONVENTIONAL_DOC_DIRS, Layout, _find_package_root from .._project.remote import HttpRemote -from .._project.scaffold import update_gitignore +from .._project.scaffold import update_gitignore, write_config_template from .._reference.exports import Exports from .._website import changelog as changelog_page from .._website import quarto_yml, website_overlay @@ -126,10 +126,6 @@ def config(project_path: str | None, force: bool, config_path: str | None = None great-docs config --force # Overwrite existing file great-docs config --project-path ../pkg """ - from pathlib import Path - - from ..config import create_default_config - try: project_root = Path(project_path) if project_path else Path.cwd() layout = Layout.make(project_root, Path(config_path) if config_path else None, create=True) @@ -142,9 +138,7 @@ def config(project_path: str | None, force: bool, config_path: str | None = None click.echo("Cancelled.") return - config_content = create_default_config() - config_path.parent.mkdir(parents=True, exist_ok=True) - config_path.write_text(config_content, encoding="utf-8") + write_config_template(layout) update_gitignore(layout, report=click.echo) click.echo(f"✓ Created {config_path}") click.echo("\nEdit this file to customize your documentation settings.") @@ -424,6 +418,9 @@ def migrate_layout( if candidate.is_file(): check_symlinks(candidate) layout = Layout.make(root, Path(config_path) if config_path else None) + if not layout.source_dir.is_relative_to(layout.package_root): + click.echo("No migration is needed. The documentation already has its own directory.") + return target = root / destination is_default_destination = ( ctx.get_parameter_source("destination") == click.core.ParameterSource.DEFAULT diff --git a/great_docs/_project/layout.py b/great_docs/_project/layout.py index 574565d01..4e696af30 100644 --- a/great_docs/_project/layout.py +++ b/great_docs/_project/layout.py @@ -3,10 +3,10 @@ from __future__ import annotations import re -from dataclasses import dataclass -from pathlib import Path +from dataclasses import dataclass, field +from pathlib import Path, PureWindowsPath -from ..config import Config +from ..config import Config, read_user_settings _PROJECT_MANIFESTS = ("pyproject.toml", "setup.py", "go.mod", "Cargo.toml") CONVENTIONAL_DOC_DIRS = ("docs", "docs-website", "doc", "website") @@ -30,6 +30,7 @@ class Layout: site_dir: Path freeze_dir: Path cache_dir: Path + package_root_override: str | None = field(default=None, kw_only=True) @classmethod def make( @@ -38,13 +39,15 @@ def make( config_path: Path | None = None, *, create: bool = False, + checkout: Path | None = None, ) -> Layout: """ Resolve a documentation layout from project context Automatic selection considers configuration files at the package root - and in `docs/`, `docs-website/`, `doc/`, or `website/`. An explicit - configuration must remain within the discovered package root. + and in `docs/`, `docs-website/`, `doc/`, or `website/`. A configuration + can set `package_root` relative to its directory. This also permits + a configuration outside the discovered package root. Parameters ---------- @@ -56,6 +59,8 @@ def make( create Permit a missing explicit file or select `docs/great-docs.yml` when neither conventional configuration exists. + checkout + Limit the configuration and package to a cloned repository. Returns ------- @@ -66,17 +71,37 @@ def make( ------ LayoutError If automatic selection is ambiguous, an explicit file is missing, - or the selected configuration is outside the package root. + or the configuration and package directories are incompatible. """ package_root = _find_package_root(project_path.resolve()) - selected = _select_config(package_root, config_path, create=create) - resolved_config = selected.resolve() - if not resolved_config.is_relative_to(package_root): + selected = _select_config(package_root, config_path, create=create).resolve() + if checkout is not None: + checkout = checkout.resolve() + if not selected.is_relative_to(checkout): + raise LayoutError("Remote configuration must remain inside the checkout") + source_dir = selected.parent + override: object = read_user_settings(selected, report=lambda _: None).get("package_root") + if override is not None: + if ( + not isinstance(override, str) + or not override.strip() + or Path(override).is_absolute() + or PureWindowsPath(override).anchor + ): + raise LayoutError(f"{selected}: package_root must be a non-empty relative path") + package_root = (source_dir / override).resolve() + elif not selected.is_relative_to(package_root): raise LayoutError( - f"Configuration must be inside the package root {package_root}: {selected}" + f"Configuration must be inside the package root {package_root}: {selected}. " + "Set package_root in the configuration to select a separate package directory." ) + if checkout is not None and not package_root.is_relative_to(checkout): + raise LayoutError("Remote package root must remain inside the checkout") + if override is not None and not any( + (package_root / name).is_file() for name in _PROJECT_MANIFESTS + ): + raise LayoutError(f"{selected}: package_root has no project manifest: {package_root}") - source_dir = resolved_config.parent if source_dir == package_root: build_dir = package_root / "great-docs" site_dir = build_dir / "_site" @@ -88,12 +113,13 @@ def make( return cls( package_root=package_root, - config_path=resolved_config, + config_path=selected, source_dir=source_dir, build_dir=build_dir, site_dir=site_dir, freeze_dir=source_dir / "_freeze", cache_dir=cache_dir, + package_root_override=override, ) def is_reserved_directory(self, path: Path) -> bool: diff --git a/great_docs/_project/scaffold.py b/great_docs/_project/scaffold.py index b2d062639..15194db3a 100644 --- a/great_docs/_project/scaffold.py +++ b/great_docs/_project/scaffold.py @@ -27,7 +27,12 @@ from .layout import Layout from .manifest import Manifest -__all__ = ["format_authors_yaml", "update_gitignore", "write_initial_config"] +__all__ = [ + "format_authors_yaml", + "update_gitignore", + "write_config_template", + "write_initial_config", +] _YES = {"", "y", "yes"} @@ -44,6 +49,15 @@ _VERSIONING_COMMENT = "\n# Great Docs versioned-build artifacts\n" +def write_config_template(layout: Layout, overrides: dict[str, str] | None = None) -> None: + """Write the default configuration and retain an explicit package location""" + if layout.package_root_override is not None: + package_root = format_yaml({"package_root": layout.package_root_override}).strip() + overrides = {**(overrides or {}), "package_root": package_root} + layout.config_path.parent.mkdir(parents=True, exist_ok=True) + _ = layout.config_path.write_text(create_default_config(overrides), encoding="utf-8") + + def write_initial_config( config: Config, layout: Layout, @@ -89,13 +103,11 @@ def write_initial_config( ) return - config_path.parent.mkdir(parents=True, exist_ok=True) - if not project.name or not (importable_name := project.importable_name): report("Warning: Could not detect package name, creating minimal config") # Keep active defaults even when no package can be inspected. minimal_overrides = {"parser": "parser: numpy", "dynamic": "dynamic: true"} - _ = config_path.write_text(create_default_config(minimal_overrides), encoding="utf-8") + write_config_template(layout, minimal_overrides) report(f"Created {config_path}") return @@ -130,7 +142,7 @@ def write_initial_config( package, package.members, report=report ) overrides["dynamic"] = f"dynamic: {'true' if dynamic_mode else 'false'}" - _ = config_path.write_text(create_default_config(overrides), encoding="utf-8") + write_config_template(layout, overrides) report(f"Created {config_path}") return @@ -151,7 +163,7 @@ def write_initial_config( if " - title:" in reference_yaml: overrides["reference"] = reference_yaml - _ = config_path.write_text(create_default_config(overrides), encoding="utf-8") + write_config_template(layout, overrides) report(f"Created {config_path}") @@ -182,14 +194,18 @@ def update_gitignore( `input` does. An empty answer, `y` or `yes` approves the change. If `None`, the file is updated without asking. """ - gitignore_path = layout.package_root / ".gitignore" - if layout.source_dir != layout.package_root: - source = layout.source_dir.relative_to(layout.package_root).as_posix() + if layout.source_dir.is_relative_to(layout.package_root): + ignore_root = layout.package_root + prefix = f"/{layout.source_dir.relative_to(ignore_root).as_posix()}" + else: + ignore_root = layout.source_dir + prefix = "" + gitignore_path = ignore_root / ".gitignore" entries = [ - f"/{source}/_quarto/", - f"/{source}/_site/", - f"/{source}/.cache/", + f"{prefix}/_quarto/", + f"{prefix}/_site/", + f"{prefix}/.cache/", "/.great-docs-build/", "/.great-docs/", ] @@ -202,6 +218,7 @@ def update_gitignore( ) return + gitignore_path = layout.package_root / ".gitignore" if not gitignore_path.exists(): if ask is not None: report("\nThe great-docs/ build directory is temporary and should not be committed.") diff --git a/great_docs/assets/great-docs.default.yml b/great_docs/assets/great-docs.default.yml index 9a5f1a334..e5c96e2c8 100644 --- a/great_docs/assets/great-docs.default.yml +++ b/great_docs/assets/great-docs.default.yml @@ -8,6 +8,13 @@ # from its directory, including assets, bibliography, CSS, and render hooks. # Keep package metadata and Python source paths relative to the package root. +# Package Root +# ------------ +# Use this when a repository keeps the docs and package in separate directories. +# : null - (default) detect the package root from the project directory +# : type(str) - path from this file to the package directory, e.g. ../python/my_package +package_root: null + # Module Name # ----------- # Importable module name, when it differs from the project name diff --git a/great_docs/config.py b/great_docs/config.py index 3585ef773..a921dc89e 100644 --- a/great_docs/config.py +++ b/great_docs/config.py @@ -41,6 +41,7 @@ from ._yaml import YamlMapping if TYPE_CHECKING: + from collections.abc import Callable from typing import Any, TypeAlias ConfigDict: TypeAlias = dict[str, Any] @@ -91,6 +92,30 @@ class ConfigError(ValueError): """A configuration value that great-docs cannot build with""" +def read_user_settings(path: Path, *, report: Callable[[str], None]) -> ConfigDict: + """Read authored settings and report unreadable or non-mapping configuration""" + try: + with open(path, encoding="utf-8") as file: + value = read_yaml(file) + except FileNotFoundError: + return {} + except ValueError as error: + report(f"Warning: Error parsing great-docs.yml: {error}") + return {} + except OSError as error: + report(f"Warning: Could not read great-docs.yml: {error}") + return {} + + if isinstance(value, dict): + return cast("ConfigDict", value) + if value is not None: + report( + "Warning: great-docs.yml must be a mapping of options; " + f"got {type(value).__name__}. Using defaults." + ) + return {} + + class Config: """ Configuration manager for Great Docs. @@ -137,29 +162,7 @@ def _load_config(self) -> ConfigDict: The loaded configuration merged with defaults. """ config = copy.deepcopy(DEFAULT_CONFIG) - self._user_config: ConfigDict = {} - - if self.config_path.exists(): - try: - with open(self.config_path, "r", encoding="utf-8") as f: - user_config = read_yaml(f) - - if user_config is None: - user_config = {} - - if not isinstance(user_config, dict): - # A valid YAML document that isn't a mapping (a list, a bare - # scalar) has no config to contribute; the defaults stand. - print( - "Warning: great-docs.yml must be a mapping of options; " - f"got {type(user_config).__name__}. Using defaults." - ) - else: - self._user_config = cast("ConfigDict", user_config) - except ValueError as e: - print(f"Warning: Error parsing great-docs.yml: {e}") - except OSError as e: - print(f"Warning: Could not read great-docs.yml: {e}") + self._user_config = read_user_settings(self.config_path, report=print) normalised = normalise_member_placement( self._user_config, diff --git a/great_docs/core.py b/great_docs/core.py index efcb651bb..3a59db5df 100644 --- a/great_docs/core.py +++ b/great_docs/core.py @@ -88,8 +88,9 @@ def __init__( create Permit a missing configuration for initialisation without creating files. """ + self._project_path = Path(project_path or os.getcwd()).resolve() self.layout = Layout.make( - Path(project_path or os.getcwd()), + self._project_path, Path(config_path) if config_path else None, create=create, ) @@ -142,7 +143,7 @@ def install(self, force: bool = False) -> None: """ print("Initializing great-docs...") - self.layout = Layout.make(self.layout.package_root, self._selected_config_path, create=True) + self.layout = Layout.make(self._project_path, self._selected_config_path, create=True) project = Project.make(self._config, self.layout) write_initial_config( diff --git a/tests/test_cli.py b/tests/test_cli.py index a972630ed..a2763150d 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -431,6 +431,24 @@ def test_creation_selects_docs_or_custom_config( assert not (tmp_path / "great-docs.yml").exists() +@pytest.mark.parametrize("command", ["config", "init"]) +def test_config_regeneration_keeps_sibling_package_root(tmp_path: Path, command: str) -> None: + package = tmp_path / "python" / "example" + package.mkdir(parents=True) + (package / "pyproject.toml").write_text('[project]\nname = "example"\n') + source = tmp_path / "docs" + source.mkdir() + config = source / "great-docs.yml" + config.write_text("package_root: ../python/example\n") + + result = CliRunner().invoke(cli, [command, "--project-path", str(tmp_path), "--force"]) + + assert result.exit_code == 0, result.output + assert "package_root: ../python/example" in config.read_text() + assert not (package / "great-docs.yml").exists() + assert "/_quarto/" in (source / ".gitignore").read_text().splitlines() + + @pytest.mark.parametrize( ("selection", "ignore_entry"), [("great-docs.yml", "/great-docs/"), ("docs/great-docs.yml", "/docs/_quarto/")], diff --git a/tests/test_config_defaults.py b/tests/test_config_defaults.py index e0d165358..75ed53f2c 100644 --- a/tests/test_config_defaults.py +++ b/tests/test_config_defaults.py @@ -12,6 +12,7 @@ # great-docs.default.yml. Do NOT import DEFAULT_CONFIG for this constant -- # that would defeat the check. FROZEN_DEFAULT_CONFIG: dict[str, Any] = { + "package_root": None, "module": None, "display_name": None, "project_type": "python", diff --git a/tests/test_great_docs.py b/tests/test_great_docs.py index 19276a556..b0fe1ef3e 100644 --- a/tests/test_great_docs.py +++ b/tests/test_great_docs.py @@ -12877,9 +12877,9 @@ def test_cli_config_error(): """CLI config command handles errors gracefully.""" runner = CliRunner() - with patch("great_docs.config.create_default_config") as mock_create: - mock_create.side_effect = OSError("config error") - + with patch( + "great_docs._cli.project.write_config_template", side_effect=OSError("config error") + ): with tempfile.TemporaryDirectory() as tmp_dir: result = runner.invoke(config, ["--project-path", tmp_dir, "--force"]) assert result.exit_code == 1 diff --git a/tests/test_layout.py b/tests/test_layout.py index a9196c3bc..81d441a4e 100644 --- a/tests/test_layout.py +++ b/tests/test_layout.py @@ -242,6 +242,54 @@ def test_external_config_is_rejected(tmp_path: Path) -> None: Layout.make(project, config) +@pytest.mark.parametrize("explicit", [False, True]) +def test_config_selects_sibling_package_root(tmp_path: Path, explicit: bool) -> None: + package = tmp_path / "python" / "example" + package.mkdir(parents=True) + (package / "pyproject.toml").touch() + config = _write_config(tmp_path / "docs" / "great-docs.yml") + config.write_text("package_root: ../python/example\n") + + layout = Layout.make(package, config) if explicit else Layout.make(tmp_path) + + assert layout.package_root == package + assert layout.config_path == config + assert layout.source_dir == config.parent + assert layout.site_dir == config.parent / "_site" + assert layout.build_dir == config.parent / "_quarto/default" + assert layout.load_config().project_root == package + + +@pytest.mark.parametrize("value", ["''", "[]", "/tmp/package", "C:/package"]) +def test_package_root_requires_a_relative_path(tmp_path: Path, value: str) -> None: + config = _write_config(tmp_path / "great-docs.yml") + config.write_text(f"package_root: {value}\n") + + with pytest.raises(LayoutError, match="package_root must be a non-empty relative path"): + Layout.make(tmp_path) + + +def test_package_root_requires_a_project_manifest(tmp_path: Path) -> None: + (tmp_path / "package").mkdir() + config = _write_config(tmp_path / "great-docs.yml") + config.write_text("package_root: package\n") + + with pytest.raises(LayoutError, match="package_root has no project manifest"): + Layout.make(tmp_path) + + +def test_remote_package_root_cannot_escape_the_checkout(tmp_path: Path) -> None: + package = tmp_path / "package" + package.mkdir() + (package / "pyproject.toml").touch() + checkout = tmp_path / "repo" + config = _write_config(checkout / "docs" / "great-docs.yml") + config.write_text("package_root: ../../package\n") + + with pytest.raises(LayoutError, match="package root must remain inside the checkout"): + Layout.make(checkout, checkout=checkout) + + def test_symlinked_config_cannot_escape_package_root(tmp_path: Path) -> None: project = tmp_path / "project" project.mkdir()