|
| 1 | +"""Script to automatically sort members lists in API reference markdown files.""" |
| 2 | +# ruff: noqa: T201 |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import re |
| 7 | +import sys |
| 8 | +from pathlib import Path |
| 9 | + |
| 10 | + |
| 11 | +def sort_members_in_markdown(file_path: Path) -> int: |
| 12 | + """Sort members lists in a markdown file alphabetically. |
| 13 | +
|
| 14 | + Returns: |
| 15 | + 1 if the file was modified, 0 if no changes were needed. |
| 16 | + """ |
| 17 | + content = file_path.read_text(encoding="utf-8") |
| 18 | + |
| 19 | + # Pattern matches "members:" followed by list items (lines starting with "- ") |
| 20 | + pattern = r"(members:)((?:\n\s+-[^\n]+)+)" |
| 21 | + |
| 22 | + def sort_list(match: re.Match[str]) -> str: |
| 23 | + """Sort a matched members list section.""" |
| 24 | + prefix = match.group(1) # "members:" |
| 25 | + items = match.group(2) # All list items with newlines and indentation |
| 26 | + |
| 27 | + item_pattern = r"(\n\s+-)([^\n]+)" # Extract individual items: (\n + spaces + -) and (content) |
| 28 | + matches = re.findall(item_pattern, items) |
| 29 | + |
| 30 | + # Sort alphabetically by the item content (excluding indentation and dash) |
| 31 | + sorted_items = sorted(matches, key=lambda x: x[1].strip()) |
| 32 | + |
| 33 | + # Reconstruct: "members:" + sorted items with their indentation preserved |
| 34 | + return prefix + "".join(f"{indent}{content}" for indent, content in sorted_items) |
| 35 | + |
| 36 | + sorted_content = re.sub(pattern, sort_list, content) |
| 37 | + if sorted_content == content: |
| 38 | + return 0 |
| 39 | + |
| 40 | + file_path.write_text(sorted_content, encoding="utf-8") |
| 41 | + print(f"Sorting members in {file_path}") |
| 42 | + return 1 |
| 43 | + |
| 44 | + |
| 45 | +PATH = Path("docs") / "api-reference" |
| 46 | +FILES_TO_SKIP = {"dtypes", "typing"} |
| 47 | + |
| 48 | +ret = max( |
| 49 | + sort_members_in_markdown(file_path=file_path) |
| 50 | + for file_path in PATH.glob("*.md") |
| 51 | + if file_path.stem not in FILES_TO_SKIP |
| 52 | +) |
| 53 | + |
| 54 | +sys.exit(ret) |
0 commit comments