-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathupdate-commit-log.py
More file actions
154 lines (132 loc) · 5.15 KB
/
update-commit-log.py
File metadata and controls
154 lines (132 loc) · 5.15 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import os
import json
import codecs
from datetime import datetime, timezone, timedelta
BEIJING_TZ = timezone(timedelta(hours=8))
commit_log_file = "commit-log.txt"
commit_log_js_file = "commit-log.js"
def decode_and_map_paths(raw_paths):
decoded_map = []
for raw in raw_paths:
try:
decoded_bytes = codecs.escape_decode(raw.encode())[0]
decoded = decoded_bytes.decode('utf-8')
except Exception as e:
print(f"[ERROR] Failed to decode: {raw} - {e}")
decoded = raw
decoded_map.append((raw, decoded))
return decoded_map
def get_metadata(file_path):
try:
with open(file_path, "r", encoding="utf-8", errors='ignore') as file:
lines = file.readlines()
if lines and lines[0].startswith('---'):
metadata = {}
for line in lines[1:]:
if line.startswith('---'):
break
if ':' in line:
key, value = line.split(":", 1)
metadata[key.strip()] = value.strip()
return metadata
else:
return None
except Exception as e:
print(f"[ERROR] Reading metadata from {file_path} failed: {e}")
return None
def clean_commit_log():
try:
with open(commit_log_file, "r", encoding="utf-8", errors='ignore') as file:
raw_lines = list(set([line.strip() for line in file if line.strip()]))
decoded_pairs = decode_and_map_paths(raw_lines)
logs_with_time = []
for raw, decoded in decoded_pairs:
if os.path.exists(decoded):
timestamp = os.path.getmtime(decoded)
logs_with_time.append({
'raw': raw,
'decoded': decoded,
'timestamp': timestamp
})
sorted_logs = sorted(logs_with_time, key=lambda x: x['timestamp'], reverse=True)
latest_logs = sorted_logs[:5]
return latest_logs
except Exception as e:
print(f"[ERROR] Failed to clean commit log: {e}")
return []
def get_blog_metadata(latest_logs):
blog_metadata = []
for log in latest_logs:
decoded_path = log['decoded']
metadata = get_metadata(decoded_path)
if metadata:
title = metadata.get("title", "No title")
timestamp = log['timestamp']
date = datetime.fromtimestamp(timestamp, tz=BEIJING_TZ).strftime("%Y-%m-%d %H:%M:%S")
slug = os.path.splitext(os.path.basename(decoded_path))[0]
parts = decoded_path.replace("\\", "/").split("/")
try:
blog_index = parts.index("blog")
section = parts[blog_index + 1] if blog_index + 1 < len(parts) else "unknown"
except ValueError:
section = "unknown"
blog_metadata.append({
"title": title,
"date": date,
"slug": slug,
"section": section
})
return blog_metadata
def get_all_blog_last_modified():
last_modified_map = {}
blog_root = "blog"
for root, dirs, files in os.walk(blog_root):
for file in files:
if file.endswith(".md"):
full_path = os.path.join(root, file)
timestamp = os.path.getmtime(full_path)
iso_time = datetime.fromtimestamp(timestamp, tz=BEIJING_TZ).isoformat()
rel_path = os.path.relpath(full_path).replace("\\", "/")
last_modified_map[rel_path] = iso_time
return last_modified_map
def write_commit_log_js(blog_metadata):
try:
if not blog_metadata:
print("[ERROR] No metadata to write.")
return
logs = [
{
"title": e["title"],
"date": e["date"],
"slug": e["slug"],
"section": e["section"]
} for e in blog_metadata
]
last_modified = get_all_blog_last_modified()
js_content = (
"export const logs = " + json.dumps(logs, indent=2) + ";\n\n" +
"export const lastModified = " + json.dumps(last_modified, indent=2) + ";"
)
with open(commit_log_js_file, "w", encoding="utf-8") as file:
file.write(js_content)
print("[INFO] commit-log.js has been updated successfully.")
except Exception as e:
print(f"[ERROR] Failed to write commit-log.js: {e}")
def update_commit_log():
try:
print("[INFO] Cleaning commit-log.txt and retrieving latest blog logs...")
latest_logs = clean_commit_log()
if not latest_logs:
print("[ERROR] No valid blog logs to process.")
return
blog_metadata = get_blog_metadata(latest_logs)
write_commit_log_js(blog_metadata)
print("[INFO] commit-log.js has been updated.")
with open(commit_log_file, "w", encoding="utf-8") as file:
for log in latest_logs:
file.write(f"{log['raw']}\n")
print("[INFO] commit-log.txt has been updated.")
except Exception as e:
print(f"[ERROR] Failed to update commit log: {e}")
if __name__ == "__main__":
update_commit_log()