File: hooks.py

package info (click to toggle)
python-mkdocs 1.6.1%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 7,812 kB
  • sloc: python: 14,346; javascript: 10,535; perl: 143; sh: 57; makefile: 30; xml: 11
file content (36 lines) | stat: -rw-r--r-- 1,155 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from __future__ import annotations

import re
from pathlib import Path
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from mkdocs.config.defaults import MkDocsConfig
    from mkdocs.structure.nav import Page


def _get_language_of_translation_file(path: Path) -> str:
    with path.open(encoding='utf-8') as f:
        translation_line = f.readline()
    m = re.search('^# (.+) translations ', translation_line)
    assert m
    return m[1]


def on_page_markdown(markdown: str, page: Page, config: MkDocsConfig, **kwargs) -> str | None:
    if page.file.src_uri == 'user-guide/choosing-your-theme.md':
        here = Path(config.config_file_path).parent

        def replacement(m: re.Match) -> str:
            lines = []
            for d in sorted(here.glob(m[2])):
                lang = _get_language_of_translation_file(Path(d, 'LC_MESSAGES', 'messages.po'))
                lines.append(f'{m[1]}`{d.name}`: {lang}')
            return '\n'.join(lines)

        return re.sub(
            r'^( *\* )\(see the list of existing directories `(.+)`\)$',
            replacement,
            markdown,
            flags=re.MULTILINE,
        )