|
26 | 26 |
|
27 | 27 | """ |
28 | 28 |
|
| 29 | +DOCUSAURUS_FRONTMATTER = """--- |
| 30 | +title: {title} |
| 31 | +id: {id} |
| 32 | +description: {description} |
| 33 | +--- |
| 34 | +
|
| 35 | +""" |
| 36 | + |
29 | 37 |
|
30 | 38 | def create_headers(version: str): |
31 | 39 | # Utility function to create Readme.io headers. |
@@ -210,3 +218,53 @@ def _doc_version(self) -> str: |
210 | 218 |
|
211 | 219 | major, minor = latest_version.major, latest_version.minor |
212 | 220 | 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