Skip to content

Commit

Permalink
Add generator of literate navs
Browse files Browse the repository at this point in the history
  • Loading branch information
oprypin committed Apr 30, 2021
1 parent a614fb4 commit 5846b8e
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
1 change: 1 addition & 0 deletions mkdocs_gen_files/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import mkdocs.utils

from .editor import FilesEditor
from .nav import Nav # noqa

log = logging.getLogger(f"mkdocs.plugins.{__name__}")
log.addFilter(mkdocs.utils.warning_filter)
Expand Down
44 changes: 44 additions & 0 deletions mkdocs_gen_files/nav.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import dataclasses
from typing import Iterable, Mapping, Optional, Tuple, Union


class Nav:
def __init__(self):
self._data = {}

def __setitem__(self, keys: Union[str, Tuple[str, ...]], value: str):
if isinstance(keys, str):
keys = (keys,)
cur = self._data
for key in keys:
if not isinstance(key, str):
raise TypeError(
f"The navigation path must consist of strings, but got a {type(key)}"
)
cur = cur.setdefault(key, {})
cur[None] = value

@dataclasses.dataclass
class Item:
level: int
title: str
filename: Optional[str]

def items(self) -> Iterable[Item]:
return self._items(self._data, 0)

@classmethod
def _items(cls, data: Mapping, level: int) -> Iterable[Item]:
for key, value in data.items():
if key is not None:
yield cls.Item(level=level, title=key, filename=value.get(None))
yield from cls._items(value, level + 1)

def build_literate_nav(self, indentation: Union[int, str] = "") -> Iterable[str]:
if isinstance(indentation, int):
indentation = " " * indentation
for item in self.items():
line = item.title
if item.filename is not None:
line = f"[{line}]({item.filename})"
yield indentation + " " * item.level + "* " + line + "\n"

0 comments on commit 5846b8e

Please sign in to comment.