-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfix_date.py
51 lines (42 loc) · 1.7 KB
/
fix_date.py
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
import os
import re
import frontmatter
def extract_date_from_filename(filename):
# Assuming the filename format is 'YYYY-MM-DD-some-title.md'
match = re.match(r'(\d{4}-\d{2}-\d{2})-', filename)
if match:
return match.group(1)
return None
def process_markdown_file(filepath):
# Load the markdown file and parse its frontmatter
with open(filepath, 'r', encoding='utf-8') as f:
post = frontmatter.load(f)
# Extract the date from the filename
filename = os.path.basename(filepath)
file_date = extract_date_from_filename(filename)
if not file_date:
print(f"Could not extract date from filename: {filename}")
return
# Check if the frontmatter already contains a date
frontmatter_date = post.get('date')
if frontmatter_date:
# If the date is different, update it
if frontmatter_date != file_date:
print(f"Updating date in {filename}: {frontmatter_date} -> {file_date}")
post['date'] = file_date
else:
# If no date exists, add it
print(f"Adding date to {filename}: {file_date}")
post['date'] = file_date
# Write the updated content back to the markdown file
with open(filepath, 'w', encoding='utf-8') as f:
f.write(frontmatter.dumps(post))
def process_markdown_files_in_directory(directory):
# Process all markdown files in the given directory
for filename in os.listdir(directory):
if filename.endswith('.md'):
filepath = os.path.join(directory, filename)
process_markdown_file(filepath)
# Example usage:
directory_path = './_posts' # Change to your directory path
process_markdown_files_in_directory(directory_path)