Skip to content

writers

Class info

Re-exported classes

Class Module Description
GeneratedFolder mkdocs_mknodes.writers.base A folder that may contain both hand-written and generated files.
Writer mkdocs_mknodes.writers.base Turns a BuildOutput into the input files of a static site engine.
ZensicalWriter mkdocs_mknodes.writers.zensical Write a BuildOutput as Zensical input: docs folder + generated config.

šŸ›ˆ DocStrings

Writers turning a BuildOutput into the input of a static site engine.

GeneratedFolder

A folder that may contain both hand-written and generated files.

Generated files are tracked in a .gitignore manifest inside the folder (so git ignores them, and the next run knows which files it owns). Files that exist but are not listed in the manifest are considered hand-written and never overwritten. If the folder already contains a hand-written .gitignore, the manifest goes into .mknodes-generated instead (and the files are not git-ignored).

Source code in mkdocs_mknodes/writers/base.py
class GeneratedFolder:
    """A folder that may contain both hand-written and generated files.

    Generated files are tracked in a `.gitignore` manifest inside the folder (so git
    ignores them, and the next run knows which files it owns). Files that exist but are
    not listed in the manifest are considered hand-written and never overwritten.
    If the folder already contains a hand-written `.gitignore`, the manifest goes into
    `.mknodes-generated` instead (and the files are not git-ignored).
    """

    def __init__(self, path: pathlib.Path, *, owned: bool = False) -> None:
        """Constructor.

        Args:
            path: The folder
            owned: Whether the whole folder is generated (no hand-written files inside)
        """
        self.path = path
        self.owned = owned
        self.manifest_path = self._get_manifest_path()
        self.previous = self._read_manifest()
        self.written: set[str] = set()
        self.skipped: list[str] = []
        self.changed: list[str] = []

    def _get_manifest_path(self) -> pathlib.Path:
        gitignore = self.path / MANIFEST_NAME
        if not gitignore.exists() or _is_manifest(gitignore):
            return gitignore
        return self.path / ".mknodes-generated"

    def _read_manifest(self) -> set[str]:
        if not self.manifest_path.is_file() or not _is_manifest(self.manifest_path):
            return set()
        lines = self.manifest_path.read_text(encoding="utf-8").splitlines()
        return {
            line.removeprefix("/")
            for line in lines
            if line and not line.startswith("#") and line != f"/{self.manifest_path.name}"
        }

    def is_hand_written(self, rel_path: str) -> bool:
        if self.owned:
            return False
        return (self.path / rel_path).exists() and rel_path not in self.previous

    def write(self, rel_path: str, content: str | bytes) -> bool:
        """Write a generated file unless a hand-written file exists at that path.

        Returns True if the file was written (or is already up to date).
        """
        rel_path = pathlib.PurePosixPath(rel_path).as_posix()
        if self.is_hand_written(rel_path):
            logger.warning("Not overwriting hand-written file %s", self.path / rel_path)
            self.skipped.append(rel_path)
            return False
        target = self.path / rel_path
        data = content.encode() if isinstance(content, str) else content
        if not target.is_file() or target.read_bytes() != data:
            target.parent.mkdir(parents=True, exist_ok=True)
            target.write_bytes(data)
            self.changed.append(rel_path)
        self.written.add(rel_path)
        return True

    def finish(self) -> list[str]:
        """Delete stale generated files and write the manifest. Returns removed paths."""
        removed = []
        for rel_path in sorted(self.previous - self.written):
            target = self.path / rel_path
            if target.is_file():
                target.unlink()
                removed.append(rel_path)
                _remove_empty_parents(target.parent, self.path)
        if self.written or self.manifest_path.exists():
            self.path.mkdir(parents=True, exist_ok=True)
            lines = [MANIFEST_MARKER, f"/{self.manifest_path.name}"]
            lines += [f"/{p}" for p in sorted(self.written)]
            text = "\n".join(lines) + "\n"
            if not self.manifest_path.is_file() or self.manifest_path.read_text() != text:
                self.manifest_path.write_text(text, encoding="utf-8")
        return removed

__init__

__init__(path: Path, *, owned: bool = False) -> None

Constructor.

Parameters:

Name Type Description Default
path Path

The folder

required
owned bool

Whether the whole folder is generated (no hand-written files inside)

False
Source code in mkdocs_mknodes/writers/base.py
def __init__(self, path: pathlib.Path, *, owned: bool = False) -> None:
    """Constructor.

    Args:
        path: The folder
        owned: Whether the whole folder is generated (no hand-written files inside)
    """
    self.path = path
    self.owned = owned
    self.manifest_path = self._get_manifest_path()
    self.previous = self._read_manifest()
    self.written: set[str] = set()
    self.skipped: list[str] = []
    self.changed: list[str] = []

finish

finish() -> list[str]

Delete stale generated files and write the manifest. Returns removed paths.

Source code in mkdocs_mknodes/writers/base.py
def finish(self) -> list[str]:
    """Delete stale generated files and write the manifest. Returns removed paths."""
    removed = []
    for rel_path in sorted(self.previous - self.written):
        target = self.path / rel_path
        if target.is_file():
            target.unlink()
            removed.append(rel_path)
            _remove_empty_parents(target.parent, self.path)
    if self.written or self.manifest_path.exists():
        self.path.mkdir(parents=True, exist_ok=True)
        lines = [MANIFEST_MARKER, f"/{self.manifest_path.name}"]
        lines += [f"/{p}" for p in sorted(self.written)]
        text = "\n".join(lines) + "\n"
        if not self.manifest_path.is_file() or self.manifest_path.read_text() != text:
            self.manifest_path.write_text(text, encoding="utf-8")
    return removed

write

write(rel_path: str, content: str | bytes) -> bool

Write a generated file unless a hand-written file exists at that path.

Returns True if the file was written (or is already up to date).

Source code in mkdocs_mknodes/writers/base.py
def write(self, rel_path: str, content: str | bytes) -> bool:
    """Write a generated file unless a hand-written file exists at that path.

    Returns True if the file was written (or is already up to date).
    """
    rel_path = pathlib.PurePosixPath(rel_path).as_posix()
    if self.is_hand_written(rel_path):
        logger.warning("Not overwriting hand-written file %s", self.path / rel_path)
        self.skipped.append(rel_path)
        return False
    target = self.path / rel_path
    data = content.encode() if isinstance(content, str) else content
    if not target.is_file() or target.read_bytes() != data:
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_bytes(data)
        self.changed.append(rel_path)
    self.written.add(rel_path)
    return True

Writer

Turns a BuildOutput into the input files of a static site engine.

Source code in mkdocs_mknodes/writers/base.py
class Writer:
    """Turns a `BuildOutput` into the input files of a static site engine."""

    name: str = ""

    def __init__(self, settings: GeneratorSettings) -> None:
        self.settings = settings

    def write(self, output: BuildOutput) -> pathlib.Path:
        """Write the output. Returns the path of the config file to build with."""
        raise NotImplementedError

    def build_command(
        self, *, serve: bool = False, extra_args: list[str] | None = None
    ) -> list[str]:
        """Return the command which builds (or serves) the written site."""
        raise NotImplementedError

build_command

build_command(*, serve: bool = False, extra_args: list[str] | None = None) -> list[str]

Return the command which builds (or serves) the written site.

Source code in mkdocs_mknodes/writers/base.py
def build_command(
    self, *, serve: bool = False, extra_args: list[str] | None = None
) -> list[str]:
    """Return the command which builds (or serves) the written site."""
    raise NotImplementedError

write

write(output: BuildOutput) -> Path

Write the output. Returns the path of the config file to build with.

Source code in mkdocs_mknodes/writers/base.py
def write(self, output: BuildOutput) -> pathlib.Path:
    """Write the output. Returns the path of the config file to build with."""
    raise NotImplementedError

ZensicalWriter

Bases: Writer

Write a BuildOutput as Zensical input: docs folder + generated config.

Source code in mkdocs_mknodes/writers/zensical.py
class ZensicalWriter(Writer):
    """Write a `BuildOutput` as Zensical input: docs folder + generated config."""

    name = "zensical"

    @property
    def source_config(self) -> dict[str, Any]:
        return self.settings.site_config

    def write(self, output: BuildOutput) -> pathlib.Path:
        docs_dir = self.settings.resolved_docs_dir
        gen_dir = self.settings.resolved_generated_dir
        mirror = gen_dir.resolve() != docs_dir.resolve()
        folder = GeneratedFolder(gen_dir, owned=mirror)
        if mirror:
            self._mirror_docs(docs_dir, folder, output)
        icons = IconResolver()
        pages = {path: icons.update_page(md) for path, md in output.pages.items()}
        social = icons.update_social(output.metadata.social)
        for path, content in {**output.assets, **pages}.items():
            if not (mirror and path in folder.written):
                folder.write(path, content)
        removed = folder.finish()
        templates_dir = self._write_templates({**output.templates, **icons.svgs})
        config = self.build_config(output, templates_dir=templates_dir, social=social)
        cfg_path = self.settings.generated_config_path
        source = self.settings.config_file.name if self.settings.config_file else "defaults"
        header = CONFIG_HEADER.format(source=source, name=cfg_path.name)
        text = header + yamlconfig.dumps(config)
        if not cfg_path.is_file() or cfg_path.read_text(encoding="utf-8") != text:
            cfg_path.write_text(text, encoding="utf-8")
        logger.info(
            "Wrote %s files (%s changed, %s removed, %s hand-written kept) to %s",
            len(folder.written),
            len(folder.changed),
            len(removed),
            len(folder.skipped),
            gen_dir,
        )
        self.folder = folder
        return cfg_path

    def _mirror_docs(
        self, docs_dir: pathlib.Path, folder: GeneratedFolder, output: BuildOutput
    ) -> None:
        """Copy hand-written docs into the generated folder (hand-written files win)."""
        if not docs_dir.is_dir():
            return
        for root, dirs, files in os.walk(docs_dir):
            dirs[:] = [d for d in dirs if d not in SKIP_MIRROR_DIRS]
            for filename in files:
                src = pathlib.Path(root) / filename
                rel = src.relative_to(docs_dir).as_posix()
                if rel in output.files:
                    logger.warning("Hand-written %s shadows a generated file", rel)
                folder.write(rel, src.read_bytes())

    def _write_templates(self, templates: dict[str, str]) -> str | None:
        """Write theme template overrides (and icons) into the theme's custom_dir."""
        theme = self.source_config.get("theme")
        custom_dir = theme.get("custom_dir") if isinstance(theme, dict) else None
        if not templates and not custom_dir:
            return None
        rel_dir = str(custom_dir or DEFAULT_OVERRIDES_DIR)
        folder = GeneratedFolder(self.settings.project_dir / rel_dir)
        for filename, html in templates.items():
            folder.write(filename, html)
        folder.finish()
        return None if custom_dir else rel_dir

    def build_config(
        self,
        output: BuildOutput,
        *,
        templates_dir: str | None = None,
        social: list[dict[str, str]] | None = None,
    ) -> dict[str, Any]:
        """Return the generated config (to be layered over the source config)."""
        src = self.source_config
        cfg: dict[str, Any] = {}
        if self.settings.config_file:
            rel = os.path.relpath(self.settings.config_file, self.settings.project_dir)
            cfg["INHERIT"] = pathlib.Path(rel).as_posix()
        meta = output.metadata
        for key in ("site_name", "site_description", "site_author", "repo_url", "copyright"):
            if not src.get(key) and (value := getattr(meta, key)):
                cfg[key] = value
        if "site_name" not in cfg and not src.get("site_name"):
            cfg["site_name"] = self.settings.project_dir.name
        gen_dir = self.settings.resolved_generated_dir
        if gen_dir.resolve() != self.settings.resolved_docs_dir.resolve():
            rel_docs = os.path.relpath(gen_dir, self.settings.project_dir)
            cfg["docs_dir"] = pathlib.Path(rel_docs).as_posix()
        if self.settings.site_dir:
            cfg["site_dir"] = self.settings.site_dir
        if templates_dir:
            cfg["theme"] = {"custom_dir": templates_dir}
        user_nav = src.get("nav")
        if not isinstance(user_nav, list):
            user_nav = []
        if nav := nav_to_config(output.nav):
            cfg["nav"] = [*user_nav, *nav]
        cfg["markdown_extensions"] = merge_markdown_extensions(
            src.get("markdown_extensions"), output.markdown_extensions
        )
        css = list(src.get("extra_css") or [])
        css += [c for c in output.extra_css if c not in css]
        if css:
            cfg["extra_css"] = css
        js = list(src.get("extra_javascript") or [])
        known = {_script_path(i) for i in js}
        js += [_script_to_config(s) for s in output.extra_javascript if s.path not in known]
        if js:
            cfg["extra_javascript"] = js
        extra = dict(output.extra)
        src_extra = src.get("extra")
        if not isinstance(src_extra, dict):
            src_extra = {}
        if meta.social and not src_extra.get("social"):
            extra["social"] = social_to_config(meta.social) if social is None else social
        if extra:
            cfg["extra"] = extra
        excluded = [line for line in (src.get("exclude_docs") or "").splitlines() if line]
        excluded += [p for p in EXCLUDED_DOCS if p not in excluded]
        cfg["exclude_docs"] = "\n".join(excluded) + "\n"
        return cfg

    def build_command(
        self, *, serve: bool = False, extra_args: list[str] | None = None
    ) -> list[str]:
        cmd = [sys.executable, "-m", "zensical", "serve" if serve else "build"]
        cmd += ["-f", str(self.settings.generated_config_path)]
        return cmd + list(extra_args or [])

    @staticmethod
    def is_available() -> bool:
        return shutil.which("zensical") is not None or _has_module("zensical")

build_config

build_config(
    output: BuildOutput,
    *,
    templates_dir: str | None = None,
    social: list[dict[str, str]] | None = None
) -> dict[str, Any]

Return the generated config (to be layered over the source config).

Source code in mkdocs_mknodes/writers/zensical.py
def build_config(
    self,
    output: BuildOutput,
    *,
    templates_dir: str | None = None,
    social: list[dict[str, str]] | None = None,
) -> dict[str, Any]:
    """Return the generated config (to be layered over the source config)."""
    src = self.source_config
    cfg: dict[str, Any] = {}
    if self.settings.config_file:
        rel = os.path.relpath(self.settings.config_file, self.settings.project_dir)
        cfg["INHERIT"] = pathlib.Path(rel).as_posix()
    meta = output.metadata
    for key in ("site_name", "site_description", "site_author", "repo_url", "copyright"):
        if not src.get(key) and (value := getattr(meta, key)):
            cfg[key] = value
    if "site_name" not in cfg and not src.get("site_name"):
        cfg["site_name"] = self.settings.project_dir.name
    gen_dir = self.settings.resolved_generated_dir
    if gen_dir.resolve() != self.settings.resolved_docs_dir.resolve():
        rel_docs = os.path.relpath(gen_dir, self.settings.project_dir)
        cfg["docs_dir"] = pathlib.Path(rel_docs).as_posix()
    if self.settings.site_dir:
        cfg["site_dir"] = self.settings.site_dir
    if templates_dir:
        cfg["theme"] = {"custom_dir": templates_dir}
    user_nav = src.get("nav")
    if not isinstance(user_nav, list):
        user_nav = []
    if nav := nav_to_config(output.nav):
        cfg["nav"] = [*user_nav, *nav]
    cfg["markdown_extensions"] = merge_markdown_extensions(
        src.get("markdown_extensions"), output.markdown_extensions
    )
    css = list(src.get("extra_css") or [])
    css += [c for c in output.extra_css if c not in css]
    if css:
        cfg["extra_css"] = css
    js = list(src.get("extra_javascript") or [])
    known = {_script_path(i) for i in js}
    js += [_script_to_config(s) for s in output.extra_javascript if s.path not in known]
    if js:
        cfg["extra_javascript"] = js
    extra = dict(output.extra)
    src_extra = src.get("extra")
    if not isinstance(src_extra, dict):
        src_extra = {}
    if meta.social and not src_extra.get("social"):
        extra["social"] = social_to_config(meta.social) if social is None else social
    if extra:
        cfg["extra"] = extra
    excluded = [line for line in (src.get("exclude_docs") or "").splitlines() if line]
    excluded += [p for p in EXCLUDED_DOCS if p not in excluded]
    cfg["exclude_docs"] = "\n".join(excluded) + "\n"
    return cfg

get_writer

get_writer(engine: str) -> type[Writer]

Return the writer class for given engine name.

Source code in mkdocs_mknodes/writers/__init__.py
def get_writer(engine: str) -> type[Writer]:
    """Return the writer class for given engine name."""
    try:
        return WRITERS[engine]
    except KeyError:
        msg = f"Unknown engine {engine!r}. Available: {', '.join(WRITERS)}"
        raise ValueError(msg) from None
Page info
Resources
Resources(css=[],
          markdown_extensions={'tables': {}},
          plugins=[Plugin('mkdocstrings')],
          js=[],
          assets=[],
          packages=[])
Metadata
created:
  source_filename: /home/runner/work/mkdocs-mknodes/mkdocs-mknodes/.venv/lib/python3.13/site-packages/mknodes/pages/mkmodulepage/__init__.py
  source_function: MkModulePage.__init__
  source_line_no: 52
title: writers