Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a custom pydoc renderer for Readme.io #2825

Merged
merged 6 commits into from Jul 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/utils/code_and_docs.sh
Expand Up @@ -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
Empty file added docs/pydoc/__init__.py
Empty file.
49 changes: 49 additions & 0 deletions docs/pydoc/renderers.py
@@ -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)