scripts/docs.py PYTHON 920 lines View on github.com → Search inside
1import json2import logging3import os4import re5import shutil6import subprocess7from html.parser import HTMLParser8from http.server import HTTPServer, SimpleHTTPRequestHandler9from multiprocessing import Pool10from pathlib import Path11from typing import Any1213import typer14import yaml15from jinja2 import Template16from ruff.__main__ import find_ruff_bin17from slugify import slugify as py_slugify1819logging.basicConfig(level=logging.INFO)2021SUPPORTED_LANGS = {22    "de",23    "en",24    "es",25    "fr",26    "ja",27    "ko",28    "pt",29    "ru",30    "tr",31    "uk",32    "zh",33    "zh-hant",34    "hi",35}363738app = typer.Typer()3940mkdocs_name = "mkdocs.yml"4142non_translated_sections = (43    f"reference{os.sep}",44    "release-notes.md",45    "fastapi-people.md",46    "external-links.md",47    "newsletter.md",48    "management-tasks.md",49    "management.md",50    "contributing.md",51    "translations.md",52)5354docs_path = Path("docs")55en_docs_path = Path("docs/en")56en_config_path: Path = en_docs_path / mkdocs_name57site_path = Path("site").absolute()58zensical_src_path = Path("site_zensical_src").absolute()5960header_pattern = re.compile(r"^(#{1,6}) (.+?)(?:\s*\{\s*(#.*)\s*\})?\s*$")61header_with_permalink_pattern = re.compile(r"^(#{1,6}) (.+?)(\s*\{\s*#.*\s*\})\s*$")62code_block3_pattern = re.compile(r"^\s*```")63code_block4_pattern = re.compile(r"^\s*````")646566# Pattern to match markdown links: [text](url) → text67md_link_pattern = re.compile(r"\[([^\]]+)\]\([^)]+\)")686970def strip_markdown_links(text: str) -> str:71    """Replace markdown links with just their visible text."""72    return md_link_pattern.sub(r"\1", text)737475class VisibleTextExtractor(HTMLParser):76    """Extract visible text from a string with HTML tags."""7778    def __init__(self):79        super().__init__()80        self.text_parts = []8182    def handle_data(self, data):83        self.text_parts.append(data)8485    def extract_visible_text(self, html: str) -> str:86        self.reset()87        self.text_parts = []88        self.feed(html)89        return "".join(self.text_parts).strip()909192def slugify(text: str) -> str:93    return py_slugify(94        text,95        replacements=[96            ("`", ""),  # `dict`s -> dicts97            ("'s", "s"),  # it's -> its98            ("'t", "t"),  # don't -> dont99            ("**", ""),  # **FastAPI**s -> FastAPIs100        ],101    )102103104def get_en_config() -> dict[str, Any]:105    return yaml.unsafe_load(en_config_path.read_text(encoding="utf-8"))106107108def get_lang_paths() -> list[Path]:109    return sorted(docs_path.iterdir())110111112def lang_callback(lang: str | None) -> str | None:113    if lang is None:114        return None115    lang = lang.lower()116    return lang117118119def complete_existing_lang(incomplete: str):120    lang_path: Path121    for lang_path in get_lang_paths():122        if lang_path.is_dir() and lang_path.name.startswith(incomplete):123            yield lang_path.name124125126@app.callback()127def callback() -> None:128    # For MacOS with Cairo129    os.environ["DYLD_FALLBACK_LIBRARY_PATH"] = "/opt/homebrew/lib"130131132@app.command()133def new_lang(lang: str = typer.Argument(..., callback=lang_callback)):134    """135    Generate a new docs translation directory for the language LANG.136    """137    new_path: Path = Path("docs") / lang138    if new_path.exists():139        typer.echo(f"The language was already created: {lang}")140        raise typer.Abort()141    new_path.mkdir()142    new_llm_prompt_path: Path = new_path / "llm-prompt.md"143    new_llm_prompt_path.write_text("", encoding="utf-8")144    print(f"Successfully initialized: {new_path}")145    update_languages()146147148@app.command()149def build_lang(150    lang: str = typer.Argument(151        ..., callback=lang_callback, autocompletion=complete_existing_lang152    ),153) -> None:154    """155    Build the docs for a language.156    """157    build_zensical_lang_to_stage(lang)158    copy_zensical_stage_to_site(lang)159    typer.secho(f"Successfully built docs for: {lang}", fg=typer.colors.GREEN)160161162def split_markdown_header(markdown: str) -> tuple[str, str]:163    prefix = ""164    if markdown.startswith("---\n"):165        front_matter_end = markdown.find("\n---\n", 4)166        if front_matter_end != -1:167            front_matter_end += len("\n---\n")168            prefix = markdown[:front_matter_end]169            markdown = markdown[front_matter_end:]170    if markdown.startswith("#"):171        header, separator, body = markdown.partition("\n\n")172        if separator:173            return f"{prefix}{header}", body174    if prefix:175        return prefix.rstrip("\n"), markdown176    return "", markdown177178179def add_markdown_notice(markdown: str, notice: str) -> str:180    header, body = split_markdown_header(markdown)181    if header:182        return f"{header}\n\n{notice}\n\n{body}"183    return f"{notice}\n\n{body}"184185186def is_non_translated_path(path: Path) -> bool:187    src_path = path.as_posix()188    return any(src_path.startswith(section) for section in non_translated_sections)189190191def get_en_url(path: Path) -> str:192    url_path = path.with_suffix("").as_posix()193    if url_path.endswith("/index"):194        url_path = url_path.removesuffix("index")195    elif url_path != "index":196        url_path = f"{url_path}/"197    else:198        url_path = ""199    return f"https://fastapi.tiangolo.com/{url_path}"200201202def get_zensical_theme_language(lang: str) -> str:203    if lang == "zh-hant":204        return "zh-Hant"205    return lang206207208def stage_zensical_docs(lang: str) -> Path:209    lang_docs_path = docs_path / lang / "docs"210    if not lang_docs_path.is_dir():211        typer.echo(f"The language translation doesn't seem to exist yet: {lang}")212        raise typer.Abort()213214    en_docs_source_path = en_docs_path / "docs"215    staged_docs_src_path = zensical_src_path / "docs_src"216    if not staged_docs_src_path.exists():217        shutil.copytree(Path("docs_src"), staged_docs_src_path, dirs_exist_ok=True)218    lang_stage_path = zensical_src_path / lang219    staged_docs_path = lang_stage_path / "content"220    shutil.rmtree(lang_stage_path, ignore_errors=True)221    shutil.copytree(en_docs_source_path, staged_docs_path)222223    missing_translation = (docs_path / "missing-translation.md").read_text(224        encoding="utf-8"225    )226    translation_banner_path = lang_docs_path / "translation-banner.md"227    if not translation_banner_path.is_file():228        translation_banner_path = en_docs_source_path / "translation-banner.md"229    translation_banner = translation_banner_path.read_text(encoding="utf-8")230231    if lang != "en":232        for staged_file in staged_docs_path.rglob("*.md"):233            relative_path = staged_file.relative_to(staged_docs_path)234            translated_file = lang_docs_path / relative_path235            if translated_file.is_file():236                markdown = translated_file.read_text(encoding="utf-8")237                if relative_path.name == "translation-banner.md":238                    staged_file.write_text(markdown, encoding="utf-8")239                    continue240                en_url = get_en_url(relative_path)241                banner = translation_banner.replace("ENGLISH_VERSION_URL", en_url)242                staged_file.write_text(243                    add_markdown_notice(markdown, banner), encoding="utf-8"244                )245            elif not is_non_translated_path(relative_path):246                markdown = staged_file.read_text(encoding="utf-8")247                staged_file.write_text(248                    add_markdown_notice(markdown, missing_translation),249                    encoding="utf-8",250                )251252    render_banner_sponsors()253    shutil.copytree(en_docs_path / "data", lang_stage_path / "data")254    shutil.copytree(en_docs_path / "overrides", lang_stage_path / "overrides")255256    config = get_updated_config_content()257    config["docs_dir"] = "content"258    config["site_dir"] = "site"259    if lang == "en":260        config["site_url"] = "https://fastapi.tiangolo.com/"261    else:262        config["site_url"] = f"https://fastapi.tiangolo.com/{lang}/"263    config.setdefault("theme", {})264    config["theme"]["language"] = get_zensical_theme_language(lang)265    if lang != "en":266        # The root English build owns shared static assets; translated builds should267        # reference those root paths instead of emitting language-local copies.268        if "logo" in config["theme"]:269            config["theme"]["logo"] = "/" + config["theme"]["logo"].lstrip("/")270        if "favicon" in config["theme"]:271            config["theme"]["favicon"] = "/" + config["theme"]["favicon"].lstrip("/")272        config["extra_css"] = ["/" + path.lstrip("/") for path in config["extra_css"]]273        config["extra_javascript"] = [274            "/" + path.lstrip("/") for path in config["extra_javascript"]275        ]276    config_path = lang_stage_path / mkdocs_name277    config_path.write_text(278        yaml.dump(config, sort_keys=False, width=200, allow_unicode=True),279        encoding="utf-8",280    )281    return config_path282283284def build_zensical_config(config_path: Path) -> None:285    subprocess.run(286        ["zensical", "build", "--config-file", config_path.name],287        check=True,288        cwd=config_path.parent,289    )290291292def build_zensical_lang_to_stage(lang: str) -> Path:293    typer.echo(f"Building Zensical docs for: {lang}")294    config_path = stage_zensical_docs(lang)295    config = yaml.unsafe_load(config_path.read_text(encoding="utf-8"))296    build_site_dist_path = config_path.parent / config["site_dir"]297    shutil.rmtree(build_site_dist_path, ignore_errors=True)298    build_zensical_config(config_path)299    return build_site_dist_path300301302def copy_zensical_stage_to_site(lang: str) -> None:303    build_site_dist_path = zensical_src_path / lang / "site"304    if lang == "en":305        dist_path = site_path306    else:307        dist_path = site_path / lang308        shutil.rmtree(dist_path, ignore_errors=True)309    shutil.copytree(build_site_dist_path, dist_path, dirs_exist_ok=True)310311312index_sponsors_template = """313### Keystone Sponsor314315{% for sponsor in sponsors.keystone -%}316<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor_img_url(sponsor.img) }}"></a>317{% endfor %}318### Gold Sponsors319320{% for sponsor in sponsors.gold -%}321<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor_img_url(sponsor.img) }}"></a>322{% endfor %}323### Silver Sponsors324325{% for sponsor in sponsors.silver -%}326<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor_img_url(sponsor.img) }}"></a>327{% endfor %}328329"""330331332def sponsor_img_url(img: str) -> str:333    return f"https://fastapi.tiangolo.com{img}"334335336def remove_header_permalinks(content: str):337    lines: list[str] = []338    for line in content.split("\n"):339        match = header_with_permalink_pattern.match(line)340        if match:341            hashes, title, *_ = match.groups()342            line = f"{hashes} {title}"343        lines.append(line)344    return "\n".join(lines)345346347def generate_readme_content() -> str:348    en_index = en_docs_path / "docs" / "index.md"349    content = en_index.read_text("utf-8")350    content = remove_header_permalinks(content)  # remove permalinks from headers351    match_pre = re.search(r"</style>\n\n", content)352    match_start = re.search(r"<!-- sponsors -->", content)353    match_end = re.search(r"<!-- /sponsors -->", content)354    sponsors_data_path = en_docs_path / "data" / "sponsors.yml"355    sponsors = yaml.safe_load(sponsors_data_path.read_text(encoding="utf-8"))356    if not (match_start and match_end):357        raise RuntimeError("Couldn't auto-generate sponsors section")358    if not match_pre:359        raise RuntimeError("Couldn't find pre section (<style>) in index.md")360    frontmatter_end = match_pre.end()361    pre_end = match_start.end()362    post_start = match_end.start()363    template = Template(index_sponsors_template)364    message = template.render(sponsors=sponsors, sponsor_img_url=sponsor_img_url)365    pre_content = content[frontmatter_end:pre_end]366    post_content = content[post_start:]367    new_content = pre_content + message + post_content368    # Remove content between <!-- only-mkdocs --> and <!-- /only-mkdocs -->369    new_content = re.sub(370        r"<!-- only-mkdocs -->.*?<!-- /only-mkdocs -->",371        "",372        new_content,373        flags=re.DOTALL,374    )375    return new_content376377378@app.command()379def generate_readme() -> None:380    """381    Generate README.md content from main index.md382    """383    readme_path = Path("README.md")384    old_content = readme_path.read_text("utf-8")385    new_content = generate_readme_content()386    if new_content != old_content:387        print("README.md outdated from the latest index.md")388        print("Updating README.md")389        readme_path.write_text(new_content, encoding="utf-8")390        raise typer.Exit(1)391    print("README.md is up to date ✅")392393394@app.command()395def build_all() -> None:396    """397    Build the full translated docs site into ./site/.398    """399    update_languages()400    shutil.rmtree(site_path, ignore_errors=True)401    shutil.rmtree(zensical_src_path, ignore_errors=True)402    shutil.copytree(Path("docs_src"), zensical_src_path / "docs_src")403    langs = [404        lang.name405        for lang in get_lang_paths()406        if (lang.is_dir() and lang.name in SUPPORTED_LANGS)407    ]408    process_pool_size = min(4, len(langs), os.cpu_count() or 1)409    typer.echo(f"Using process pool size: {process_pool_size}")410    with Pool(process_pool_size) as p:411        p.map(build_zensical_lang_to_stage, langs)412    if "en" in langs:413        copy_zensical_stage_to_site("en")414    for lang in langs:415        if lang != "en":416            copy_zensical_stage_to_site(lang)417    typer.secho("Successfully built all docs", fg=typer.colors.GREEN)418419420@app.command()421def update_languages() -> None:422    """423    Update the docs config Languages section including all the available languages.424    """425    old_config = get_en_config()426    updated_config = get_updated_config_content()427    if old_config != updated_config:428        print("docs/en/mkdocs.yml outdated")429        print("Updating docs/en/mkdocs.yml")430        en_config_path.write_text(431            yaml.dump(updated_config, sort_keys=False, width=200, allow_unicode=True),432            encoding="utf-8",433        )434        raise typer.Exit(1)435    print("docs/en/mkdocs.yml is up to date ✅")436437438@app.command()439def serve() -> None:440    """441    A quick server to preview a built site with translations.442443    For development, prefer the command live.444445    This is here only to preview a site with translations already built.446447    Make sure you run the build-all command first.448    """449    typer.echo("Warning: this is a very simple server.")450    typer.echo("For development, use the command live instead.")451    typer.echo("This is here only to preview a site with translations already built.")452    typer.echo("Make sure you run the build-all command first.")453    os.chdir("site")454    server_address = ("", 8008)455    server = HTTPServer(server_address, SimpleHTTPRequestHandler)456    typer.echo("Serving at: http://127.0.0.1:8008")457    server.serve_forever()458459460@app.command()461def live() -> None:462    """463    Serve the English docs with livereload from the source files.464    """465    render_banner_sponsors()466    subprocess.run(467        [468            "zensical",469            "serve",470            "--config-file",471            mkdocs_name,472            "--dev-addr",473            "127.0.0.1:8008",474        ],475        cwd=en_docs_path,476        check=True,477    )478479480def get_updated_config_content() -> dict[str, Any]:481    config = get_en_config()482    languages = [{"en": "/"}]483    new_alternate: list[dict[str, str]] = []484    # Language names sourced from https://quickref.me/iso-639-1485    # Contributors may wish to update or change these, e.g. to fix capitalization.486    language_names_path = Path(__file__).parent / "../docs/language_names.yml"487    local_language_names: dict[str, str] = yaml.safe_load(488        language_names_path.read_text(encoding="utf-8")489    )490    for lang_path in get_lang_paths():491        if lang_path.name in {"en", "em"} or not lang_path.is_dir():492            continue493        if lang_path.name not in SUPPORTED_LANGS:494            # Skip languages that are not yet ready495            continue496        code = lang_path.name497        languages.append({code: f"/{code}/"})498    for lang_dict in languages:499        code = list(lang_dict.keys())[0]500        url = lang_dict[code]501        if code not in local_language_names:502            print(503                f"Missing language name for: {code}, "504                "update it in docs/language_names.yml"505            )506            raise typer.Abort()507        use_name = f"{code} - {local_language_names[code]}"508        new_alternate.append({"link": url, "name": use_name})509    config["extra"]["alternate"] = new_alternate510    return config511512513banner_sponsors_template = """{% for sponsor in banner_sponsors -%}514<div class="item">515  <a title="{{ sponsor.title }}" style="display: block; position: relative;" href="{{ sponsor.url }}" target="_blank">516    <span class="sponsor-badge">sponsor</span>517    <img class="sponsor-image" src="{{ sponsor.img }}" alt="{{ sponsor.title }}" />518  </a>519</div>520{% endfor %}521"""522523524def get_banner_sponsors(sponsors: dict[str, Any]) -> list[dict[str, str]]:525    banner_sponsors: list[dict[str, str]] = []526    for sponsor in sponsors.get("gold", []):527        banner_img = sponsor.get("banner_img")528        if not banner_img:529            continue530        banner_sponsors.append(531            {532                "url": sponsor.get("banner_url", sponsor["url"]),533                "title": sponsor.get("banner_title", sponsor["title"]),534                "img": banner_img,535            }536        )537    return banner_sponsors538539540def render_banner_sponsors_partial() -> str:541    sponsors_path = en_docs_path / "data" / "sponsors.yml"542    sponsors = yaml.safe_load(sponsors_path.read_text(encoding="utf-8"))543    template = Template(banner_sponsors_template)544    return template.render(banner_sponsors=get_banner_sponsors(sponsors))545546547@app.command()548def render_banner_sponsors() -> None:549    """550    Render the sponsor banner partial from sponsors.yml.551    """552    partial_path = en_docs_path / "overrides" / "partials" / "banner-sponsors.html"553    old_content = partial_path.read_text("utf-8") if partial_path.is_file() else ""554    new_content = render_banner_sponsors_partial()555    if new_content != old_content:556        print(f"{partial_path} outdated from the latest sponsors.yml")557        print(f"Updating {partial_path}")558        partial_path.write_text(new_content, encoding="utf-8")559        raise typer.Exit(1)560    print(f"{partial_path} is up to date ✅")561562563@app.command()564def ensure_non_translated() -> None:565    """566    Ensure there are no files in the non translatable pages.567    """568    print("Ensuring no non translated pages")569    lang_paths = get_lang_paths()570    error_paths = []571    for lang in lang_paths:572        if lang.name == "en":573            continue574        for non_translatable in non_translated_sections:575            non_translatable_path = lang / "docs" / non_translatable576            if non_translatable_path.exists():577                error_paths.append(non_translatable_path)578    if error_paths:579        print("Non-translated pages found, removing them:")580        for error_path in error_paths:581            print(error_path)582            if error_path.is_file():583                error_path.unlink()584            else:585                shutil.rmtree(error_path)586        raise typer.Exit(1)587    print("No non-translated pages found ✅")588589590@app.command()591def langs_json():592    langs = []593    for lang_path in get_lang_paths():594        if lang_path.is_dir() and lang_path.name in SUPPORTED_LANGS:595            langs.append(lang_path.name)596    print(json.dumps(langs))597598599@app.command()600def generate_docs_src_versions_for_file(file_path: Path) -> None:601    target_versions = ["py39", "py310"]602    full_path_str = str(file_path)603    for target_version in target_versions:604        if f"_{target_version}" in full_path_str:605            logging.info(606                f"Skipping {file_path}, already a version file for {target_version}"607            )608            return609    base_content = file_path.read_text(encoding="utf-8")610    previous_content = {base_content}611    for target_version in target_versions:612        version_result = subprocess.run(613            [614                find_ruff_bin(),615                "check",616                "--target-version",617                target_version,618                "--fix",619                "--unsafe-fixes",620                "-",621            ],622            input=base_content.encode("utf-8"),623            capture_output=True,624        )625        content_target = version_result.stdout.decode("utf-8")626        format_result = subprocess.run(627            [find_ruff_bin(), "format", "-"],628            input=content_target.encode("utf-8"),629            capture_output=True,630        )631        content_format = format_result.stdout.decode("utf-8")632        if content_format in previous_content:633            continue634        previous_content.add(content_format)635        # Determine where the version label should go: in the parent directory636        # name or in the file name, matching the source structure.637        label_in_parent = False638        for v in target_versions:639            if f"_{v}" in file_path.parent.name:640                label_in_parent = True641                break642        if label_in_parent:643            parent_name = file_path.parent.name644            for v in target_versions:645                parent_name = parent_name.replace(f"_{v}", "")646            new_parent = file_path.parent.parent / f"{parent_name}_{target_version}"647            new_parent.mkdir(parents=True, exist_ok=True)648            version_file = new_parent / file_path.name649        else:650            base_name = file_path.stem651            for v in target_versions:652                if base_name.endswith(f"_{v}"):653                    base_name = base_name[: -len(f"_{v}")]654                    break655            version_file = file_path.with_name(f"{base_name}_{target_version}.py")656        logging.info(f"Writing to {version_file}")657        version_file.write_text(content_format, encoding="utf-8")658659660@app.command()661def generate_docs_src_versions() -> None:662    """663    Generate Python version-specific files for all .py files in docs_src.664    """665    docs_src_path = Path("docs_src")666    for py_file in sorted(docs_src_path.rglob("*.py")):667        generate_docs_src_versions_for_file(py_file)668669670@app.command()671def copy_py39_to_py310() -> None:672    """673    For each docs_src file/directory with a _py39 label that has no _py310674    counterpart, copy it with the _py310 label.675    """676    docs_src_path = Path("docs_src")677    # Handle directory-level labels (e.g. app_b_an_py39/)678    for dir_path in sorted(docs_src_path.rglob("*_py39")):679        if not dir_path.is_dir():680            continue681        py310_dir = dir_path.parent / dir_path.name.replace("_py39", "_py310")682        if py310_dir.exists():683            continue684        logging.info(f"Copying directory {dir_path} -> {py310_dir}")685        shutil.copytree(dir_path, py310_dir)686    # Handle file-level labels (e.g. tutorial001_py39.py)687    for file_path in sorted(docs_src_path.rglob("*_py39.py")):688        if not file_path.is_file():689            continue690        # Skip files inside _py39 directories (already handled above)691        if "_py39" in file_path.parent.name:692            continue693        py310_file = file_path.with_name(694            file_path.name.replace("_py39.py", "_py310.py")695        )696        if py310_file.exists():697            continue698        logging.info(f"Copying file {file_path} -> {py310_file}")699        shutil.copy2(file_path, py310_file)700701702@app.command()703def update_docs_includes_py39_to_py310() -> None:704    """705    Update .md files in docs/en/ to replace _py39 includes with _py310 versions.706707    For each include line referencing a _py39 file or directory in docs_src, replace708    the _py39 label with _py310.709    """710    include_pattern = re.compile(r"\{[^}]*docs_src/[^}]*_py39[^}]*\.py[^}]*\}")711    count = 0712    for md_file in sorted(en_docs_path.rglob("*.md")):713        content = md_file.read_text(encoding="utf-8")714        if "_py39" not in content:715            continue716        new_content = include_pattern.sub(717            lambda m: m.group(0).replace("_py39", "_py310"), content718        )719        if new_content != content:720            md_file.write_text(new_content, encoding="utf-8")721            count += 1722            logging.info(f"Updated includes in {md_file}")723    print(f"Updated {count} file(s) ✅")724725726@app.command()727def remove_unused_docs_src() -> None:728    """729    Delete .py files in docs_src that are not included in any .md file under docs/.730    """731    docs_src_path = Path("docs_src")732    # Collect all docs .md content referencing docs_src733    all_docs_content = ""734    for md_file in docs_path.rglob("*.md"):735        all_docs_content += md_file.read_text(encoding="utf-8")736    # Build a set of directory-based package roots (e.g. docs_src/bigger_applications/app_py39)737    # where at least one file is referenced in docs. All files in these directories738    # should be kept since they may be internally imported by the referenced files.739    used_package_dirs: set[Path] = set()740    for py_file in docs_src_path.rglob("*.py"):741        if py_file.name == "__init__.py":742            continue743        rel_path = str(py_file)744        if rel_path in all_docs_content:745            # Walk up from the file's parent to find the package root746            # (a subdirectory under docs_src/<topic>/)747            parts = py_file.relative_to(docs_src_path).parts748            if len(parts) > 2:749                # File is inside a sub-package like docs_src/topic/app_xxx/...750                package_root = docs_src_path / parts[0] / parts[1]751                used_package_dirs.add(package_root)752    removed = 0753    for py_file in sorted(docs_src_path.rglob("*.py")):754        if py_file.name == "__init__.py":755            continue756        # Build the relative path as it appears in includes (e.g. docs_src/first_steps/tutorial001.py)757        rel_path = str(py_file)758        if rel_path in all_docs_content:759            continue760        # If this file is inside a directory-based package where any sibling is761        # referenced, keep it (it's likely imported internally).762        parts = py_file.relative_to(docs_src_path).parts763        if len(parts) > 2:764            package_root = docs_src_path / parts[0] / parts[1]765            if package_root in used_package_dirs:766                continue767        # Check if the _an counterpart (or non-_an counterpart) is referenced.768        # If either variant is included, keep both.769        # Handle both file-level _an (tutorial001_an.py) and directory-level _an770        # (app_an/main.py)771        counterpart_found = False772        full_path_str = str(py_file)773        if "_an" in py_file.stem:774            # This is an _an file, check if the non-_an version is referenced775            counterpart = full_path_str.replace(776                f"/{py_file.stem}", f"/{py_file.stem.replace('_an', '', 1)}"777            )778            if counterpart in all_docs_content:779                counterpart_found = True780        else:781            # This is a non-_an file, check if there's an _an version referenced782            # Insert _an before any version suffix or at the end of the stem783            stem = py_file.stem784            for suffix in ("_py39", "_py310"):785                if suffix in stem:786                    an_stem = stem.replace(suffix, f"_an{suffix}", 1)787                    break788            else:789                an_stem = f"{stem}_an"790            counterpart = full_path_str.replace(f"/{stem}.", f"/{an_stem}.")791            if counterpart in all_docs_content:792                counterpart_found = True793        # Also check directory-level _an counterparts794        if not counterpart_found:795            parent_name = py_file.parent.name796            if "_an" in parent_name:797                counterpart_parent = parent_name.replace("_an", "", 1)798                counterpart_dir = str(py_file).replace(799                    f"/{parent_name}/", f"/{counterpart_parent}/"800                )801                if counterpart_dir in all_docs_content:802                    counterpart_found = True803            else:804                # Try inserting _an into parent directory name805                for suffix in ("_py39", "_py310"):806                    if suffix in parent_name:807                        an_parent = parent_name.replace(suffix, f"_an{suffix}", 1)808                        break809                else:810                    an_parent = f"{parent_name}_an"811                counterpart_dir = str(py_file).replace(812                    f"/{parent_name}/", f"/{an_parent}/"813                )814                if counterpart_dir in all_docs_content:815                    counterpart_found = True816        if counterpart_found:817            continue818        logging.info(f"Removing unused file: {py_file}")819        py_file.unlink()820        removed += 1821    # Clean up directories that are empty or only contain __init__.py / __pycache__822    for dir_path in sorted(docs_src_path.rglob("*"), reverse=True):823        if not dir_path.is_dir():824            continue825        remaining = [826            f827            for f in dir_path.iterdir()828            if f.name != "__pycache__" and f.name != "__init__.py"829        ]830        if not remaining:831            logging.info(f"Removing empty/init-only directory: {dir_path}")832            shutil.rmtree(dir_path)833    print(f"Removed {removed} unused file(s) ✅")834835836@app.command()837def add_permalinks_page(path: Path, update_existing: bool = False):838    """839    Add or update header permalinks in specific page of En docs.840    """841842    if not path.is_relative_to(en_docs_path / "docs"):843        raise RuntimeError(f"Path must be inside {en_docs_path}")844    rel_path = path.relative_to(en_docs_path / "docs")845846    # Skip excluded sections847    if str(rel_path).startswith(non_translated_sections):848        return849850    visible_text_extractor = VisibleTextExtractor()851    updated_lines = []852    in_code_block3 = False853    in_code_block4 = False854    permalinks = set()855856    with path.open("r", encoding="utf-8") as f:857        lines = f.readlines()858859    for line in lines:860        # Handle codeblocks start and end861        if not (in_code_block3 or in_code_block4):862            if code_block4_pattern.match(line):863                in_code_block4 = True864            elif code_block3_pattern.match(line):865                in_code_block3 = True866        else:867            if in_code_block4 and code_block4_pattern.match(line):868                in_code_block4 = False869            elif in_code_block3 and code_block3_pattern.match(line):870                in_code_block3 = False871872        # Process Headers only outside codeblocks873        if not (in_code_block3 or in_code_block4):874            match = header_pattern.match(line)875            if match:876                hashes, title, _permalink = match.groups()877                if (not _permalink) or update_existing:878                    slug = slugify(879                        visible_text_extractor.extract_visible_text(880                            strip_markdown_links(title)881                        )882                    )883                    if slug in permalinks:884                        # If the slug is already used, append a number to make it unique885                        count = 1886                        original_slug = slug887                        while slug in permalinks:888                            slug = f"{original_slug}_{count}"889                            count += 1890                    permalinks.add(slug)891892                    line = f"{hashes} {title} {{ #{slug} }}\n"893894        updated_lines.append(line)895896    with path.open("w", encoding="utf-8") as f:897        f.writelines(updated_lines)898899900@app.command()901def add_permalinks_pages(pages: list[Path], update_existing: bool = False) -> None:902    """903    Add or update header permalinks in specific pages of En docs.904    """905    for md_file in pages:906        add_permalinks_page(md_file, update_existing=update_existing)907908909@app.command()910def add_permalinks(update_existing: bool = False) -> None:911    """912    Add or update header permalinks in all pages of En docs.913    """914    for md_file in en_docs_path.rglob("*.md"):915        add_permalinks_page(md_file, update_existing=update_existing)916917918if __name__ == "__main__":919    app()

Code quality findings 44

Ensure functions have docstrings for documentation
info maintainability missing-docstring
def handle_data(self, data):
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def extract_visible_text(self, html: str) -> str:
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def slugify(text: str) -> str:
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def get_en_config() -> dict[str, Any]:
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def get_lang_paths() -> list[Path]:
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def lang_callback(lang: str | None) -> str | None:
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def complete_existing_lang(incomplete: str):
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def callback() -> None:
Use logging module for better control and configurability
info maintainability print-statement
print(f"Successfully initialized: {new_path}")
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def split_markdown_header(markdown: str) -> tuple[str, str]:
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def add_markdown_notice(markdown: str, notice: str) -> str:
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def is_non_translated_path(path: Path) -> bool:
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def get_en_url(path: Path) -> str:
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def get_zensical_theme_language(lang: str) -> str:
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def stage_zensical_docs(lang: str) -> Path:
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def build_zensical_config(config_path: Path) -> None:
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def build_zensical_lang_to_stage(lang: str) -> Path:
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def copy_zensical_stage_to_site(lang: str) -> None:
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def sponsor_img_url(img: str) -> str:
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def remove_header_permalinks(content: str):
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def generate_readme_content() -> str:
Use logging module for better control and configurability
info maintainability print-statement
print("README.md outdated from the latest index.md")
Use logging module for better control and configurability
info maintainability print-statement
print("Updating README.md")
Use logging module for better control and configurability
info maintainability print-statement
print("README.md is up to date ✅")
Use logging module for better control and configurability
info maintainability print-statement
print("docs/en/mkdocs.yml outdated")
Use logging module for better control and configurability
info maintainability print-statement
print("Updating docs/en/mkdocs.yml")
Use logging module for better control and configurability
info maintainability print-statement
print("docs/en/mkdocs.yml is up to date ✅")
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def get_updated_config_content() -> dict[str, Any]:
Use logging module for better control and configurability
info maintainability print-statement
print(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def get_banner_sponsors(sponsors: dict[str, Any]) -> list[dict[str, str]]:
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def render_banner_sponsors_partial() -> str:
Use logging module for better control and configurability
info maintainability print-statement
print(f"{partial_path} outdated from the latest sponsors.yml")
Use logging module for better control and configurability
info maintainability print-statement
print(f"Updating {partial_path}")
Use logging module for better control and configurability
info maintainability print-statement
print(f"{partial_path} is up to date ✅")
Use logging module for better control and configurability
info maintainability print-statement
print("Ensuring no non translated pages")
Use logging module for better control and configurability
info maintainability print-statement
print("Non-translated pages found, removing them:")
Use logging module for better control and configurability
info maintainability print-statement
print(error_path)
Use logging module for better control and configurability
info maintainability print-statement
print("No non-translated pages found ✅")
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def langs_json():
Use logging module for better control and configurability
info maintainability print-statement
print(json.dumps(langs))
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def generate_docs_src_versions_for_file(file_path: Path) -> None:
Avoid complex 'lambda' functions; prefer named functions for clarity and debugging
info maintainability complex-lambda
lambda m: m.group(0).replace("_py39", "_py310"), content
Use logging module for better control and configurability
info maintainability print-statement
print(f"Updated {count} file(s) ✅")
Use logging module for better control and configurability
info maintainability print-statement
print(f"Removed {removed} unused file(s) ✅")

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.

Generated by searchcode.com · powered by code_get_file + code_get_findings