-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_posts.py
More file actions
49 lines (37 loc) · 1.54 KB
/
generate_posts.py
File metadata and controls
49 lines (37 loc) · 1.54 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
import os
import json
import re
input_dir = 'src/contexts/resource'
output_file = 'src/contexts/postsData.ts'
posts = []
if not os.path.exists(input_dir):
os.makedirs(input_dir)
files = [f for f in os.listdir(input_dir) if f.endswith('.md')]
for filename in files:
with open(os.path.join(input_dir, filename), 'r', encoding='utf-8') as f:
content = f.read()
# Parse JSON frontmatter
# We look for content between the first two --- lines
parts = re.split(r'^---$', content, maxsplit=2, flags=re.MULTILINE)
if len(parts) >= 3:
metadata_json = parts[1].strip()
body = parts[2].strip()
try:
metadata = json.loads(metadata_json)
metadata['content'] = body
posts.append(metadata)
except Exception as e:
print(f"Error parsing {filename}: {e}")
else:
print(f"Invalid format in {filename}")
# Sort by id descending
posts.sort(key=lambda x: int(x['id']) if str(x.get('id', '')).isdigit() else 0, reverse=True)
# Generate TypeScript
ts_content = "import { BlogPost } from './BlogContext';\n\n"
ts_content += "// This file is auto-generated by generate_posts.py. DO NOT EDIT.\n"
ts_content += "export const blogPostsData: BlogPost[] = "
ts_content += json.dumps(posts, ensure_ascii=False, indent=2)
ts_content += ";\n"
with open(output_file, 'w', encoding='utf-8') as f:
f.write(ts_content)
print(f"Success: Generated {output_file} with {len(posts)} posts.")