Skip to content

Commit 8cb7b74

Browse files
authored
feat: Add Docusaurus renderer (#7)
* feat: Add Docusaurus renderer * use slug as id * replace slug with id
1 parent 77faa25 commit 8cb7b74

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

src/haystack_pydoc_tools/renderers.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,14 @@
2626
2727
"""
2828

29+
DOCUSAURUS_FRONTMATTER = """---
30+
title: {title}
31+
id: {id}
32+
description: {description}
33+
---
34+
35+
"""
36+
2937

3038
def create_headers(version: str):
3139
# Utility function to create Readme.io headers.
@@ -210,3 +218,53 @@ def _doc_version(self) -> str:
210218

211219
major, minor = latest_version.major, latest_version.minor
212220
return f"v{major}.{minor}"
221+
222+
@dataclasses.dataclass
223+
class DocusaurusRenderer(Renderer):
224+
"""
225+
This custom Renderer is heavily based on the `MarkdownRenderer`,
226+
it just prepends a front matter so that the output can be published
227+
directly to docusaurus.
228+
"""
229+
230+
# These settings will be used in the front matter output
231+
title: str
232+
id: str
233+
description: str
234+
235+
# This exposes a special `markdown` settings value that can be used to pass
236+
# parameters to the underlying `MarkdownRenderer`
237+
markdown: MarkdownRenderer = dataclasses.field(default_factory=MarkdownRenderer)
238+
239+
def init(self, context: Context) -> None:
240+
self.markdown.init(context)
241+
self.version = os.environ.get("PYDOC_TOOLS_HAYSTACK_DOC_VERSION", self._doc_version())
242+
243+
def _doc_version(self) -> str:
244+
"""
245+
Returns the docs version.
246+
"""
247+
# We're assuming hatch is installed and working
248+
res = subprocess.run(["hatch", "version"], capture_output=True, check=True)
249+
res.check_returncode()
250+
full_version = res.stdout.decode().strip()
251+
major, minor = full_version.split(".")[:2]
252+
if "rc0" in full_version:
253+
return f"v{major}.{minor}-unstable"
254+
return f"v{major}.{minor}"
255+
256+
def render(self, modules: t.List[docspec.Module]) -> None:
257+
if self.markdown.filename is None:
258+
sys.stdout.write(self._frontmatter())
259+
self.markdown.render_single_page(sys.stdout, modules)
260+
else:
261+
with open(self.markdown.filename, "w", encoding=self.markdown.encoding) as fp:
262+
fp.write(self._frontmatter())
263+
self.markdown.render_single_page(t.cast(t.TextIO, fp), modules)
264+
265+
def _frontmatter(self) -> str:
266+
return DOCUSAURUS_FRONTMATTER.format(
267+
title=self.title,
268+
id=self.id,
269+
description=self.description,
270+
)

0 commit comments

Comments
 (0)