forked from Ikalus1988/MisakaNet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfix_frontmatter_mix.py
More file actions
89 lines (69 loc) 路 2.27 KB
/
Copy pathfix_frontmatter_mix.py
File metadata and controls
89 lines (69 loc) 路 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/usr/bin/env python3
"""Fix frontmatter JSON+YAML mix issues in lessons.
This script moves provenance blocks from frontmatter to body,
ensuring frontmatter is pure JSON.
"""
import json
import re
from pathlib import Path
REPO = Path(__file__).resolve().parent.parent
CONTRIB = REPO / "lessons" / "contrib"
def fix_frontmatter_mix(filepath: Path) -> bool:
"""Fix frontmatter JSON+YAML mix issue in a single file."""
content = filepath.read_text(encoding='utf-8')
# Parse frontmatter
m = re.match(r'^---\s*\n(.*?)\n---\s*\n(.*)', content, re.DOTALL)
if not m:
return False
frontmatter_raw = m.group(1).strip()
body = m.group(2)
# Check if it's JSON
if not frontmatter_raw.startswith('{'):
return False
# Try to parse JSON
try:
fm = json.loads(frontmatter_raw)
return False # Already valid JSON
except json.JSONDecodeError as e:
if 'Extra data' not in str(e):
return False
# Extract valid JSON part and YAML part
# Find the last closing brace before "provenance:"
lines = frontmatter_raw.split('\n')
json_lines = []
yaml_lines = []
in_json = True
brace_count = 0
for line in lines:
if in_json:
json_lines.append(line)
brace_count += line.count('{') - line.count('}')
if brace_count == 0 and line.strip() == '}':
in_json = False
else:
yaml_lines.append(line)
# Parse JSON part
json_str = '\n'.join(json_lines)
try:
fm = json.loads(json_str)
except json.JSONDecodeError:
return False
# Convert YAML part to comment in body
yaml_block = '\n'.join(yaml_lines).strip()
if yaml_block:
# Add YAML block as comment in body
body = f"<!-- provenance:\n{yaml_block}\n-->\n\n{body}"
# Reconstruct file
new_content = f"---\n{json.dumps(fm, ensure_ascii=False, indent=2)}\n---\n{body}"
# Write back
filepath.write_text(new_content, encoding='utf-8')
return True
def main():
fixed = 0
for filepath in sorted(CONTRIB.glob("*.md")):
if fix_frontmatter_mix(filepath):
print(f"Fixed: {filepath.name}")
fixed += 1
print(f"\nTotal fixed: {fixed}")
if __name__ == "__main__":
main()