Skip to main content

Docs tree & sidebar generation

One-way resolution of [tool.docs] and docs_dir into llms.txt, pkg/_modidx.py, and Quarto sidebar.yml, plus {{< doc ... >}} shortcode expansion
from fastcore.test import test_eq, expect_fail
from tempfile import TemporaryDirectory

Document metadata

doc_meta reads (title, desc, order, has_body) from .ipynb, .qmd, .md, or .py. has_body is False for frontmatter-only pages without listing: or body content.


source

py_frontmatter

def py_frontmatter(
    src:str, # Python module source text
)->dict: # Parsed YAML dict from leading `# - key: val` comments after the module docstring

Parse # - key: val frontmatter comments immediately after a module’s docstring

test_eq(py_frontmatter('"""First para.\n\nSecond para.\n"""\n# - order:1\n# - title:My Title\nx = 1\n'), dict(order=1, title='My Title'))

source

doc_meta

def doc_meta(
    path:str | pathlib.Path, # Path to `.ipynb`, `.qmd`, `.md`, or `.py`
)->tuple[str, str, float, bool]: # `(title, desc, order, has_body)`

Extract (title, desc, order, has_body) from frontmatter, notebook headers, or Python docstrings

test_eq(_md_meta('---\ntitle: Quick Guide\ndescription: Start here\norder: 2\n---\n\nBody.\n'), ('Quick Guide', 'Start here', 2.0, True))
test_eq(_md_meta('---\ntitle: Tutorials\ndescription: Step by step\norder: 1\n---\n'), ('Tutorials', 'Step by step', 1.0, False))
test_eq(_md_meta('---\ntitle: Guides\nlisting:\n  type: table\n---\n'), ('Guides', '', float('inf'), True))
test_eq(doc_meta(Path('01_llms.ipynb')), ('llms.txt generation', 'Build `llms.txt` from `pkg/skill.py`', float('inf'), True))
test_eq(doc_meta(Path('../pyskills/docs.py'))[:2], ('docs', 'One-way resolution of `[tool.docs]` and `docs_dir` into `llms.txt`, `pkg/_modidx.py`, and Quarto `sidebar.yml`, plus `{{< doc ... >}}` shortcode expansion'))
test_eq(_stem_title(Path('03c_aio.ipynb')), 'Aio')

Resolving [tool.docs] and docs_dir

test_eq(_parse_entry(None, 'pyskills.core', set()), [('mod', 'pyskills.core')])
test_eq(_parse_entry(None, ['Demo', 'https://example.com', 'Live'], set()), [('link', 'Demo', 'https://example.com', 'Live')])

docs_tree and to_sidebar


source

docs_tree

def docs_tree(
    root:str | pathlib.Path, # Project root containing `pyproject.toml`
    docs_dir:str | pathlib.Path=None, # Docs/notebooks directory
    *, mod_urls:dict=None, # Optional `{module: rel_url}` map
    url_fn:<built-in function callable>=None, # Maps doc-relative `Path` to published URL
)->dict:

Resolve project docs into {section: items | {desc?, items?, Sub: ...}}


source

to_sidebar

def to_sidebar(
    root:str | pathlib.Path, # Project root containing `pyproject.toml`
    docs_dir:str | pathlib.Path=None, # Docs/notebooks directory
    *, prefix:str='', # Path prefix for local pages (e.g. `'docs/'`)
)->list:

Build Quarto website.sidebar.contents for local pages only

write_sidebar and write_pkg_docs


source

write_sidebar

def write_sidebar(
    docs_dir:str | pathlib.Path, # Directory where `sidebar.yml` lives
    contents:list, # Quarto `website.sidebar.contents` list
    marker:str='# Generated by pyskills\n', # Header comment marking generated files
    force:bool=False, # Overwrite even if existing `sidebar.yml` is hand-written
)->bool:

Write generated sidebar.yml via write_if_changed, skipping hand-written files unless force


source

write_pkg_docs

def write_pkg_docs(
    pkg_dir:str | pathlib.Path, # Package directory where `_modidx.py` is written
    docs:dict, # `{section: items | {desc?, items?, Sub: ...}}`
)->pathlib.Path | None:

Write docs = ... in pkg/_modidx.py when docs has link tuples; remove it otherwise

_td = TemporaryDirectory()
_proj = Path(_td.name)/'proj'
_files = {
    'pyproject.toml': '[tool.docs]\nexclude = ["unpublished"]\npages = [["Get Started", "index.md"]]\nTutorials = "tutorials"\nReference = ["ref/b.md", "ref"]\nExamples = [["Demo", "https://example.com/demo", "Live"]]\nGuides = "guides"\n',
    'docs/index.md': '# Home\n',
    'docs/tutorials/index.qmd': '---\ntitle: Tutorials\ndescription: Step by step\n---\n',
    'docs/tutorials/start.md': '---\ntitle: Start\ndescription: First steps\norder: 1\n---\n\nBody.\n',
    'docs/ref/a.md': '# Ref A\n\n> First ref\n\nBody.\n',
    'docs/ref/b.md': '# Ref B\n\n> Second ref\n\nBody.\n',
    'docs/guides/intro.md': '# Intro\n\n> Basics\n\nBody.\n',
    'docs/guides/adv/index.qmd': '---\ntitle: Advanced\nlisting: true\n---\n',
    'docs/guides/adv/deep.md': '# Deep\n\n> Details\n\nBody.\n',
    'docs/unpublished/draft.md': '# Draft\n'}
for rel, txt in _files.items():
    (_proj/rel).parent.mkdir(parents=True, exist_ok=True)
    (_proj/rel).write_text(txt)
tree = docs_tree(_proj, _proj/'docs')
g = dict(items=[('Intro', 'guides/intro.html.md', 'Basics')], Advanced=[('Deep', 'guides/adv/deep.html.md', 'Details')])
exp = dict(Tutorials=dict(desc='Step by step', items=[('Start', 'tutorials/start.html.md', 'First steps')]),
    Reference=[('Ref B', 'ref/b.html.md', 'Second ref'), ('Ref A', 'ref/a.html.md', 'First ref')],
    Examples=[('Demo', 'https://example.com/demo', 'Live')], Guides=g)
test_eq(tree, exp)
sb = to_sidebar(_proj, _proj/'docs', prefix='docs/')
adv = dict(section='Advanced', href='docs/guides/adv/index.qmd', contents=['docs/guides/adv/deep.md'])
test_eq(sb, [{'text': 'Get Started', 'href': 'docs/index.md'}, {'section': 'Tutorials', 'contents': ['docs/tutorials/start.md']},
    {'section': 'Reference', 'contents': ['docs/ref/b.md', 'docs/ref/a.md']},
    {'section': 'Guides', 'contents': ['docs/guides/intro.md', adv]}])
assert write_sidebar(_proj/'docs', sb) and not write_sidebar(_proj/'docs', sb)
(_proj/'docs'/'sidebar.yml').write_text('website: {}\n')
assert not write_sidebar(_proj/'docs', sb) and write_sidebar(_proj/'docs', sb, force=True)
(_proj/'pyproject.toml').write_text('[tool.docs]\nTutorials = "tutorials"\n')
test_eq(to_sidebar(_proj, _proj/'docs', prefix='docs/')[0], 'docs/index.md')
(_proj/'pyproject.toml').write_text('[tool.docs]\nexclude = ["index.md"]\nTutorials = "tutorials"\n')
assert to_sidebar(_proj, _proj/'docs', prefix='docs/')[0] != 'docs/index.md'
sb
_pkg = _proj/'demo'
_pkg.mkdir()
dp = write_pkg_docs(_pkg, tree)
test_eq(dp, _pkg/'_modidx.py')
assert write_pkg_docs(_pkg, tree) is None
test_eq(write_pkg_docs(_pkg, {'API': ['demo.core']}), _pkg/'_modidx.py')
assert not dp.exists()
dp.write_text("# Autogenerated by nbdev\n\nd = {'settings': {}}\n")
test_eq(write_pkg_docs(_pkg, tree), dp)
assert "d = {'settings': {}}" in dp.read_text() and 'docs = ' in dp.read_text()
test_eq(write_pkg_docs(_pkg, {'API': ['demo.core']}), dp)
assert dp.exists() and "d = {'settings': {}}" in dp.read_text() and 'docs =' not in dp.read_text()
_td.cleanup()

Shortcode expansion

expand_docs replaces {{< doc sym [[level]{.quarto-shortcode__-param data-is-shortcode="1" data-value="N]"} >}} shortcodes with rendered symbol or module documentation, skipping fenced code blocks and inline code. When YAML frontmatter sets module:, bare names resolve under that module first while full dotted paths still work. mod_page builds a standalone Markdown/Quarto page (YAML frontmatter from # - key: val comments and module docstring paragraph 1, plus body, top-level Markdown strings, and symbols in definition order) for a Python module.


source

DocRenderer

def DocRenderer(
    sym, name:str | None=None, title_level:int=3, maxline:int=110
):

Markdown renderer for expand_docs with a heading


source

py_fences

def py_fences(
    txt:str, # Markdown or docstring text to scan
)->list[tuple[str, int]]: # `(code, line_offset)` pairs for each top-level `{python}` fence (`line_offset` is 0-based body start in `txt`)

Extract executable {python} fenced code blocks and their 0-based body line offsets from Markdown txt


source

clean_doc_md

def clean_doc_md(
    txt:str, # Markdown or rendered docstring text
)->str: # Text with hidden `{python}` blocks dropped, `#| ` directives stripped, and `{python}` normalized to `python`

Prepare Markdown txt with {python} fences for static docs, dropping #| hide blocks and stripping #| directives


source

render_mod

def render_mod(
    mod:module, # Imported Python module to document
    level:int=2, # Base heading level for top-level symbols (class methods use `sym_level + 1`)
    renderer:type=DocRenderer, # Renderer class or callable taking `(sym, title_level=level)`
    skip_first:bool=False, # Omit paragraph 1 of the module docstring (when already in YAML `description:`)
    src:str=None, # Optional module source text (defaults to reading `mod.__file__`)
)->str:

Render a module’s docstring, top-level Markdown strings, and public classes/callables in definition order


source

mod_page

def mod_page(
    mod_nm:str, # Dotted module name to import and render
    path:str | pathlib.Path=None, # Optional `.py` path (defaults to `mod.__file__`)
    level:int=2, # Heading level for top-level module symbols (class methods use `level + 1`)
    renderer:type=DocRenderer, # Renderer class or callable taking `(sym, title_level=level)`
)->str:

Render a standalone Markdown/Quarto page (YAML frontmatter + module docs) for mod_nm


source

expand_docs

def expand_docs(
    text:str, # Markdown or Quarto source text
    renderer:type=DocRenderer, # Renderer class or callable taking `(sym, title_level=level)`
)->str:

Expand {{< doc sym [[level]{.quarto-shortcode__-param data-is-shortcode="1" data-value="N]"} >}} shortcodes in text, skipping code blocks and inline code

_src = r"""---
title: Demo
module: pyskills.core
---
Use `{{< doc skip.inline >}}` in prose.

```markdown
{{< doc skip.fenced >}}
```

{{< doc doc level=2 >}}

{{< doc fastcore.docments.MarkdownRenderer._repr_markdown_ >}}
"""
_out = expand_docs(_src)
assert '`{{< doc skip.inline >}}`' in _out and '{{< doc skip.fenced >}}' in _out
assert '## doc' in _out and '### MarkdownRenderer._repr_markdown_' in _out
assert '---\n\n##' not in _out and '---\n\n###' not in _out
with expect_fail(ImportError, contains='no_such_sym'): expand_docs('{{< doc pyskills.core.no_such_sym >}}')
_crlf = expand_docs(_src.replace('\n', '\r\n'))
assert _crlf.startswith('---\r\ntitle: Demo\r\nmodule: pyskills.core\r\n---\r\n') and '## doc' in _crlf

render_mod, mod_page, and {{< doc pkg.mod >}} render a module in AST definition order (filtered by __all__), interleaving non-first top-level Markdown strings (skipping #| hide strings), normalizing {python} fences via clean_doc_md, skipping constants, and nesting symbol and method headings below any preceding section heading.

def beta(x:int): "Beta fn"
class Alpha:
    "Alpha cls"
    @property
    def val(self)->int: "Val prop"
    def run(self): "Run meth"

_m = types.ModuleType('_demo', 'Summary para.\n\nDetail para.')
_m.__all__ = ['CONST', 'beta', 'Alpha']
_m.CONST, _m.beta, _m.Alpha = 42, beta, Alpha

_full = render_mod(_m)
assert 'Summary para.' in _full and 'Detail para.' in _full and 'CONST' not in _full
assert _full.index('## beta') < _full.index('## Alpha') < _full.index('### Alpha.val') < _full.index('### Alpha.run')
_rest = render_mod(_m, skip_first=True)
assert 'Summary para.' not in _rest and 'Detail para.' in _rest
assert BaseException.args in _cls_members(BaseException) and str.split in _cls_members(str)
_msrc = '"""Summary para.\n\nDetail para."""\n\n"""## Types\n\n```python\n# not a heading\n```\n"""\n\nclass Alpha: pass\n\n"""## Functions"""\n\ndef beta(x): pass\n'
_sec = render_mod(_m, src=_msrc)
assert _sec.index('## Types') < _sec.index('### Alpha') < _sec.index('#### Alpha.val') < _sec.index('## Functions') < _sec.index('### beta')
_doc_md = 'Intro.\n\n```{python}\n#| hide\nassert 1 == 1\n```\n\n```{python}\n#| eval: false\nx = 1\n```\n\n```python\ny = 2\n```'
test_eq(py_fences(_doc_md), [('#| hide\nassert 1 == 1', 3), ('#| eval: false\nx = 1', 8)])
test_eq(clean_doc_md(_doc_md), 'Intro.\n\n```python\nx = 1\n```\n\n```python\ny = 2\n```')
_hsrc = '"""Mod doc."""\n\n"""#| hide\n```{python}\n_x = 1\n```\n"""\n\n"""## Sec\n\n```{python}\n#| eval: false\nbeta(1)\n```\n"""\n\ndef beta(x): pass\n'
_hrend = render_mod(_m, src=_hsrc)
assert '_x = 1' not in _hrend and '{python}' not in _hrend and '```python\nbeta(1)\n```' in _hrend

mod_page wraps render_mod with YAML frontmatter (using paragraph 1 as description: so Quarto does not repeat it), and expand_docs expands {{< doc pkg.mod >}} inline.

_fm, _bd = frontmatter(mod_page('pyskills.docs'))
assert _fm['title'] == 'docs' and 'One-way resolution' in _fm['description'] and 'One-way resolution' not in _bd
assert '## py_frontmatter' in _bd and '## render_mod' in _bd and '## mod_page' in _bd
assert '## SkillTestClass' in expand_docs('{{< doc pyskills.skill >}}')

Symbol index and linkification

DocLookup maps symbol names from installed nbdev entry points (plus optional live extra maps) to documentation and GitHub source URLs, and linkifies backticked symbols in Markdown while skipping fenced/indented code blocks and existing links. mod_syms and write_modidx build and persist d = {'settings': ..., 'syms': ...} in pkg/_modidx.py for non-nbdev packages.


source

DocLookup

def DocLookup(
    strip_libs:tuple=(), # Package names whose module prefixes are stripped for bare symbol lookups
    incl_libs=None, # Optional package names to restrict entry-point loading to
    skip_mods=None, # Module names excluded when stripping prefixes
    ns:dict=None, # Optional namespace dict to resolve module import aliases (e.g. `np.array`)
    extra:dict=None, # Optional live `{mod: {sym: (doc_path, py_path)}}` mapping overriding installed entry points
):

Mapping from symbol names to documentation and source URLs


source

write_modidx

def write_modidx(
    pkg_dir:str | pathlib.Path, # Package directory where `_modidx.py` is written
    syms:dict, # `{mod_nm: {qual_sym: (page_html#anchor, py_rel)}}` from `mod_syms`
    settings:dict, # Dict with `doc_host`, `doc_baseurl`, `lib_path`, `git_url`, `branch`
    header:str='# Autogenerated by fastship\n', # File header when creating `_modidx.py`
)->pathlib.Path | None:

Write d = {'settings': ..., 'syms': ...} in pkg/_modidx.py via set_py_var


source

mod_syms

def mod_syms(
    mod_pages:dict, # `{mod_nm: (page_html_rel, py_rel)}` mapping modules to their HTML page and source path
)->dict: # `{mod_nm: {qual_sym: (page_html#anchor, py_rel)}}`

Build the syms index mapping public modules, classes, callables, and class members to doc anchors and source paths

_extra = {'demo.api': {'demo.api': ('docs/api/api.html', 'demo/api.py'), 'demo.api.Foo': ('docs/api/api.html#foo', 'demo/api.py'), 'demo.api.Foo.bar': ('docs/api/api.html#foo.bar', 'demo/api.py')}}
_lk = DocLookup(extra=_extra)
test_eq(_lk.doc('Foo', rel_to='docs/api/other.md'), 'api.html#foo')
test_eq(_lk.doc('Foo', rel_to='docs/api/api.md'), '#foo')
test_eq(_lk.doc('Foo.bar', rel_to='index.md'), 'docs/api/api.html#foo.bar')
test_eq(_lk.linkify('Use `Foo` and [`Foo`](custom.html) and `Foo.bar()`.\n```python\n`Foo`\n```', rel_to='docs/api/other.md'),
    'Use [`Foo`](api.html#foo) and [`Foo`](custom.html) and [`Foo.bar()`](api.html#foo.bar).\n```python\n`Foo`\n```')
_src_url = _lk.code('fastcore.xtras.md_sub')
assert _src_url and '#L' in _src_url and '#LNone' not in _src_url
_ms = mod_syms({'pyskills.docs': ('docs.html', 'pyskills/docs.py')})
assert _ms['pyskills.docs']['pyskills.docs.DocLookup'][0] == 'docs.html#doclookup' and _ms['pyskills.docs']['pyskills.docs.DocLookup.linkify'][0] == 'docs.html#doclookup.linkify'