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
48 changes: 48 additions & 0 deletions docs/user_guide/11-theming.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,54 @@ include_in_header:
Your entries are merged with Great Docs' own head injections (Font Awesome, theme scripts, etc.) so
everything cooperates automatically.

## Raw Quarto Settings {#quarto-passthrough}

Great Docs generates `_quarto.yml` for you, so you never edit it by hand. When you need a Quarto
setting that Great Docs has no option for, or want to reproduce the look of an existing Quarto
site, put it under a top-level `quarto` key. Its contents are merged into the generated
`_quarto.yml` just before Quarto renders, so they take precedence over everything Great Docs
writes:

```{.yaml filename="docs/great-docs.yml"}
quarto:
format:
html:
theme:
light: [flatly, assets/custom.scss]
dark: [darkly, assets/custom.scss]
mainfont: "Source Sans Pro"
website:
page-footer: null
```

The merge follows three rules:

- mappings merge key by key, so `format.html.mainfont` leaves every other `format.html` key alone
- lists and plain values replace what Great Docs generated
- `null` removes the key altogether (above, it drops the generated page footer)

Files you reference, such as `custom.scss`, are resolved from the build directory, so keep them in
the `assets/` directory, which Great Docs copies in on every build.

For larger customizations, you can keep the settings in a separate `_quarto.user.yml` file next to
`great-docs.yml`. It uses the same format as `_quarto.yml`, Great Docs never modifies it, and it is
merged last, after the `quarto` key:

```{.yaml filename="docs/_quarto.user.yml"}
format:
html:
toc-depth: 3
code-line-numbers: true
```

::: {.callout-warning}
Replacing a list replaces Great Docs' own entries too. For example, setting `format.html.theme`
drops `great-docs.scss`, the stylesheet behind most of Great Docs' styling, and setting
`format.html.include-in-header` drops the scripts Great Docs injects. For everyday settings, prefer
`site` (which merges into `format.html` before Great Docs adds its own entries), `include_in_header`,
and the other dedicated options on this page.
:::

## Logo

Great Docs can display a logo in the navbar instead of the plain-text package name. Logos are
Expand Down
31 changes: 31 additions & 0 deletions great_docs/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,37 @@ def write_quarto_yml(path: Path, config: dict) -> None:
write_yaml(config, f)


def merge_quarto_overrides(config: dict, overrides: dict) -> dict:
"""
Deep merge user overrides into a Quarto configuration

Mappings present on both sides merge key by key; any other value (a list,
a scalar) replaces the original; a `None` value removes the key. Neither
argument is mutated.

Parameters
----------
config
The generated Quarto configuration.
overrides
The user's settings, which take precedence.

Returns
-------
dict
The merged configuration.
"""
result = dict(config)
for key, value in overrides.items():
if value is None:
result.pop(key, None)
elif isinstance(value, dict) and isinstance(result.get(key), dict):
result[key] = merge_quarto_overrides(result[key], value)
else:
result[key] = value
return result


GITIGNORE_CONTENT = """# Great Docs build directory
# This directory is ephemeral and regenerated on each build
# Do not commit this directory to version control
Expand Down
16 changes: 16 additions & 0 deletions great_docs/assets/great-docs.default.yml
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,22 @@ site:
# Translates navbar labels, widget text, tooltips, and accessibility labels.
lang: en

# Quarto Passthrough
# ------------------
# Arbitrary `_quarto.yml` content, deep-merged into the generated config just
# before Quarto renders, so it wins over everything great-docs writes. Mappings
# merge key by key; lists and scalars replace; a `null` value removes the key.
# A `_quarto.user.yml` file next to great-docs.yml, if present, merges last.
# For example:
# quarto:
# format:
# html:
# theme:
# light: [flatly, custom.scss]
# dark: [darkly, custom.scss]
# mainfont: "Source Sans Pro"
quarto: {}

# Page Metadata
# -------------
# Show page timestamps in footer
Expand Down
11 changes: 11 additions & 0 deletions great_docs/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -1048,6 +1048,17 @@ def site_quarto(self) -> ConfigDict:
site.pop("css", None)
return site

@property
def quarto(self) -> ConfigDict:
"""Get the raw `_quarto.yml` overrides, merged in last before render."""
quarto = self["quarto"]
if not isinstance(quarto, dict):
raise ValueError(
f"`quarto` in great-docs.yml must be a mapping of `_quarto.yml` "
f"settings, not {type(quarto).__name__}"
)
return cast("ConfigDict", quarto)

@property
def show_dates(self) -> bool:
"""Whether to show page metadata timestamps in the footer."""
Expand Down
44 changes: 44 additions & 0 deletions great_docs/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from ._utils import (
GITIGNORE_CONTENT,
is_great_docs_build_dir,
merge_quarto_overrides,
recognised_build_dirs,
record_site_ownership,
validate_build_dir,
Expand Down Expand Up @@ -11352,6 +11353,44 @@ def _write_initial_quarto_yml(self) -> None:
config = {"project": {"type": "website"}, "format": {"html": {"theme": "flatly"}}}
self._write_quarto_yml(self.build_dir / "_quarto.yml", config)

def _apply_quarto_overrides(self) -> list[str]:
"""
Merge the user's raw Quarto settings into the generated `_quarto.yml`

The `quarto` block of great-docs.yml merges first, then a
`_quarto.user.yml` file beside great-docs.yml, if present. This runs
after every other step has written the file, so the user's settings
win. The merge rules are those of `merge_quarto_overrides`.

Returns
-------
list[str]
The sources that were applied, for the build log.
"""
layers: list[tuple[str, dict]] = []
if self._config.quarto:
layers.append(("great-docs.yml `quarto`", self._config.quarto))

user_yml = self.layout.config_path.parent / "_quarto.user.yml"
if user_yml.is_file():
with open(user_yml, "r", encoding="utf-8") as f:
overlay = read_yaml(f)
if overlay is not None and not isinstance(overlay, dict):
raise ValueError(f"{user_yml.name} must contain a mapping of `_quarto.yml` settings")
if overlay:
layers.append((user_yml.name, overlay))

if not layers:
return []

quarto_yml = self.build_dir / "_quarto.yml"
with open(quarto_yml, "r", encoding="utf-8") as f:
config = read_yaml(f) or {}
for _, overrides in layers:
config = merge_quarto_overrides(config, overrides)
write_quarto_yml(quarto_yml, config)
return [name for name, _ in layers]

def _translate_navbar_labels(self, config: dict) -> None:
"""
Translate known navbar text labels using the configured language.
Expand Down Expand Up @@ -16142,6 +16181,11 @@ class Result:
else:
log.step_skip(step, "no frozen pages")

# Apply the user's raw Quarto settings last, so they win
applied = self._apply_quarto_overrides()
if applied:
log.detail("Applied Quarto overrides from " + " and ".join(applied))

# Expand source-code: mock cells before Quarto sees them
from great_docs._mock_code import process_directory as _expand_mock_cells

Expand Down
1 change: 1 addition & 0 deletions tests/test_config_defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"html-math-method": "katex",
"lang": "en",
},
"quarto": {},
"show_dates": False,
"date_format": "%B %d, %Y",
"show_author": True,
Expand Down
106 changes: 106 additions & 0 deletions tests/test_quarto_overrides.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
"""Tests for the raw `_quarto.yml` passthrough (`quarto:` and `_quarto.user.yml`)"""

from pathlib import Path

import pytest
from yaml12 import read_yaml

from great_docs import Config, GreatDocs
from great_docs._utils import merge_quarto_overrides, write_quarto_yml


def test_merge_quarto_overrides_rules():
config = {
"format": {"html": {"theme": "flatly", "toc": True, "css": ["a.css"]}},
"website": {"title": "Pkg"},
}
overrides = {
"format": {"html": {"theme": {"light": ["flatly", "custom.scss"]}, "toc": None, "css": ["b.css"]}},
"execute": {"freeze": "auto"},
}
result = merge_quarto_overrides(config, overrides)

assert result == {
"format": {"html": {"theme": {"light": ["flatly", "custom.scss"]}, "css": ["b.css"]}},
"website": {"title": "Pkg"},
"execute": {"freeze": "auto"},
}
assert config["format"]["html"]["toc"] is True # not mutated


def _make_docs(tmp_path: Path, gd_yml: str) -> GreatDocs:
(tmp_path / "pyproject.toml").write_text('[project]\nname = "mypkg"\n', encoding="utf-8")
(tmp_path / "great-docs.yml").write_text(gd_yml, encoding="utf-8")
docs = GreatDocs(project_path=str(tmp_path))
docs._config = Config(tmp_path)
docs.build_dir.mkdir(parents=True, exist_ok=True)
generated = {
"project": {"type": "website"},
"website": {"title": "mypkg", "page-footer": {"left": "GD"}},
"format": {"html": {"theme": "flatly", "toc-depth": 2}},
}
write_quarto_yml(docs.build_dir / "_quarto.yml", generated)
return docs


def _read(docs: GreatDocs) -> dict:
with open(docs.build_dir / "_quarto.yml", encoding="utf-8") as f:
return read_yaml(f)


def test_quarto_block_merges_into_generated_config(tmp_path):
docs = _make_docs(
tmp_path,
"quarto:\n"
" format:\n"
" html:\n"
" theme:\n"
" light: [flatly, custom.scss]\n"
" dark: [darkly, custom.scss]\n"
" mainfont: Source Sans Pro\n"
" website:\n"
" page-footer: null\n",
)

assert docs._apply_quarto_overrides() == ["great-docs.yml `quarto`"]
result = _read(docs)
assert result["format"]["html"] == {
"theme": {"light": ["flatly", "custom.scss"], "dark": ["darkly", "custom.scss"]},
"toc-depth": 2,
"mainfont": "Source Sans Pro",
}
assert result["website"] == {"title": "mypkg"}
assert (docs.build_dir / "_quarto.yml").read_text().startswith("# Generated by Great Docs")


def test_user_overlay_file_merges_last(tmp_path):
docs = _make_docs(tmp_path, "quarto:\n format:\n html:\n toc-depth: 3\n")
(tmp_path / "_quarto.user.yml").write_text(
"format:\n html:\n toc-depth: 4\nwebsite:\n title: Custom\n", encoding="utf-8"
)

assert docs._apply_quarto_overrides() == ["great-docs.yml `quarto`", "_quarto.user.yml"]
result = _read(docs)
assert result["format"]["html"]["toc-depth"] == 4
assert result["website"]["title"] == "Custom"


def test_no_overrides_leaves_file_untouched(tmp_path):
docs = _make_docs(tmp_path, "display_name: Pkg\n")
before = (docs.build_dir / "_quarto.yml").read_text()

assert docs._apply_quarto_overrides() == []
assert (docs.build_dir / "_quarto.yml").read_text() == before


def test_quarto_block_must_be_mapping(tmp_path):
docs = _make_docs(tmp_path, "quarto: [not, a, mapping]\n")
with pytest.raises(ValueError, match="must be a mapping"):
docs._apply_quarto_overrides()


def test_user_overlay_file_must_be_mapping(tmp_path):
docs = _make_docs(tmp_path, "")
(tmp_path / "_quarto.user.yml").write_text("- a\n- b\n", encoding="utf-8")
with pytest.raises(ValueError, match="must contain a mapping"):
docs._apply_quarto_overrides()
Loading