Skip to content

mamut_routing_publish.docs_pages

Generated pages of the documentation site.

The MkDocs site (docs/ + mkdocs.yml) is hand-written where prose has no other home, and generated wherever the text already lives somewhere else, so nothing is duplicated:

  • the website's project pages (FAQ, glossary, citing, authors, ...) come from site_assets/texts/project_pages and AUTHORS.md, the same files the website renders;
  • one page per benchmark family comes from the family sections of site_assets/texts/mamut-routing_benchmark_families.md (the website's family "context" pages), followed by the family's own README when its satellite submodule is checked out, or a stub pointing at GitHub when it is not (a plain clone leaves satellite directories empty; the docs build must never fail because of that);
  • the README of the two tooling packages (lib, tools) as-is;
  • one API-reference page per module for the curated package list.

Everything here is pure (paths in, markdown out) so it is unit-tested without MkDocs; docs/_scripts/gen_pages.py is the thin gen-files driver that writes the pages.

GeneratedDocPage dataclass

GeneratedDocPage(path: str, markdown: str)

One virtual markdown file, path relative to the MkDocs docs_dir.

shift_headings

shift_headings(markdown: str, delta: int) -> str

Shift every ATX heading level by delta (clamped to 1..6), skipping fenced code.

Source code in src/mamut_routing_publish/docs_pages.py
def shift_headings(markdown: str, delta: int) -> str:
    """Shift every ATX heading level by ``delta`` (clamped to 1..6), skipping fenced code."""
    if delta == 0:
        return markdown
    lines: list[str] = []
    in_fence = False
    for line in markdown.splitlines():
        if _FENCE_RE.match(line):
            in_fence = not in_fence
            lines.append(line)
            continue
        match = re.match(r"^(#{1,6})(\s+.*)$", line) if not in_fence else None
        if match is None:
            lines.append(line)
            continue
        level = min(6, max(1, len(match.group(1)) + delta))
        lines.append("#" * level + match.group(2))
    return "\n".join(lines) + ("\n" if markdown.endswith("\n") else "")
rewrite_relative_links(
    markdown: str, *, blob_base: str, raw_base: str
) -> str

Point relative links at GitHub so an embedded README keeps working.

blob_base receives plain links (files and directories), raw_base receives images. Both are URL prefixes without a trailing slash. Absolute URLs, anchors, mailto and root-relative links are untouched.

Source code in src/mamut_routing_publish/docs_pages.py
def rewrite_relative_links(markdown: str, *, blob_base: str, raw_base: str) -> str:
    """Point relative links at GitHub so an embedded README keeps working.

    ``blob_base`` receives plain links (files and directories), ``raw_base``
    receives images. Both are URL prefixes without a trailing slash.
    Absolute URLs, anchors, mailto and root-relative links are untouched.
    """

    def replace(match: re.Match[str]) -> str:
        target = match.group("target")
        if not _is_relative_target(target):
            return match.group(0)
        base = raw_base if match.group("bang") else blob_base
        cleaned = target[2:] if target.startswith("./") else target
        return f"{match.group('bang')}[{match.group('text')}]({base}/{cleaned}{match.group('title') or ''})"

    lines: list[str] = []
    in_fence = False
    for line in markdown.splitlines():
        if _FENCE_RE.match(line):
            in_fence = not in_fence
            lines.append(line)
            continue
        lines.append(line if in_fence else _MARKDOWN_LINK_RE.sub(replace, line))
    return "\n".join(lines) + ("\n" if markdown.endswith("\n") else "")

parse_gitmodules

parse_gitmodules(repo_root: Path) -> dict[str, str]

Map submodule path -> GitHub HTTPS URL from <repo>/.gitmodules.

Source code in src/mamut_routing_publish/docs_pages.py
def parse_gitmodules(repo_root: Path) -> dict[str, str]:
    """Map submodule path -> GitHub HTTPS URL from ``<repo>/.gitmodules``."""
    gitmodules = repo_root / ".gitmodules"
    if not gitmodules.is_file():
        return {}
    entries: dict[str, str] = {}
    path: str | None = None
    url: str | None = None

    def flush() -> None:
        if path is not None and url is not None:
            entries[path] = github_https_url(url)

    for raw_line in gitmodules.read_text(encoding="utf-8").splitlines():
        line = raw_line.strip()
        if line.startswith("[submodule"):
            flush()
            path = url = None
        elif line.startswith("path"):
            path = line.split("=", 1)[1].strip()
        elif line.startswith("url"):
            url = line.split("=", 1)[1].strip()
    flush()
    return entries

github_https_url

github_https_url(url: str) -> str

Normalise git@github.com:ORG/X.git / ../X.git / https forms to a browsable URL.

Source code in src/mamut_routing_publish/docs_pages.py
def github_https_url(url: str) -> str:
    """Normalise ``git@github.com:ORG/X.git`` / ``../X.git`` / https forms to a browsable URL."""
    value = url.strip()
    if value.endswith(".git"):
        value = value[: -len(".git")]
    if value.startswith("git@github.com:"):
        return "https://github.com/" + value[len("git@github.com:") :]
    if value.startswith("../"):
        return f"{GITHUB_ORG_URL}/{value[3:]}"
    if value.startswith("ssh://git@github.com/"):
        return "https://github.com/" + value[len("ssh://git@github.com/") :]
    return value

github_bases_for_path

github_bases_for_path(
    repo_root: Path, relative_dir: str
) -> tuple[str, str, str]

(browse URL, blob base, raw base) for a directory of the superproject.

A submodule directory maps to its own repository; anything else maps to the same path inside the main repository.

Source code in src/mamut_routing_publish/docs_pages.py
def github_bases_for_path(repo_root: Path, relative_dir: str) -> tuple[str, str, str]:
    """(browse URL, blob base, raw base) for a directory of the superproject.

    A submodule directory maps to its own repository; anything else maps to
    the same path inside the main repository.
    """
    submodules = parse_gitmodules(repo_root)
    relative_dir = relative_dir.strip("/")
    for submodule_path, repo_url in submodules.items():
        if relative_dir == submodule_path or relative_dir.startswith(submodule_path + "/"):
            inner = relative_dir[len(submodule_path) :].strip("/")
            suffix = f"/{inner}" if inner else ""
            raw_repo = repo_url.replace("https://github.com/", "https://raw.githubusercontent.com/")
            return (
                f"{repo_url}/tree/{DEFAULT_BRANCH}{suffix}" if inner else repo_url,
                f"{repo_url}/blob/{DEFAULT_BRANCH}{suffix}",
                f"{raw_repo}/{DEFAULT_BRANCH}{suffix}",
            )
    suffix = f"/{relative_dir}" if relative_dir else ""
    return (
        f"{MAIN_REPO_URL}/tree/{DEFAULT_BRANCH}{suffix}",
        f"{MAIN_REPO_URL}/blob/{DEFAULT_BRANCH}{suffix}",
        f"https://raw.githubusercontent.com/ANR-MAMUT/{MAIN_REPO_NAME}/{DEFAULT_BRANCH}{suffix}",
    )

is_collection_family

is_collection_family(
    repo_root: Path, benchmark_name: BenchmarkName
) -> bool

Family-first collections live at benchmarks/<Family>/ (Poryos2026, Mamut2026).

Source code in src/mamut_routing_publish/docs_pages.py
def is_collection_family(repo_root: Path, benchmark_name: BenchmarkName) -> bool:
    """Family-first collections live at ``benchmarks/<Family>/`` (Poryos2026, Mamut2026)."""
    collection_dir = repo_root / "benchmarks" / benchmark_name.value
    if collection_dir.is_dir():
        return True
    return f"benchmarks/{benchmark_name.value}" in parse_gitmodules(repo_root)

family_source_dir

family_source_dir(
    repo_root: Path,
    problem_type: ProblemType,
    benchmark_name: BenchmarkName,
) -> str

Repo-relative directory holding the family's README/LICENSE (mirrors the publisher's license lookup).

Source code in src/mamut_routing_publish/docs_pages.py
def family_source_dir(repo_root: Path, problem_type: ProblemType, benchmark_name: BenchmarkName) -> str:
    """Repo-relative directory holding the family's README/LICENSE (mirrors the publisher's license lookup)."""
    classic = f"benchmarks/{problem_type.value}/{benchmark_name.value}"
    if (repo_root / classic).is_dir() or not is_collection_family(repo_root, benchmark_name):
        return classic
    return f"benchmarks/{benchmark_name.value}"

embedded_readme

embedded_readme(
    repo_root: Path,
    relative_dir: str,
    *,
    heading_delta: int = 1,
) -> str | None

The README of relative_dir rewritten for embedding, or None when absent.

Source code in src/mamut_routing_publish/docs_pages.py
def embedded_readme(repo_root: Path, relative_dir: str, *, heading_delta: int = 1) -> str | None:
    """The README of ``relative_dir`` rewritten for embedding, or None when absent."""
    readme = repo_root / relative_dir / "README.md"
    if not readme.is_file():
        return None
    _browse, blob_base, raw_base = github_bases_for_path(repo_root, relative_dir)
    text = readme.read_text(encoding="utf-8")
    return shift_headings(rewrite_relative_links(text, blob_base=blob_base, raw_base=raw_base), heading_delta)

root_markdown_pages

root_markdown_pages(
    repo_root: Path,
) -> list[GeneratedDocPage]

CONTRIBUTING.md / CHANGELOG.md of the superproject, verbatim (links -> GitHub).

Source code in src/mamut_routing_publish/docs_pages.py
def root_markdown_pages(repo_root: Path) -> list[GeneratedDocPage]:
    """``CONTRIBUTING.md`` / ``CHANGELOG.md`` of the superproject, verbatim (links -> GitHub)."""
    pages: list[GeneratedDocPage] = []
    _browse, blob_base, raw_base = github_bases_for_path(repo_root, "")
    for doc_path, source in ROOT_MARKDOWN_PAGES:
        source_path = repo_root / source
        if source_path.is_file():
            text = rewrite_relative_links(source_path.read_text(encoding="utf-8"), blob_base=blob_base, raw_base=raw_base)
        else:
            text = f"# {Path(source).stem.capitalize()}\n\nNot available in this build.\n"
        pages.append(GeneratedDocPage(path=doc_path, markdown=text.rstrip("\n") + f"\n\n---\n\n*Source: [`{source}`]({blob_base}/{source}).*\n"))
    return pages

generate_docs_pages

generate_docs_pages(
    repo_root: Path,
) -> list[GeneratedDocPage]

Every generated page of the documentation site for repo_root.

Source code in src/mamut_routing_publish/docs_pages.py
def generate_docs_pages(repo_root: Path) -> list[GeneratedDocPage]:
    """Every generated page of the documentation site for ``repo_root``."""
    pages: list[GeneratedDocPage] = []
    pages += project_pages(repo_root)
    pages += root_markdown_pages(repo_root)
    pages += package_readme_pages(repo_root)
    pages += family_pages(repo_root)
    pages += reference_pages(repo_root)
    return pages