|
| 1 | +import re |
| 2 | + |
| 3 | + |
| 4 | +def run(config): |
| 5 | + markdown_files = config["markdown_files"] |
| 6 | + for file in markdown_files: |
| 7 | + process(file) |
| 8 | + |
| 9 | + |
| 10 | +def process(file_path): |
| 11 | + """ |
| 12 | + Reads a markdown file, searches for code block that have one-word flags |
| 13 | + and replace with flag=value. Otherwise Hugo will fail to parse markdown |
| 14 | + with error `failed to parse Markdown attributes; you may need to quote the values` |
| 15 | + """ |
| 16 | + try: |
| 17 | + # Read the file |
| 18 | + with open(file_path, "r", encoding="utf-8") as file: |
| 19 | + content = file.read() |
| 20 | + |
| 21 | + # Find and replace codeblocks |
| 22 | + transformed_content = transform_codeblocks(content) |
| 23 | + |
| 24 | + # Write file if content was changed |
| 25 | + if transformed_content != content: |
| 26 | + with open(file_path, "w", encoding="utf-8") as file: |
| 27 | + file.write(transformed_content) |
| 28 | + |
| 29 | + except Exception as e: |
| 30 | + print(f"Error processing file {file_path}: {str(e)}") |
| 31 | + raise |
| 32 | + |
| 33 | + |
| 34 | +def transform_codeblocks(content): |
| 35 | + pattern = re.compile( |
| 36 | + r"^\s*```([a-zA-Z0-9_-]+)" # language |
| 37 | + r"[ \t]+\{([^}]*)\}\s*$", # flags |
| 38 | + re.MULTILINE, |
| 39 | + ) |
| 40 | + |
| 41 | + def replacer(match): |
| 42 | + language = match.group(1) |
| 43 | + all_flags = match.group(2).strip() |
| 44 | + |
| 45 | + if not all_flags: |
| 46 | + return f"```{language}" |
| 47 | + |
| 48 | + flag_parts = all_flags.split() |
| 49 | + transformed_flags = [] |
| 50 | + |
| 51 | + for flag in flag_parts: |
| 52 | + if "=" in flag: |
| 53 | + # Already in key=value format, keep as is |
| 54 | + transformed_flags.append(flag) |
| 55 | + else: |
| 56 | + # One-word flag, transform to flag="" |
| 57 | + transformed_flags.append(f'{flag}=""') |
| 58 | + |
| 59 | + flags_str = " ".join(transformed_flags) |
| 60 | + return f"```{language} {{{flags_str}}}" |
| 61 | + |
| 62 | + return pattern.sub(replacer, content) |
0 commit comments