from fastcore.test import test_eq, expect_fail
from tempfile import TemporaryDirectoryDocs tree & sidebar generation
[tool.docs] and docs_dir into llms.txt, pkg/_modidx.py, and Quarto sidebar.yml, plus {{< doc ... >}} shortcode expansion
- single source:
docs_tree,to_sidebar,write_sidebar, andwrite_pkg_docsresolvenbs/ordocs/, optionaldir/index.*frontmatter (title,description,order; frontmatter-only index sets section title/order without adding a page),.py# - key: valmodule frontmatter (py_frontmatter), and optional[tool.docs]inpyproject.tomlintosidebar.yml,llms.txt, andpkg/_modidx.py(docs = ...) - API docs:
expand_docsreplaces{{< doc sym [[level]{.quarto-shortcode__-param data-is-shortcode="1" data-value="N]"} >}}(symbols defaultlevel=3, modules defaultlevel=2; optional frontmattermodule: pkg.modresolves bare names first; skips fenced and inline code) in.md/.qmdfiles without Jupyter (DocRendererdefault,BasicMarkdownRendererinnbdev);render_modandmod_pagerender a Python module directly or as a standalone page with YAML frontmatter;py_fencesandclean_doc_mdextract and normalize executable{python}fences (dropping#| hideblocks and stripping#|directives) - sidebar protection:
write_sidebarskips hand-writtensidebar.ymllacking# Generated byunlessforce=True - symbol links:
DocLookupresolves and linkifies backticked symbols fromnbdeventry points and liveextramaps (with relativerel_tolinks);mod_symsandwrite_modidxbuild and persistd = ...inpkg/_modidx.py
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.
py_frontmatter
def py_frontmatter(
src:str, # Python module source text
)->dict: # Parsed YAML dict from leading `# - key: val` comments after the module docstringParse # - 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'))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')])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.
DocRenderer
def DocRenderer(
sym, name:str | None=None, title_level:int=3, maxline:int=110
):Markdown renderer for expand_docs with a heading
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
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
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
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
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 _crlfrender_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 _hrendmod_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.
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
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
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'