mirror of
https://github.com/zensical/zensical.git
synced 2026-10-08 05:41:24 +00:00
feature: support autorefs settings
Signed-off-by: Timothée Mazzucotelli <dev@pawamoy.fr>
This commit is contained in:
7 files changed
+753
-43
No files matched your search
+234
@@ -0,0 +1,234 @@
|
||||
# Copyright (c) 2025-2026 Zensical and contributors
|
||||
|
||||
# SPDX-License-Identifier: MIT
|
||||
# All contributions are certified under the DCO
|
||||
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to
|
||||
# deal in the Software without restriction, including without limitation the
|
||||
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||
# sell copies of the Software, and to permit persons to whom the Software is
|
||||
# furnished to do so, subject to the following conditions:
|
||||
|
||||
# The above copyright notice and this permission notice shall be included in
|
||||
# all copies or substantial portions of the Software.
|
||||
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
|
||||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||
# IN THE SOFTWARE.
|
||||
|
||||
"""Integration coverage for autorefs configuration and native rendering."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from html.parser import HTMLParser
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
import zensical
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class _Links(HTMLParser):
|
||||
def __init__(self, content: str) -> None:
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.links: list[dict[str, str | None]] = []
|
||||
self.feed(content)
|
||||
|
||||
def handle_starttag(
|
||||
self, tag: str, attrs: list[tuple[str, str | None]]
|
||||
) -> None:
|
||||
attributes = dict(attrs)
|
||||
if tag == "a" and "autorefs" in (attributes.get("class") or "").split():
|
||||
self.links.append(attributes)
|
||||
|
||||
|
||||
def _write_project(
|
||||
root: Path,
|
||||
options: dict[str, Any] | None,
|
||||
*,
|
||||
features: tuple[str, ...] = (),
|
||||
) -> Path:
|
||||
docs = root / "docs"
|
||||
guide = docs / "guide"
|
||||
overrides = root / "overrides"
|
||||
guide.mkdir(parents=True, exist_ok=True)
|
||||
overrides.mkdir(exist_ok=True)
|
||||
(docs / "index.md").write_text("# Home\n", encoding="utf-8")
|
||||
(docs / "a.md").write_text("# First {#shared}\n", encoding="utf-8")
|
||||
(guide / "near.md").write_text("# Nearby {#shared}\n", encoding="utf-8")
|
||||
(guide / "index.md").write_text(
|
||||
"# Guide\n\n[Target][shared]\n\n"
|
||||
'<autoref identifier="shared" optional>API target</autoref>\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
(overrides / "main.html").write_text("{{ page.content }}", encoding="utf-8")
|
||||
extensions = ["attr_list"]
|
||||
if options is None:
|
||||
extensions.append("zensical.extensions.autorefs")
|
||||
config = root / "mkdocs.yml"
|
||||
config.write_text(
|
||||
yaml.safe_dump(
|
||||
{
|
||||
"site_name": "Autorefs settings",
|
||||
"theme": {
|
||||
"custom_dir": str(overrides),
|
||||
"features": list(features),
|
||||
},
|
||||
"plugins": {"autorefs": options} if options is not None else {},
|
||||
"markdown_extensions": extensions,
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
def _build_links(
|
||||
root: Path, config: Path, *, clean: bool = True
|
||||
) -> list[dict[str, str | None]]:
|
||||
zensical.build(str(config), {"clean": clean, "strict": False})
|
||||
content = (root / "site" / "guide" / "index.html").read_text(
|
||||
encoding="utf-8"
|
||||
)
|
||||
return _Links(content).links
|
||||
|
||||
|
||||
def test_resolve_closest_changes_between_builds(tmp_path: Path) -> None:
|
||||
for index, (options, expected) in enumerate(
|
||||
[
|
||||
({}, "../a/#shared"),
|
||||
({"resolve_closest": True}, "near/#shared"),
|
||||
({"resolve_closest": False}, "../a/#shared"),
|
||||
]
|
||||
):
|
||||
config = _write_project(tmp_path, options)
|
||||
links = _build_links(tmp_path, config, clean=index == 0)
|
||||
assert [link["href"] for link in links] == [expected, expected]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("mode", "features", "has_title"),
|
||||
[
|
||||
(True, (), True),
|
||||
(True, ("navigation.instant.preview",), True),
|
||||
(False, (), False),
|
||||
("external", (), False),
|
||||
("auto", (), True),
|
||||
("auto", ("navigation.instant.preview",), False),
|
||||
],
|
||||
)
|
||||
def test_link_titles(
|
||||
tmp_path: Path,
|
||||
mode: bool | str,
|
||||
features: tuple[str, ...],
|
||||
has_title: bool,
|
||||
) -> None:
|
||||
config = _write_project(tmp_path, {"link_titles": mode}, features=features)
|
||||
links = _build_links(tmp_path, config)
|
||||
assert len(links) == 2
|
||||
assert all(("title" in link) == has_title for link in links)
|
||||
if has_title:
|
||||
assert links[0]["title"] == "First"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("mode", "features", "title"),
|
||||
[
|
||||
(True, ("content.tooltips",), "First (shared)"),
|
||||
(False, (), "First (<code>shared</code>)"),
|
||||
("auto", (), "First (shared)"),
|
||||
("auto", ("content.tooltips",), "First (<code>shared</code>)"),
|
||||
],
|
||||
)
|
||||
def test_strip_title_tags(
|
||||
tmp_path: Path,
|
||||
mode: bool | str,
|
||||
features: tuple[str, ...],
|
||||
title: str,
|
||||
) -> None:
|
||||
config = _write_project(
|
||||
tmp_path, {"strip_title_tags": mode}, features=features
|
||||
)
|
||||
links = _build_links(tmp_path, config)
|
||||
assert links[1]["title"] == title
|
||||
|
||||
|
||||
@pytest.mark.parametrize("preview", [False, True])
|
||||
def test_implicit_autorefs_uses_automatic_title_defaults(
|
||||
tmp_path: Path, preview: bool
|
||||
) -> None:
|
||||
features = ("navigation.instant.preview",) if preview else ()
|
||||
config = _write_project(tmp_path, None, features=features)
|
||||
links = _build_links(tmp_path, config)
|
||||
assert len(links) == 2
|
||||
assert all(("title" in link) != preview for link in links)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("record_backlinks", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
("options", "href", "titles"),
|
||||
[
|
||||
(
|
||||
{
|
||||
"resolve_closest": True,
|
||||
"link_titles": True,
|
||||
"strip_title_tags": False,
|
||||
},
|
||||
"near/#shared",
|
||||
[
|
||||
"Nearby",
|
||||
"Nearby (<code>shared</code>)",
|
||||
"Nearby (<code>shared</code>)",
|
||||
],
|
||||
),
|
||||
(
|
||||
{"resolve_closest": False, "link_titles": False},
|
||||
"../a/#shared",
|
||||
[None, None, None],
|
||||
),
|
||||
(
|
||||
{
|
||||
"resolve_closest": False,
|
||||
"link_titles": True,
|
||||
"strip_title_tags": True,
|
||||
},
|
||||
"../a/#shared",
|
||||
["First", "First (shared)", "First (shared)"],
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_settings_apply_to_cached_and_template_references(
|
||||
tmp_path: Path,
|
||||
record_backlinks: bool,
|
||||
options: dict[str, Any],
|
||||
href: str,
|
||||
titles: list[str | None],
|
||||
) -> None:
|
||||
# Exercise both registry paths with references in Markdown and a template.
|
||||
config = _write_project(tmp_path, options)
|
||||
project = yaml.safe_load(config.read_text(encoding="utf-8"))
|
||||
project["markdown_extensions"].append(
|
||||
{"zensical.extensions.autorefs": {"record_backlinks": record_backlinks}}
|
||||
)
|
||||
config.write_text(yaml.safe_dump(project), encoding="utf-8")
|
||||
reference = '<autoref identifier="shared" optional>Template</autoref>'
|
||||
(tmp_path / "overrides" / "main.html").write_text(
|
||||
"{{ page.content }}" + reference,
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
# The same settings must apply on the initial build and when reusing caches.
|
||||
for clean in [True, False]:
|
||||
links = _build_links(tmp_path, config, clean=clean)
|
||||
|
||||
assert [link["href"] for link in links] == [href, href, href]
|
||||
assert [link.get("title") for link in links] == titles
|
||||
Vendored
+20
-3
@@ -279,7 +279,6 @@ class TestPluginShimming:
|
||||
self, tmp_path: Path
|
||||
) -> None:
|
||||
plugins: dict[str, dict[str, Any]] = {
|
||||
"autorefs": {},
|
||||
"callouts": {},
|
||||
"glightbox": {"auto": False},
|
||||
"macros": {"render_by_default": False},
|
||||
@@ -290,7 +289,6 @@ class TestPluginShimming:
|
||||
}
|
||||
baseline = self._parse_yaml(tmp_path, plugins=plugins)
|
||||
for name, options in {
|
||||
"autorefs": {"link_titles": "external"},
|
||||
"callouts": {"aliases": False, "breakless_lists": False},
|
||||
"glightbox": {"slide_effect": "fade"},
|
||||
"macros": {"force_render_paths": "guides/**"},
|
||||
@@ -708,7 +706,26 @@ class TestPluginShimming:
|
||||
}
|
||||
config = self._parse_yaml(tmp_path, plugins={"autorefs": options})
|
||||
assert AutorefsExtension.name in config["markdown_extensions"]
|
||||
assert config["plugins"]["autorefs"]["config"] == {}
|
||||
assert config["plugins"]["autorefs"]["config"] == options
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("option", "value"),
|
||||
[
|
||||
("resolve_closest", True),
|
||||
("link_titles", False),
|
||||
("strip_title_tags", True),
|
||||
],
|
||||
)
|
||||
def test_autorefs_settings_affect_rebuild_hash(
|
||||
self, tmp_path: Path, option: str, value: bool
|
||||
) -> None:
|
||||
baseline = self._parse_yaml(tmp_path, plugins={"autorefs": {}})
|
||||
config_file = tmp_path / "mkdocs.yml"
|
||||
config_file.write_text(
|
||||
_minimal_yaml(plugins={"autorefs": {option: value}})
|
||||
)
|
||||
configured = parse_config(str(config_file))
|
||||
assert configured["plugins_hash"] != baseline["plugins_hash"]
|
||||
|
||||
def test_autorefs_disabled_not_added(
|
||||
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
|
||||
+67
-14
@@ -276,9 +276,6 @@ def test_rejects_invalid_blog_configuration(name: str, data: Any) -> None:
|
||||
@pytest.mark.parametrize(
|
||||
("plugin", "option"),
|
||||
[
|
||||
("autorefs", "resolve_closest"),
|
||||
("autorefs", "link_titles"),
|
||||
("autorefs", "strip_title_tags"),
|
||||
("callouts", "aliases"),
|
||||
("callouts", "breakless_lists"),
|
||||
("callouts", "title_from_first_bold"),
|
||||
@@ -386,14 +383,32 @@ def test_silently_discards_unsupported_search_options(
|
||||
@pytest.mark.parametrize("name", SHIM_PLUGINS)
|
||||
def test_normalizes_null_shim_configuration(name: str) -> None:
|
||||
plugins = _convert_plugins({name: None})
|
||||
assert plugins[name]["config"] == {}
|
||||
expected = (
|
||||
{
|
||||
"resolve_closest": False,
|
||||
"link_titles": "auto",
|
||||
"strip_title_tags": "auto",
|
||||
}
|
||||
if name == "autorefs"
|
||||
else {}
|
||||
)
|
||||
assert plugins[name]["config"] == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("name", "config"),
|
||||
[
|
||||
pytest.param("autorefs", {"enabled": False}, id="autorefs"),
|
||||
pytest.param("callouts", {"enabled": False}, id="callouts"),
|
||||
pytest.param(
|
||||
"autorefs",
|
||||
{
|
||||
"enabled": False,
|
||||
"resolve_closest": True,
|
||||
"link_titles": "external",
|
||||
"strip_title_tags": False,
|
||||
},
|
||||
id="autorefs",
|
||||
),
|
||||
pytest.param(
|
||||
"markdown-exec",
|
||||
{"enabled": False, "ansi": "off", "languages": ["python"]},
|
||||
@@ -465,18 +480,50 @@ def test_accepts_supported_shim_options(
|
||||
assert plugins[name]["config"] == config
|
||||
|
||||
|
||||
@pytest.mark.parametrize("plugin", ["autorefs", "material/autorefs"])
|
||||
@pytest.mark.parametrize(
|
||||
("option", "value"),
|
||||
[
|
||||
("resolve_closest", True),
|
||||
("resolve_closest", False),
|
||||
("link_titles", True),
|
||||
("link_titles", False),
|
||||
("link_titles", "auto"),
|
||||
("link_titles", "external"),
|
||||
("strip_title_tags", True),
|
||||
("strip_title_tags", False),
|
||||
("strip_title_tags", "auto"),
|
||||
],
|
||||
)
|
||||
def test_preserves_autorefs_settings(
|
||||
plugin: str, option: str, value: Any
|
||||
) -> None:
|
||||
data = {option: value}
|
||||
plugins = _convert_plugins({plugin: data})
|
||||
assert plugins["autorefs"]["config"][option] == value
|
||||
assert data == {option: value}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"option", ["resolve_closest", "link_titles", "strip_title_tags"]
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"value", [True, False, "auto", "external", 42, [], {}, None]
|
||||
)
|
||||
def test_silently_discards_unsupported_autorefs_options(
|
||||
option: str, value: Any, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
plugins = _convert_plugins({"autorefs": {"enabled": True, option: value}})
|
||||
assert plugins["autorefs"]["config"] == {"enabled": True}
|
||||
assert capsys.readouterr().err == ""
|
||||
@pytest.mark.parametrize("value", [0, 1, "invalid", [], {}])
|
||||
def test_rejects_invalid_autorefs_settings(option: str, value: Any) -> None:
|
||||
with pytest.raises(ConfigurationError, match=f"autorefs {option} must be"):
|
||||
_convert_plugins({"autorefs": {option: value}})
|
||||
|
||||
|
||||
def test_normalizes_null_autorefs_settings() -> None:
|
||||
plugins = _convert_plugins(
|
||||
{
|
||||
"autorefs": {
|
||||
"resolve_closest": None,
|
||||
"link_titles": None,
|
||||
"strip_title_tags": None,
|
||||
}
|
||||
}
|
||||
)
|
||||
assert plugins == _convert_plugins({"autorefs": {}})
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -535,6 +582,12 @@ def test_silently_discards_unsupported_autorefs_options(
|
||||
),
|
||||
("autorefs", {"enabled": "yes"}, "enabled must be a boolean"),
|
||||
("callouts", {"enabled": "yes"}, "enabled must be a boolean"),
|
||||
("autorefs", {"resolve_closest": "auto"}, "resolve_closest must be"),
|
||||
(
|
||||
"autorefs",
|
||||
{"strip_title_tags": "external"},
|
||||
"strip_title_tags must be",
|
||||
),
|
||||
("markdown-exec", {"ansi": "sometimes"}, "ansi must be"),
|
||||
(
|
||||
"markdown-exec",
|
||||
|
||||
@@ -117,12 +117,7 @@ DEFAULT_MARKDOWN_EXTENSIONS = {
|
||||
# Discard these before validation, hashing and forwarding to native modules or
|
||||
# Markdown extensions. Empty tuples mark plugins with no ignored options.
|
||||
_PLUGIN_UNSUPPORTED_OPTIONS = {
|
||||
"autorefs": (
|
||||
# TODO: Configure native URL selection and link title rendering.
|
||||
"resolve_closest",
|
||||
"link_titles",
|
||||
"strip_title_tags",
|
||||
),
|
||||
"autorefs": (),
|
||||
"awesome-nav": (),
|
||||
"blog": (),
|
||||
"callouts": (
|
||||
@@ -1980,11 +1975,33 @@ def _convert_plugins(value: Any, config: dict) -> dict:
|
||||
)
|
||||
plugins["mike"] = mike
|
||||
|
||||
# Validate settings forwarded by the plugin-to-extension shims.
|
||||
# Validate settings for plugins enabled through Markdown extensions.
|
||||
if "autorefs" in plugins:
|
||||
autorefs = plugins["autorefs"]
|
||||
_reject_unknown_options("autorefs", autorefs, {"enabled"})
|
||||
_validate_boolean_options("autorefs", autorefs, ("enabled",))
|
||||
_reject_unknown_options(
|
||||
"autorefs",
|
||||
autorefs,
|
||||
{"enabled", "resolve_closest", "link_titles", "strip_title_tags"},
|
||||
)
|
||||
set_default(autorefs, "resolve_closest", False)
|
||||
set_default(autorefs, "link_titles", "auto")
|
||||
set_default(autorefs, "strip_title_tags", "auto")
|
||||
_validate_boolean_options(
|
||||
"autorefs", autorefs, ("enabled", "resolve_closest")
|
||||
)
|
||||
for name, modes in (
|
||||
("link_titles", ("auto", "external")),
|
||||
("strip_title_tags", ("auto",)),
|
||||
):
|
||||
setting = autorefs[name]
|
||||
if not (
|
||||
isinstance(setting, bool)
|
||||
or (isinstance(setting, str) and setting in modes)
|
||||
):
|
||||
choices = ", ".join(repr(mode) for mode in modes)
|
||||
raise ConfigurationError(
|
||||
f"autorefs {name} must be a boolean or {choices}"
|
||||
)
|
||||
|
||||
if "callouts" in plugins:
|
||||
callouts = plugins["callouts"]
|
||||
|
||||
Reference in new issue
Block a user