convert_admonitions.py

 1#!/usr/bin/env python3
 2"""Convert GitHub-style markdown admonitions to VitePress custom containers.
 3
 4Reads from stdin and writes to stdout.
 5"""
 6
 7import re
 8import sys
 9
10ADMONITION_START = re.compile(
11    r"^>\s+\[!(WARNING|NOTE|TIP|IMPORTANT|CAUTION)\]\s*$",
12    re.IGNORECASE,
13)
14
15TYPE_MAP = {
16    "WARNING": "warning",
17    "NOTE": "info",
18    "TIP": "tip",
19    "IMPORTANT": "details",
20    "CAUTION": "danger",
21}
22
23
24def convert_admonitions(lines):
25    out = []
26    i = 0
27    n = len(lines)
28    while i < n:
29        match = ADMONITION_START.match(lines[i])
30        if match:
31            kind = match.group(1).upper()
32            out.append(f"::: {TYPE_MAP[kind]}")
33            i += 1
34            while i < n and lines[i].startswith("> "):
35                out.append(lines[i][2:])
36                i += 1
37            out.append(":::")
38        else:
39            out.append(lines[i])
40            i += 1
41    return out
42
43
44def main():
45    text = sys.stdin.read()
46    lines = text.splitlines()
47    converted = convert_admonitions(lines)
48    sys.stdout.write("\n".join(converted))
49    if text.endswith("\n"):
50        sys.stdout.write("\n")
51
52
53if __name__ == "__main__":
54    main()