|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +# to run: uv run https://raw.githubusercontent.com/huggingface/doc-builder/main |
| 4 | +# example: uv run https://raw.githubusercontent.com/huggingface/doc-builder/main/migrations/migrate_tips.py /Users/mishig/transformers/ |
| 5 | + |
| 6 | +# Replace <Tip> blocks with [!TIP]/[!WARNING] blockquotes. |
| 7 | + |
| 8 | +import argparse |
| 9 | +import re |
| 10 | +from pathlib import Path |
| 11 | + |
| 12 | +TIP_PATTERN = re.compile( |
| 13 | + r"(?m)^(?P<indent>[ \t]*)<Tip(?P<warning>\s+warning(?:={true})?)?>\s*(?P<body>.*?)\s*</Tip>", |
| 14 | + re.DOTALL, |
| 15 | +) |
| 16 | + |
| 17 | +SUPPORTED_EXTENSIONS = {".md", ".mdx", ".py"} |
| 18 | + |
| 19 | + |
| 20 | +def tip_to_admonition(match: re.Match) -> str: |
| 21 | + indent = match.group("indent") or "" |
| 22 | + body = match.group("body").strip("\n") |
| 23 | + label = "[!WARNING]" if match.group("warning") else "[!TIP]" |
| 24 | + |
| 25 | + lines = [f"{indent}> {label}"] |
| 26 | + |
| 27 | + if body: |
| 28 | + for line in body.splitlines(): |
| 29 | + if indent and line.startswith(indent): |
| 30 | + line = line[len(indent) :] |
| 31 | + if line.strip(): |
| 32 | + lines.append(f"{indent}> {line}") |
| 33 | + else: |
| 34 | + lines.append(f"{indent}>") |
| 35 | + else: |
| 36 | + lines.append(f"{indent}>") |
| 37 | + |
| 38 | + return "\n".join(lines) |
| 39 | + |
| 40 | + |
| 41 | +def convert_file(path: Path) -> bool: |
| 42 | + text = path.read_text(encoding="utf-8") |
| 43 | + new_text, replaced = TIP_PATTERN.subn(tip_to_admonition, text) |
| 44 | + if replaced: |
| 45 | + path.write_text(new_text, encoding="utf-8") |
| 46 | + return bool(replaced) |
| 47 | + |
| 48 | + |
| 49 | +def main() -> None: |
| 50 | + parser = argparse.ArgumentParser(description="Convert <Tip> blocks to [!TIP]/[!WARNING] blockquotes.") |
| 51 | + parser.add_argument("root", type=Path, help="Docs directory to process.") |
| 52 | + args = parser.parse_args() |
| 53 | + |
| 54 | + if args.root.is_file(): |
| 55 | + targets = [args.root] if args.root.suffix.lower() in SUPPORTED_EXTENSIONS else [] |
| 56 | + else: |
| 57 | + targets = sorted(path for ext in SUPPORTED_EXTENSIONS for path in args.root.rglob(f"*{ext}") if path.is_file()) |
| 58 | + |
| 59 | + changed = sum(convert_file(path) for path in targets) |
| 60 | + |
| 61 | + print(f"Updated {changed} file(s).") |
| 62 | + |
| 63 | + |
| 64 | +if __name__ == "__main__": |
| 65 | + main() |
0 commit comments