|
| 1 | +#!/usr/bin/env python3 |
| 2 | +from pathlib import Path |
| 3 | +import fnmatch |
| 4 | + |
| 5 | + |
| 6 | +def load_ignore(dir_path: Path): |
| 7 | + ignore_file = dir_path / ".indexignore" |
| 8 | + patterns = [] |
| 9 | + if ignore_file.exists(): |
| 10 | + for line in ignore_file.read_text().splitlines(): |
| 11 | + line = line.strip() |
| 12 | + if not line or line.startswith("#"): |
| 13 | + continue |
| 14 | + patterns.append(line) |
| 15 | + patterns.append("index.md") # always ignore old indexes |
| 16 | + return patterns |
| 17 | + |
| 18 | + |
| 19 | +def should_ignore(path: Path, patterns): |
| 20 | + return any(fnmatch.fnmatch(path.name, pat) for pat in patterns) |
| 21 | + |
| 22 | + |
| 23 | +def make_index(dir_path: Path): |
| 24 | + patterns = load_ignore(dir_path) |
| 25 | + readme = dir_path / "README.md" |
| 26 | + index = dir_path / "index.md" |
| 27 | + parts = [] |
| 28 | + |
| 29 | + # 1) README or fallback title |
| 30 | + if readme.exists() and not should_ignore(readme, patterns): |
| 31 | + parts.append(readme.read_text(encoding="utf-8")) |
| 32 | + parts.append("\n") |
| 33 | + else: |
| 34 | + title = dir_path.name.replace("_", " ").title() or "Documentation" |
| 35 | + parts.append(f"# {title}\n\n") |
| 36 | + |
| 37 | + parts.append("## Contents\n\n") |
| 38 | + |
| 39 | + # 2) List markdown files |
| 40 | + for md in sorted(dir_path.glob("*.md")): |
| 41 | + if should_ignore(md, patterns) or md.name.lower() in ("readme.md", "index.md"): |
| 42 | + continue |
| 43 | + title = md.stem.replace("_", " ").title() |
| 44 | + parts.append(f"- [{title}]({md.name})\n") |
| 45 | + parts.append("\n") |
| 46 | + |
| 47 | + # 3) Recurse into subdirectories |
| 48 | + for sub in sorted([d for d in dir_path.iterdir() if d.is_dir()]): |
| 49 | + if should_ignore(sub, patterns): |
| 50 | + continue |
| 51 | + make_index(sub) |
| 52 | + title = sub.name.replace("_", " ").title() |
| 53 | + parts.append(f"### [{title}]({sub.name}/index.html)\n") |
| 54 | + |
| 55 | + index.write_text("".join(parts), encoding="utf-8") |
| 56 | + print(f"Generated {index}") |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == "__main__": |
| 60 | + make_index(Path("docs")) |
0 commit comments