|
| 1 | +import argparse # noqa: INP001 |
| 2 | +import re |
| 3 | +import typing as t |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | +from markdown import Markdown # type: ignore[import-untyped] |
| 7 | +from markdownify import MarkdownConverter # type: ignore[import-untyped] |
| 8 | +from markupsafe import Markup |
| 9 | +from mkdocstrings_handlers.python._internal.config import PythonConfig |
| 10 | +from mkdocstrings_handlers.python._internal.handler import ( |
| 11 | + PythonHandler, |
| 12 | +) |
| 13 | + |
| 14 | +# ruff: noqa: T201 |
| 15 | + |
| 16 | + |
| 17 | +class CustomMarkdownConverter(MarkdownConverter): # type: ignore[misc] |
| 18 | + # Strip extra whitespace from code blocks |
| 19 | + def convert_pre(self, el: t.Any, text: str, parent_tags: t.Any) -> t.Any: |
| 20 | + return super().convert_pre(el, text.strip(), parent_tags) |
| 21 | + |
| 22 | + # bold items with doc-section-title in a span class |
| 23 | + def convert_span(self, el: t.Any, text: str, parent_tags: t.Any) -> t.Any: # noqa: ARG002 |
| 24 | + if "doc-section-title" in el.get("class", []): |
| 25 | + return f"**{text.strip()}**" |
| 26 | + return text |
| 27 | + |
| 28 | + # Remove the div wrapper for inline descriptions |
| 29 | + def convert_div(self, el: t.Any, text: str, parent_tags: t.Any) -> t.Any: |
| 30 | + if "doc-md-description" in el.get("class", []): |
| 31 | + return text.strip() |
| 32 | + return super().convert_div(el, text, parent_tags) |
| 33 | + |
| 34 | + # Map mkdocstrings details classes to Mintlify callouts |
| 35 | + def convert_details(self, el: t.Any, text: str, parent_tags: t.Any) -> t.Any: # noqa: ARG002 |
| 36 | + classes = el.get("class", []) |
| 37 | + |
| 38 | + # Handle source code details specially |
| 39 | + if "quote" in classes: |
| 40 | + summary = el.find("summary") |
| 41 | + if summary: |
| 42 | + file_path = summary.get_text().replace("Source code in ", "").strip() |
| 43 | + content = text[text.find("```") :] |
| 44 | + return f'\n<Accordion title="Source code in {file_path}" icon="code">\n{content}\n</Accordion>\n' |
| 45 | + |
| 46 | + callout_map = { |
| 47 | + "note": "Note", |
| 48 | + "warning": "Warning", |
| 49 | + "info": "Info", |
| 50 | + "tip": "Tip", |
| 51 | + } |
| 52 | + |
| 53 | + callout_type = None |
| 54 | + for cls in classes: |
| 55 | + if cls in callout_map: |
| 56 | + callout_type = callout_map[cls] |
| 57 | + break |
| 58 | + |
| 59 | + if not callout_type: |
| 60 | + return text |
| 61 | + |
| 62 | + content = text.strip() |
| 63 | + if content.startswith(callout_type): |
| 64 | + content = content[len(callout_type) :].strip() |
| 65 | + |
| 66 | + return f"\n<{callout_type}>\n{content}\n</{callout_type}>\n" |
| 67 | + |
| 68 | + def convert_table(self, el: t.Any, text: str, parent_tags: t.Any) -> t.Any: |
| 69 | + # Check if this is a highlighttable (source code with line numbers) |
| 70 | + if "highlighttable" in el.get("class", []): |
| 71 | + code_cells = el.find_all("td", class_="code") |
| 72 | + if code_cells: |
| 73 | + code = code_cells[0].get_text() |
| 74 | + code = code.strip() |
| 75 | + code = code.replace("```", "~~~") |
| 76 | + return f"\n```python\n{code}\n```\n" |
| 77 | + |
| 78 | + return super().convert_table(el, text, parent_tags) |
| 79 | + |
| 80 | + |
| 81 | +class AutoDocGenerator: |
| 82 | + def __init__(self, source_paths: list[str], theme: str = "material", **options: t.Any) -> None: |
| 83 | + self.source_paths = source_paths |
| 84 | + self.theme = theme |
| 85 | + self.handler = PythonHandler(PythonConfig.from_data(), base_dir=Path.cwd()) |
| 86 | + self.options = options |
| 87 | + |
| 88 | + self.handler._update_env( # noqa: SLF001 |
| 89 | + Markdown(), |
| 90 | + config={"mdx": ["toc"]}, |
| 91 | + ) |
| 92 | + |
| 93 | + md = Markdown(extensions=["fenced_code"]) |
| 94 | + |
| 95 | + def simple_convert_markdown( |
| 96 | + text: str, |
| 97 | + heading_level: int, |
| 98 | + html_id: str = "", |
| 99 | + **kwargs: t.Any, |
| 100 | + ) -> t.Any: |
| 101 | + return Markup(md.convert(text) if text else "") # noqa: S704 # nosec |
| 102 | + |
| 103 | + self.handler.env.filters["convert_markdown"] = simple_convert_markdown |
| 104 | + |
| 105 | + def generate_docs_for_module( |
| 106 | + self, |
| 107 | + module_path: str, |
| 108 | + ) -> str: |
| 109 | + options = self.handler.get_options( |
| 110 | + { |
| 111 | + "docstring_section_style": "list", |
| 112 | + "merge_init_into_class": True, |
| 113 | + "show_signature_annotations": True, |
| 114 | + "separate_signature": True, |
| 115 | + "show_source": True, |
| 116 | + "show_labels": False, |
| 117 | + "show_bases": False, |
| 118 | + **self.options, |
| 119 | + }, |
| 120 | + ) |
| 121 | + |
| 122 | + module_data = self.handler.collect(module_path, options) |
| 123 | + html = self.handler.render(module_data, options) |
| 124 | + |
| 125 | + return str( |
| 126 | + CustomMarkdownConverter( |
| 127 | + code_language="python", |
| 128 | + ).convert(html), |
| 129 | + ) |
| 130 | + |
| 131 | + def process_mdx_file(self, file_path: Path) -> bool: |
| 132 | + content = file_path.read_text(encoding="utf-8") |
| 133 | + original_content = content |
| 134 | + |
| 135 | + # Find the header comment block |
| 136 | + header_match = re.search( |
| 137 | + r"\{\s*/\*\s*((?:::.*?\n?)*)\s*\*/\s*\}", |
| 138 | + content, |
| 139 | + re.MULTILINE | re.DOTALL, |
| 140 | + ) |
| 141 | + |
| 142 | + if not header_match: |
| 143 | + return False |
| 144 | + |
| 145 | + header = header_match.group(0) |
| 146 | + module_lines = header_match.group(1).strip().split("\n") |
| 147 | + |
| 148 | + # Generate content for each module |
| 149 | + markdown_blocks = [] |
| 150 | + for line in module_lines: |
| 151 | + if line.startswith(":::"): |
| 152 | + module_path = line.strip()[3:].strip() |
| 153 | + if module_path: |
| 154 | + markdown = self.generate_docs_for_module(module_path) |
| 155 | + markdown_blocks.append(markdown) |
| 156 | + |
| 157 | + keep_end = content.find(header) + len(header) |
| 158 | + new_content = content[:keep_end] + "\n\n" + "\n".join(markdown_blocks) |
| 159 | + |
| 160 | + # Write back if changed |
| 161 | + if new_content != original_content: |
| 162 | + file_path.write_text(new_content, encoding="utf-8") |
| 163 | + print(f"[+] Updated: {file_path}") |
| 164 | + return True |
| 165 | + |
| 166 | + return False |
| 167 | + |
| 168 | + def process_directory(self, directory: Path, pattern: str = "**/*.mdx") -> int: |
| 169 | + if not directory.exists(): |
| 170 | + print(f"[!] Directory does not exist: {directory}") |
| 171 | + return 0 |
| 172 | + |
| 173 | + files_processed = 0 |
| 174 | + files_modified = 0 |
| 175 | + |
| 176 | + for mdx_file in directory.glob(pattern): |
| 177 | + if mdx_file.is_file(): |
| 178 | + files_processed += 1 |
| 179 | + if self.process_mdx_file(mdx_file): |
| 180 | + files_modified += 1 |
| 181 | + |
| 182 | + return files_modified |
| 183 | + |
| 184 | + |
| 185 | +def main() -> None: |
| 186 | + """Main entry point for the script.""" |
| 187 | + |
| 188 | + parser = argparse.ArgumentParser(description="Generate auto-docs for MDX files") |
| 189 | + parser.add_argument("--directory", help="Directory containing MDX files", default="docs") |
| 190 | + parser.add_argument("--pattern", default="**/*.mdx", help="File pattern to match") |
| 191 | + parser.add_argument( |
| 192 | + "--source-paths", |
| 193 | + nargs="+", |
| 194 | + default=["dreadnode"], |
| 195 | + help="Python source paths for module discovery", |
| 196 | + ) |
| 197 | + parser.add_argument( |
| 198 | + "--show-if-no-docstring", |
| 199 | + type=bool, |
| 200 | + default=False, |
| 201 | + help="Show module/class/function even if no docstring is present", |
| 202 | + ) |
| 203 | + parser.add_argument("--theme", default="material", help="Theme to use for rendering") |
| 204 | + |
| 205 | + args = parser.parse_args() |
| 206 | + |
| 207 | + # Create generator |
| 208 | + generator = AutoDocGenerator( |
| 209 | + source_paths=args.source_paths, |
| 210 | + theme=args.theme, |
| 211 | + show_if_no_docstring=args.show_if_no_docstring, |
| 212 | + ) |
| 213 | + |
| 214 | + # Process directory |
| 215 | + directory = Path(args.directory) |
| 216 | + modified_count = generator.process_directory(directory, args.pattern) |
| 217 | + |
| 218 | + print(f"\n[+] Auto-doc generation complete. {modified_count} files were updated.") |
| 219 | + |
| 220 | + |
| 221 | +if __name__ == "__main__": |
| 222 | + main() |
0 commit comments