|
| 1 | +import os |
| 2 | +import re |
| 3 | +import argparse |
| 4 | + |
| 5 | +# Registry for bidirectional format conversion: |
| 6 | +# |
| 7 | +# Key: The MkDocs admonition type (the target for '!!! type' syntax). |
| 8 | +# Value: |
| 9 | +# - emoji: Used for mapping GitHub-style emoji quotes (> ⚠️) to MkDocs. |
| 10 | +# - tag: Reserved for mapping official GitHub Alert syntax (> [!WARNING]). |
| 11 | +MAPPING = { |
| 12 | + "warning": {"emoji": "⚠️", "tag": "WARNING"}, |
| 13 | + "tip": {"emoji": "💡", "tag": "TIP"}, |
| 14 | + "info": {"emoji": "ℹ️", "tag": "NOTE"}, |
| 15 | + "success": {"emoji": "✅", "tag": "SUCCESS"}, |
| 16 | + "danger": {"emoji": "🚫", "tag": "CAUTION"}, |
| 17 | + "note": {"emoji": "📝", "tag": "NOTE"} |
| 18 | +} |
| 19 | + |
| 20 | +# Reverse lookup: mapping emojis back to their respective MkDocs types |
| 21 | +EMOJI_TO_TYPE = {v["emoji"]: k for k, v in MAPPING.items()} |
| 22 | + |
| 23 | +# Emoji Pattern: Handles optional bold titles and standard emojis |
| 24 | +EMOJI_PATTERN = r'>\s*(⚠️|💡|ℹ️|✅|🚫|📝)(?:\s*\*\*(.*?)\*\*)?\s*\n((?:>\s*.*\n?)*)' |
| 25 | + |
| 26 | +# GitHub Alert Pattern [!TYPE] |
| 27 | +GITHUB_ALERT_PATTERN = r'>\s*\[\!(WARNING|TIP|NOTE|IMPORTANT|CAUTION)\]\s*\n((?:>\s*.*\n?)*)' |
| 28 | + |
| 29 | +# MkDocs Pattern: Captures '!!! type "Title"' blocks |
| 30 | +MKDOCS_PATTERN = r'!!!\s+(\w+)\s+"(.*?)"\n((?:\s{4}.*\n?)*)' |
| 31 | + |
| 32 | + |
| 33 | +def clean_body_for_mkdocs(body_text): |
| 34 | + """ |
| 35 | + Cleans blockquote content for MkDocs: |
| 36 | + 1. Removes leading '>' markers. |
| 37 | + 2. Strips ALL leading blank lines to close the gap with the title. |
| 38 | + 3. Strips ALL trailing blank lines to prevent extra lines at the end. |
| 39 | + 4. Preserves internal paragraph breaks. |
| 40 | + """ |
| 41 | + # Remove leading '>' and trailing whitespace from each line |
| 42 | + raw_lines = [re.sub(r'^>\s?', '', line).rstrip() for line in body_text.split('\n')] |
| 43 | + |
| 44 | + # Find the first line with actual text (to strip leading blank lines) |
| 45 | + start_idx = -1 |
| 46 | + for i, line in enumerate(raw_lines): |
| 47 | + if line.strip(): |
| 48 | + start_idx = i |
| 49 | + break |
| 50 | + |
| 51 | + if start_idx == -1: |
| 52 | + return "" |
| 53 | + |
| 54 | + # Slice from the first content line |
| 55 | + content_lines = raw_lines[start_idx:] |
| 56 | + |
| 57 | + # Join lines and rstrip the entire block to remove trailing blank lines |
| 58 | + body = "\n".join([f" {l}".rstrip() for l in content_lines]).rstrip() |
| 59 | + return body |
| 60 | + |
| 61 | +def to_mkdocs(content): |
| 62 | + """Converts GitHub style to MkDocs style.""" |
| 63 | + |
| 64 | + def emoji_replacer(match): |
| 65 | + emoji_char, title, raw_body = match.groups() |
| 66 | + adm_type = EMOJI_TO_TYPE.get(emoji_char, "note") |
| 67 | + body = clean_body_for_mkdocs(raw_body) |
| 68 | + title_val = title if title else "" |
| 69 | + # Return block with exactly one newline at the end |
| 70 | + return f'!!! {adm_type} "{title_val}"\n{body}\n' |
| 71 | + |
| 72 | + |
| 73 | + def alert_replacer(match): |
| 74 | + alert_type = match.group(1).lower() |
| 75 | + type_map = {"important": "info", "caution": "danger"} |
| 76 | + mkdocs_type = type_map.get(alert_type, alert_type) |
| 77 | + raw_body = match.group(2) |
| 78 | + |
| 79 | + first_line_match = re.search(r'^>\s*\*\*(.*?)\*\*\s*\n', raw_body) |
| 80 | + title = first_line_match.group(1) if first_line_match else "" |
| 81 | + if first_line_match: |
| 82 | + raw_body = raw_body[first_line_match.end():] |
| 83 | + |
| 84 | + body = clean_body_for_mkdocs(raw_body) |
| 85 | + return f'!!! {mkdocs_type} "{title}"\n{body}\n' |
| 86 | + |
| 87 | + content = re.sub(EMOJI_PATTERN, emoji_replacer, content, flags=re.MULTILINE) |
| 88 | + content = re.sub(GITHUB_ALERT_PATTERN, alert_replacer, content, flags=re.MULTILINE) |
| 89 | + return content |
| 90 | + |
| 91 | +def to_github(content): |
| 92 | + """Converts MkDocs style to GitHub style.""" |
| 93 | + |
| 94 | + def mkdocs_replacer(match): |
| 95 | + adm_type, title, body = match.groups() |
| 96 | + # Safely retrieve the emoji, default to 'note' (📝) for unknown/unmapped types |
| 97 | + emoji = MAPPING.get(adm_type, {"emoji": "📝"})["emoji"] |
| 98 | + |
| 99 | + # Strip trailing whitespace from captured body to prevent hanging '>' |
| 100 | + clean_body = body.rstrip() |
| 101 | + raw_lines = clean_body.split('\n') |
| 102 | + content_lines = [re.sub(r'^\s{4}', '', line).rstrip() for line in raw_lines] |
| 103 | + |
| 104 | + # Header line logic |
| 105 | + github_lines = [f"> {emoji} **{title}**"] if title.strip() else [f"> {emoji}"] |
| 106 | + github_lines.append(">") # Spacer line |
| 107 | + |
| 108 | + for line in content_lines: |
| 109 | + github_lines.append(f"> {line}" if line else ">") |
| 110 | + |
| 111 | + return "\n".join(github_lines) + "\n" |
| 112 | + |
| 113 | + return re.sub(MKDOCS_PATTERN, mkdocs_replacer, content) |
| 114 | + |
| 115 | +def process_file(path, mode): |
| 116 | + mode_map = { |
| 117 | + "github-to-mkdocs": to_mkdocs, |
| 118 | + "mkdocs-to-github": to_github |
| 119 | + } |
| 120 | + if mode not in mode_map: |
| 121 | + raise ValueError(f"Unsupported mode: {mode}. Choose from {list(mode_map.keys())}.") |
| 122 | + target_func = mode_map[mode] |
| 123 | + |
| 124 | + with open(path, 'r', encoding='utf-8') as f: |
| 125 | + content = f.read() |
| 126 | + new_content = target_func(content) |
| 127 | + if new_content != content: |
| 128 | + with open(path, 'w', encoding='utf-8') as f: |
| 129 | + f.write(new_content) |
| 130 | + print(f"[{mode.upper()}] Converted: {path}") |
| 131 | + |
| 132 | +def run_conversion(mode): |
| 133 | + for root, dirs, files in os.walk('docs'): |
| 134 | + if any(x in root for x in ['scripts', 'assets', '__pycache__']): |
| 135 | + continue |
| 136 | + for file in files: |
| 137 | + if file.endswith('.md'): |
| 138 | + process_file(os.path.join(root, file), mode) |
| 139 | + |
| 140 | +if __name__ == "__main__": |
| 141 | + parser = argparse.ArgumentParser(description="Bidirectional Markdown Admonition Converter") |
| 142 | + parser.add_argument("--mode", choices=["github-to-mkdocs", "mkdocs-to-github"], required=True, help="Target format") |
| 143 | + args = parser.parse_args() |
| 144 | + run_conversion(args.mode) |
0 commit comments