Files
mxpic_forge/md_doc_gen.py
T

80 lines
2.7 KiB
Python

import os
import shutil
from pathlib import Path
basic_md_info = "\
.. mxpic_handbook documentation master file, created by\n\
sphinx-quickstart on Sun May 3 16:05:57 2026.\n\
You can adapt this file completely to your liking, but it should at least\n\
contain the root `toctree` directive.\n\n\
# Welcome to the automated documentation for the mxPIC silicon photonics library.\n\
```{toctree}\n\
:maxdepth: 2\n\
:caption: Components:\n\n\
"
def generate_myst_docs(src_dir: str, docs_api_dir: str) -> None:
"""
Scans a Python package and generates MyST Markdown files for Sphinx autodoc.
"""
src_path = Path(src_dir).resolve()
api_path = Path(docs_api_dir).resolve()
# Clean the old api directory to prevent dead links from deleted files
if api_path.exists():
# shutil.rmtree(api_path)
pass
else :
api_path.mkdir(parents=True, exist_ok=True)
package_name = src_path.name
generated_files = []
print(f"Scanning {package_name} for Python modules...")
index_info = basic_md_info
# Recursively find all .py files
for py_file in src_path.rglob("*.py"):
# Skip init files and private/internal scripts if desired
if py_file.name == "__init__.py" or py_file.name.startswith("_"):
continue
# Convert file path to Python module format (e.g., mxpic.primitives.mzm)
rel_path = py_file.relative_to(src_path.parent.parent)
class_name = str(rel_path.with_suffix("")).replace(os.sep, ".")
module_name = str(rel_path.with_suffix("")).replace(os.sep, "\\")
index_md_name = str(rel_path.with_suffix("")).replace(os.sep, "/")
# Create the markdown file
md_filename = api_path / f"{module_name}.md"
# MyST Markdown format using Sphinx autodoc directives
content = f"# {module_name}\n \
```{{eval-rst}}\n \
.. automodule:: {class_name}\n\
:members:\n\
:undoc-members:\n\
:show-inheritance:\n\
```\n\
"
## Building .md file for each .py file
try :
try : os.makedirs(name=str(md_filename.parent.resolve()))
except : pass
with open(file=str(md_filename.resolve()),mode="w") as md_file:
md_file.write(content)
print(f"Generated: {docs_api_dir}{module_name}.md")
except Exception as e:
print(e)
## Writing information into the index.md file
index_info = index_info + f"{index_md_name}\n"
with open(file=docs_api_dir+"index.md",mode="w") as md_file:
md_file.write(index_info)
if __name__ == "__main__":
generate_myst_docs(src_dir="mxpic\\components\\",docs_api_dir="mxpic\\docs\\source\\")