-
-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |