Add a custom pydoc renderer for Readme.io (#2825)

* add custom pydoc renderer

* create an example

* revert example code
This commit is contained in:
Massimiliano Pippi 2022-07-22 10:43:51 +02:00 committed by GitHub
parent 11c46006df
commit 8ee2b6b403
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 51 additions and 1 deletions

View File

@ -18,9 +18,10 @@ echo
echo "========== Generate the API documentation ========== "
set -e # Fails on any error in the following loop
export PYTHONPATH=$PWD/docs/pydoc # Make the renderers available to pydoc
cd docs/_src/api/api/
for file in ../pydoc/* ; do
echo "Processing" $file
pydoc-markdown "$file"
done
echo
echo

0
docs/pydoc/__init__.py Normal file
View File

49
docs/pydoc/renderers.py Normal file
View File

@ -0,0 +1,49 @@
import sys
import io
import dataclasses
import docspec
import typing as t
from pathlib import Path
from pydoc_markdown.interfaces import Context, Renderer
from pydoc_markdown.contrib.renderers.markdown import MarkdownRenderer
README_FRONTMATTER = """---
title: {title}
excerpt: {excerpt}
category: {category}
---
"""
@dataclasses.dataclass
class ReadmeRenderer(Renderer):
"""
This custom Renderer is heavily based on the `MarkdownRenderer`,
it just prepends a front matter so that the output can be published
directly to readme.io.
"""
# These settings will be used in the front matter output
title: str
category: str
excerpt: str
# This exposes a special `markdown` settings value that can be used to pass
# parameters to the underlying `MarkdownRenderer`
markdown: MarkdownRenderer = dataclasses.field(default_factory=MarkdownRenderer)
def init(self, context: Context) -> None:
self.markdown.init(context)
def render(self, modules: t.List[docspec.Module]) -> None:
if self.markdown.filename is None:
sys.stdout.write(self._frontmatter())
self.markdown.render_to_stream(modules, sys.stdout)
else:
with io.open(self.markdown.filename, "w", encoding=self.markdown.encoding) as fp:
fp.write(self._frontmatter())
self.markdown.render_to_stream(modules, t.cast(t.TextIO, fp))
def _frontmatter(self) -> str:
return README_FRONTMATTER.format(title=self.title, category=self.category, excerpt=self.excerpt)