|
13 | 13 | import yaml |
14 | 14 |
|
15 | 15 |
|
| 16 | +class _LiteralDumper(yaml.SafeDumper): |
| 17 | + """Dump multiline strings using literal style so code stays readable.""" |
| 18 | + |
| 19 | + |
| 20 | +def _str_presenter(dumper, data): |
| 21 | + if isinstance(data, str) and "\n" in data: |
| 22 | + return dumper.represent_scalar("tag:yaml.org,2002:str", data, style='|') |
| 23 | + return dumper.represent_scalar("tag:yaml.org,2002:str", data) |
| 24 | + |
| 25 | + |
| 26 | +# Register custom string representer |
| 27 | +_LiteralDumper.add_representer(str, _str_presenter) |
| 28 | + |
| 29 | + |
16 | 30 | def inject_minified_to_markdown(markdown_file, minified_code=None, minified_bundled_code=None): |
17 | 31 | """Inject minified code into markdown file's front matter using proper YAML parsing.""" |
18 | 32 | try: |
@@ -62,9 +76,14 @@ def inject_minified_to_markdown(markdown_file, minified_code=None, minified_bund |
62 | 76 | if not updated: |
63 | 77 | return False |
64 | 78 |
|
65 | | - # Re-serialize YAML front matter |
66 | | - # Use default_flow_style=False to keep lists as blocks, allow_unicode=True for special chars |
67 | | - new_front_matter_str = yaml.dump(front_matter, default_flow_style=False, allow_unicode=True, sort_keys=False) |
| 79 | + # Re-serialize YAML front matter with literal blocks for multiline strings |
| 80 | + new_front_matter_str = yaml.dump( |
| 81 | + front_matter, |
| 82 | + Dumper=_LiteralDumper, |
| 83 | + default_flow_style=False, |
| 84 | + allow_unicode=True, |
| 85 | + sort_keys=False, |
| 86 | + ) |
68 | 87 |
|
69 | 88 | # Write updated content |
70 | 89 | new_content = f'---{new_front_matter_str}---{body}' |
|
0 commit comments