Skip to content
Myr

docs.py

This file

Path

scripts/docs.py

362 lines · 13.2 KiB · Python

Last changed by

⬆️ Migrate to Zensical (#1470)Sebastián Ramírezbefore adoptionf655ef2

History of this file

Take it

The walk stopped after 200 commits: lines older than 2c8a54c point at it.

⬆ Bump pydantic from 2.13.1 to 2.13.2 (#1703)dependabot[bot]before adoption2c8a54c

lines 1–84why, one step back
1import logging
2import os3import re4import shutil5import subprocess6from http.server import HTTPServer, SimpleHTTPRequestHandler7from pathlib import Path89import typer10from ruff.__main__ import find_ruff_bin1112logging.basicConfig(level=logging.INFO)1314mkdocs_name = "mkdocs.yml"15docs_path = Path("docs")16en_docs_path = Path("")1718app = typer.Typer()192021@app.callback()22def callback() -> None:23 # For MacOS with Cairo24 os.environ["DYLD_FALLBACK_LIBRARY_PATH"] = "/opt/homebrew/lib"252627def generate_readme_content() -> str:28 en_index = en_docs_path / "docs" / "index.md"29 content = en_index.read_text("utf-8")30 match_pre = re.search(r"</style>\n\n", content)31 if not match_pre:32 raise RuntimeError("Couldn't find pre section (<style>) in index.md")33 frontmatter_end = match_pre.end()34 new_content = content[frontmatter_end:]35 # Remove content between <!-- only-mkdocs --> and <!-- /only-mkdocs -->36 new_content = re.sub(37 r"<!-- only-mkdocs -->.*?<!-- /only-mkdocs -->",38 "",39 new_content,40 flags=re.DOTALL,41 )42 return new_content434445@app.command()46def generate_readme() -> None:47 """48 Generate README.md content from main index.md49 """50 typer.echo("Generating README")51 readme_path = Path("README.md")52 new_content = generate_readme_content()53 readme_path.write_text(new_content, encoding="utf-8")545556@app.command()57def verify_readme() -> None:58 """59 Verify README.md content from main index.md60 """61 typer.echo("Verifying README")62 readme_path = Path("README.md")63 generated_content = generate_readme_content()64 readme_content = readme_path.read_text("utf-8")65 if generated_content != readme_content:66 typer.secho(67 "README.md outdated from the latest index.md", color=typer.colors.RED68 )69 raise typer.Abort()70 typer.echo("Valid README ✅")717273@app.command()74def live(dirty: bool = False) -> None:75 """76 Serve with livereload a docs site for a specific language.7778 This only shows the actual translated files, not the placeholders created with79 build-all.8081 Takes an optional LANG argument with the name of the language to serve, by default82 en.83 """84 # Enable line numbers during local development to make it easier to highlight

⬆️ Migrate to Zensical (#1470)Sebastián Ramírezbefore adoptionf655ef2

line 85why, one step back
85 args = ["zensical", "serve", "--dev-addr", "127.0.0.1:8008"]

⬆ Bump pydantic from 2.13.1 to 2.13.2 (#1703)dependabot[bot]before adoption2c8a54c

lines 86–96why, one step back
86 if dirty:
87 args.append("--dirty")88 subprocess.run(args, env={**os.environ, "LINENUMS": "true"}, check=True)899091@app.command()92def build() -> None:93 """94 Build the docs.95 """96 print("Building docs")

⬆️ Migrate to Zensical (#1470)Sebastián Ramírezbefore adoptionf655ef2

line 97why, one step back
97 subprocess.run(["zensical", "build"], check=True)

⬆ Bump pydantic from 2.13.1 to 2.13.2 (#1703)dependabot[bot]before adoption2c8a54c

lines 98–105why, one step back
98 typer.secho("Successfully built docs", color=typer.colors.GREEN)
99100101@app.command()102def serve() -> None:103 """104 A quick server to preview a built site.105

⬆️ Migrate to Zensical (#1470)Sebastián Ramírezbefore adoptionf655ef2

line 106why, one step back
106 For development, prefer the command live (or just zensical serve).

⬆ Bump pydantic from 2.13.1 to 2.13.2 (#1703)dependabot[bot]before adoption2c8a54c

lines 107–362why, one step back
107
108 This is here only to preview the documentation site.109110 Make sure you run the build command first.111 """112 typer.echo("Warning: this is a very simple server.")113 typer.echo("For development, use the command live instead.")114 typer.echo("This is here only to preview the documentation site.")115 typer.echo("Make sure you run the build command first.")116 os.chdir("site")117 server_address = ("", 8008)118 server = HTTPServer(server_address, SimpleHTTPRequestHandler)119 typer.echo("Serving at: http://127.0.0.1:8008")120 server.serve_forever()121122123@app.command()124def generate_docs_src_versions_for_file(file_path: Path) -> None:125 target_versions = ["py39", "py310"]126 full_path_str = str(file_path)127 for target_version in target_versions:128 if f"_{target_version}" in full_path_str:129 logging.info(130 f"Skipping {file_path}, already a version file for {target_version}"131 )132 return133 base_content = file_path.read_text(encoding="utf-8")134 previous_content = {base_content}135 for target_version in target_versions:136 version_result = subprocess.run(137 [138 find_ruff_bin(),139 "check",140 "--target-version",141 target_version,142 "--fix",143 "--unsafe-fixes",144 "-",145 ],146 input=base_content.encode("utf-8"),147 capture_output=True,148 )149 content_target = version_result.stdout.decode("utf-8")150 format_result = subprocess.run(151 [find_ruff_bin(), "format", "-"],152 input=content_target.encode("utf-8"),153 capture_output=True,154 )155 content_format = format_result.stdout.decode("utf-8")156 if content_format in previous_content:157 continue158 previous_content.add(content_format)159 # Determine where the version label should go: in the parent directory160 # name or in the file name, matching the source structure.161 label_in_parent = False162 for v in target_versions:163 if f"_{v}" in file_path.parent.name:164 label_in_parent = True165 break166 if label_in_parent:167 parent_name = file_path.parent.name168 for v in target_versions:169 parent_name = parent_name.replace(f"_{v}", "")170 new_parent = file_path.parent.parent / f"{parent_name}_{target_version}"171 new_parent.mkdir(parents=True, exist_ok=True)172 version_file = new_parent / file_path.name173 else:174 base_name = file_path.stem175 for v in target_versions:176 if base_name.endswith(f"_{v}"):177 base_name = base_name[: -len(f"_{v}")]178 break179 version_file = file_path.with_name(f"{base_name}_{target_version}.py")180 logging.info(f"Writing to {version_file}")181 version_file.write_text(content_format, encoding="utf-8")182183184@app.command()185def generate_docs_src_versions() -> None:186 """187 Generate Python version-specific files for all .py files in docs_src.188 """189 docs_src_path = Path("docs_src")190 for py_file in sorted(docs_src_path.rglob("*.py")):191 generate_docs_src_versions_for_file(py_file)192193194@app.command()195def copy_py39_to_py310() -> None:196 """197 For each docs_src file/directory with a _py39 label that has no _py310198 counterpart, copy it with the _py310 label.199 """200 docs_src_path = Path("docs_src")201 # Handle directory-level labels (e.g. app_b_an_py39/)202 for dir_path in sorted(docs_src_path.rglob("*_py39")):203 if not dir_path.is_dir():204 continue205 py310_dir = dir_path.parent / dir_path.name.replace("_py39", "_py310")206 if py310_dir.exists():207 continue208 logging.info(f"Copying directory {dir_path} -> {py310_dir}")209 shutil.copytree(dir_path, py310_dir)210 # Handle file-level labels (e.g. tutorial001_py39.py)211 for file_path in sorted(docs_src_path.rglob("*_py39.py")):212 if not file_path.is_file():213 continue214 # Skip files inside _py39 directories (already handled above)215 if "_py39" in file_path.parent.name:216 continue217 py310_file = file_path.with_name(218 file_path.name.replace("_py39.py", "_py310.py")219 )220 if py310_file.exists():221 continue222 logging.info(f"Copying file {file_path} -> {py310_file}")223 shutil.copy2(file_path, py310_file)224225226@app.command()227def update_docs_includes_py39_to_py310() -> None:228 """229 Update .md files in docs/en/ to replace _py39 includes with _py310 versions.230231 For each include line referencing a _py39 file or directory in docs_src, replace232 the _py39 label with _py310.233 """234 include_pattern = re.compile(r"\{[^}]*docs_src/[^}]*_py39[^}]*\.py[^}]*\}")235 count = 0236 for md_file in sorted(en_docs_path.rglob("*.md")):237 content = md_file.read_text(encoding="utf-8")238 if "_py39" not in content:239 continue240 new_content = include_pattern.sub(241 lambda m: m.group(0).replace("_py39", "_py310"), content242 )243 if new_content != content:244 md_file.write_text(new_content, encoding="utf-8")245 count += 1246 logging.info(f"Updated includes in {md_file}")247 print(f"Updated {count} file(s) ✅")248249250@app.command()251def remove_unused_docs_src() -> None:252 """253 Delete .py files in docs_src that are not included in any .md file under docs/.254 """255 docs_src_path = Path("docs_src")256 # Collect all docs .md content referencing docs_src257 all_docs_content = ""258 for md_file in docs_path.rglob("*.md"):259 all_docs_content += md_file.read_text(encoding="utf-8")260 # Build a set of directory-based package roots (e.g. docs_src/bigger_applications/app_py39)261 # where at least one file is referenced in docs. All files in these directories262 # should be kept since they may be internally imported by the referenced files.263 used_package_dirs: set[Path] = set()264 for py_file in docs_src_path.rglob("*.py"):265 if py_file.name == "__init__.py":266 continue267 rel_path = str(py_file)268 if rel_path in all_docs_content:269 # Walk up from the file's parent to find the package root270 # (a subdirectory under docs_src/<topic>/)271 parts = py_file.relative_to(docs_src_path).parts272 if len(parts) > 2 and not py_file.name.startswith("tutorial"):273 # File is inside a sub-package like docs_src/topic/app_xxx/...274 # but not a standalone tutorial file in a topic subdirectory275 package_root = docs_src_path / parts[0] / parts[1]276 used_package_dirs.add(package_root)277 removed = 0278 for py_file in sorted(docs_src_path.rglob("*.py")):279 if py_file.name == "__init__.py":280 continue281 # Build the relative path as it appears in includes (e.g. docs_src/first_steps/tutorial001.py)282 rel_path = str(py_file)283 if rel_path in all_docs_content:284 continue285 # If this file is inside a directory-based package where any sibling is286 # referenced, keep it (it's likely imported internally).287 parts = py_file.relative_to(docs_src_path).parts288 if len(parts) > 2:289 package_root = docs_src_path / parts[0] / parts[1]290 if package_root in used_package_dirs:291 continue292 # Check if the _an counterpart (or non-_an counterpart) is referenced.293 # If either variant is included, keep both.294 # Handle both file-level _an (tutorial001_an.py) and directory-level _an295 # (app_an/main.py)296 counterpart_found = False297 full_path_str = str(py_file)298 if "_an" in py_file.stem:299 # This is an _an file, check if the non-_an version is referenced300 counterpart = full_path_str.replace(301 f"/{py_file.stem}", f"/{py_file.stem.replace('_an', '', 1)}"302 )303 if counterpart in all_docs_content:304 counterpart_found = True305 else:306 # This is a non-_an file, check if there's an _an version referenced307 # Insert _an before any version suffix or at the end of the stem308 stem = py_file.stem309 for suffix in ("_py39", "_py310"):310 if suffix in stem:311 an_stem = stem.replace(suffix, f"_an{suffix}", 1)312 break313 else:314 an_stem = f"{stem}_an"315 counterpart = full_path_str.replace(f"/{stem}.", f"/{an_stem}.")316 if counterpart in all_docs_content:317 counterpart_found = True318 # Also check directory-level _an counterparts319 if not counterpart_found:320 parent_name = py_file.parent.name321 if "_an" in parent_name:322 counterpart_parent = parent_name.replace("_an", "", 1)323 counterpart_dir = str(py_file).replace(324 f"/{parent_name}/", f"/{counterpart_parent}/"325 )326 if counterpart_dir in all_docs_content:327 counterpart_found = True328 else:329 # Try inserting _an into parent directory name330 for suffix in ("_py39", "_py310"):331 if suffix in parent_name:332 an_parent = parent_name.replace(suffix, f"_an{suffix}", 1)333 break334 else:335 an_parent = f"{parent_name}_an"336 counterpart_dir = str(py_file).replace(337 f"/{parent_name}/", f"/{an_parent}/"338 )339 if counterpart_dir in all_docs_content:340 counterpart_found = True341 if counterpart_found:342 continue343 logging.info(f"Removing unused file: {py_file}")344 py_file.unlink()345 removed += 1346 # Clean up directories that are empty or only contain __init__.py / __pycache__347 for dir_path in sorted(docs_src_path.rglob("*"), reverse=True):348 if not dir_path.is_dir():349 continue350 remaining = [351 f352 for f in dir_path.iterdir()353 if f.name != "__pycache__" and f.name != "__init__.py"354 ]355 if not remaining:356 logging.info(f"Removing empty/init-only directory: {dir_path}")357 shutil.rmtree(dir_path)358 print(f"Removed {removed} unused file(s) ✅")359360361if __name__ == "__main__":362 app()