🔨 Add internal scripts to migrate docs from Python 3.9 to 3.10 (#1547)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sebastián Ramírez · committed by GitHub · parent 570fd02 · Browse files · 1 file·+207 added−3 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+207 added−3 removed
- other:+207 added−3 removed
Provenance
- Commit
52ec007- Tree
79d0007- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
570fd02
1 file changed+207 added−3 removed
modified:scripts/docs.py+207 added-3 removed
1 import logging2 import os3 import re4+import shutil5 import subprocess6 from http.server import HTTPServer, SimpleHTTPRequestHandler7 from pathlib import Path8 2 unmodified lines11 12 logging.basicConfig(level=logging.INFO)13 14 mkdocs_name = "mkdocs.yml"15+docs_path = Path("docs")16 en_docs_path = Path("")17 18 app = typer.Typer()19 102 unmodified lines122 123 @app.command()124 def 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(18 unmodified lines155 content_format = format_result.stdout.decode("utf-8")156 if content_format in previous_content:157 continue158 previous_content.add(content_format)150- version_file = file_path.with_name(151- file_path.name.replace(".py", f"_{target_version}.py")152- )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")182 183 184+@app.command()185+def 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)192+193+194+@app.command()195+def 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)224+225+226+@app.command()227+def update_docs_includes_py39_to_py310() -> None:228+ """229+ Update .md files in docs/en/ to replace _py39 includes with _py310 versions.230+231+ 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) ✅")248+249+250+@app.command()251+def 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) ✅")359+360+361 if __name__ == "__main__":362 app()