问题描述

在之前Github Action部署博客时遇到的文章更新时间问题,是通过js代码来解决的,参考hexo自动更新文章修改时间。但是该文章的js实现存在一些问题,因此这里改用python实现,核心的原理不变,都是通过读取文件的updated字段并修改来实现的。

代码

下面给出实现代码:

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
import os
import re
from datetime import datetime

LINE_LIMIT = 20
base_path = "./source/_posts"
ALL_FILES = []


def get_all_files(current_dir):
files = os.listdir(current_dir)
for file in files:
new_path = os.path.join(current_dir, file)
if os.path.isdir(new_path):
get_all_files(new_path)
elif os.path.isfile(new_path) and re.match(".*\.md", file):
print(f"正在处理:{file}")
ALL_FILES.append(new_path)


def write_file_time_if_needed(filepath):
stat = os.stat(filepath)
file_stamp = int(stat.st_mtime)

with open(filepath, "r+", encoding="utf-8") as f:
last_cursor_pos = 0
lineno = 0
line = f.readline()
while line:
lineno += 1
if lineno > LINE_LIMIT:
break
result = re.findall(".*updated:.*(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})", line)
if result:
ori_time = result[0]
strp_time = datetime.strptime(ori_time, "%Y-%m-%d %H:%M:%S")
content_stamp = int(strp_time.timestamp())
if content_stamp != file_stamp:
new_str_time = datetime.strftime(datetime.fromtimestamp(file_stamp), "%Y-%m-%d %H:%M:%S")
new_line_str = line.replace(ori_time, new_str_time)
f.seek(last_cursor_pos)
f.write(new_line_str.strip())
print(f"{filepath},成功更新修改时间为:{new_str_time}")
break
# read next line
last_cursor_pos = f.tell()
line = f.readline()
os.utime(filepath, (stat.st_atime, stat.st_mtime))


get_all_files(base_path)
for path in ALL_FILES:
write_file_time_if_needed(path)

使用方法,将代码保存为文件,比如叫做update_file_time.py,保存在hexo博客根目录下,然后只需要在git提交前,执行

1
python update_file_time.py

即可。