|
| 1 | +"""Task automation using ewok (invoke-compatible).""" |
| 2 | + |
| 3 | +import re |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | +from ewok import Context, task |
| 7 | + |
| 8 | +# Compiled regex pattern for replacing the nav section in mkdocs.yml |
| 9 | +NAV_SECTION_PATTERN = re.compile(r"nav:.*?(?=\n[a-z_]+:|$)", re.DOTALL) |
| 10 | + |
| 11 | + |
| 12 | +def extract_title(md_file: Path) -> str: |
| 13 | + """Extract the title from a markdown file's first heading.""" |
| 14 | + first_line = md_file.read_text(encoding="utf-8").split("\n", 1)[0].strip() |
| 15 | + # Remove the leading # and any extra whitespace |
| 16 | + return first_line.lstrip("#").strip() |
| 17 | + |
| 18 | + |
| 19 | +def generate_nav_entries() -> list[str]: |
| 20 | + """Generate nav entries from numbered markdown files in docs/.""" |
| 21 | + docs_dir = Path(__file__).parent / "docs" |
| 22 | + |
| 23 | + # Find all numbered chapter files (supports 1-N digits) |
| 24 | + chapters = [f for f in docs_dir.glob("*_*.md") if f.stem.split("_", 1)[0].isdigit()] |
| 25 | + |
| 26 | + return [ |
| 27 | + f" - {extract_title(chapter)}: {chapter.name}" |
| 28 | + for chapter in sorted( |
| 29 | + chapters, |
| 30 | + key=lambda f: int(f.stem.split("_", 1)[0]), |
| 31 | + ) |
| 32 | + ] |
| 33 | + |
| 34 | + |
| 35 | +@task |
| 36 | +def update_docs_nav(ctx: Context) -> None: |
| 37 | + """Update mkdocs.yml nav section from actual markdown files to prevent sync issues.""" |
| 38 | + mkdocs_file = Path(__file__).parent / "mkdocs.yml" |
| 39 | + |
| 40 | + content = mkdocs_file.read_text(encoding="utf-8") |
| 41 | + |
| 42 | + # Generate new nav entries |
| 43 | + nav_entries = generate_nav_entries() |
| 44 | + new_nav_section = "nav:\n" + "\n".join(nav_entries) |
| 45 | + |
| 46 | + # Replace the nav section |
| 47 | + updated_content = NAV_SECTION_PATTERN.sub(new_nav_section, content) |
| 48 | + |
| 49 | + mkdocs_file.write_text(updated_content, encoding="utf-8") |
| 50 | + |
| 51 | + print(f"✓ Updated mkdocs.yml with {len(nav_entries)} chapters") |
| 52 | + print("\nGenerated nav:") |
| 53 | + for entry in nav_entries: |
| 54 | + print(entry) |
0 commit comments