-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathset_link_category.py
More file actions
59 lines (50 loc) · 2.57 KB
/
Copy pathset_link_category.py
File metadata and controls
59 lines (50 loc) · 2.57 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
import os
import yaml
import sys
def add_link_category(posts_dir):
"""
Adds a `link_category` front matter entry to all posts in the specified directory.
The value is set to the first category in the `categories` list if it exists and
`link_category` is not already set.
"""
for root, _, files in os.walk(posts_dir):
for file in files:
if file.endswith(".md"):
file_path = os.path.join(root, file)
with open(file_path, 'r') as f:
lines = f.readlines()
# Check if the file has front matter
if lines[0].strip() == '---':
front_matter_end = lines[1:].index('---\n') + 1
front_matter_lines = lines[1:front_matter_end]
front_matter = yaml.safe_load(''.join(front_matter_lines))
# Check if `categories` exists and is a list
if 'categories' in front_matter and isinstance(front_matter['categories'], list):
first_category = front_matter['categories'][0]
# Only add `link_category` if it is not already set
if 'link_category' not in front_matter:
# Add the `link_category` line to the front matter
front_matter_lines.append(f"link_category: {first_category}\n")
with open(file_path, 'w') as f:
f.write('---\n')
f.writelines(front_matter_lines)
f.write('---\n')
f.writelines(lines[front_matter_end + 1:])
print(f"Updated {file_path} with link_category: {first_category}")
else:
print(f"{file_path} already has link_category set, skipping.")
else:
print(f"No categories found in {file_path}, skipping.")
else:
print(f"No front matter found in {file_path}, skipping.")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python3 set_link_category.py <jekyll_project_path>")
sys.exit(1)
# Get the Jekyll project path from the command-line argument
jekyll_project_path = sys.argv[1]
posts_directory = os.path.join(jekyll_project_path, "_posts")
if not os.path.isdir(posts_directory):
print(f"Error: The directory '{posts_directory}' does not exist.")
sys.exit(1)
add_link_category(posts_directory)