起因

githubActions,推送到远端之后,服务器的文件Mtime会默认为push时间,这和自动读取mtime的hexo有了冲突,使得所有博客的更新日期都为push日期,也不利于outDateNotice的通知

背景知识

操作系统:文件系统

参考资料

unix系统的每个文件都有相应的atime,ctime,mtime

其中mtime指的是文件修改日期,指有插入或者删除操作而触发的日期更改

1
touch -mt YYmmddHHMM file.txt

可以修改文件mtime

解决方案1-失败

考虑使用py脚本,读取frontmatter的updated属性,os.stat读取mtime属性,判断是否相等,不等则强制同步

但是同步需要写入,写入过程本身也修改了mtime,那么下次在运行脚本的时候还是需要同步,同步成上一次脚本写入文件的时间,这是不正确的

解决方案2-成功

在py中使用touch命令,同步frontmatter之后,再将frontmatter的内容作为mtime,用touch命令加在文件上

相当于用先读取文件mtime,暂存到string,然后用touch命令再次写入mtime到文件描述符。做了一次不更改mtime的文件读写

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
import os
import time

if __name__ == "__main__":

posts_dir = "source/_posts"

# 遍历_posts目录及其子目录下的所有文件
for root, dirs, files in os.walk(posts_dir):
dirs.sort()
for file in sorted(files):
file_path = os.path.join(root, file)
file_path = os.path.abspath(file_path)
if not file_path.endswith(".md"):
continue
file_mtime = time.localtime(os.stat(file_path).st_mtime)
touch_str = time.strftime("%Y%m%d%H%M", file_mtime)
touch_cmd = "touch -mt " + touch_str + " " + file_path
ls_cmd = "ls -l " + file_path
mtime_str = "updated: " + time.strftime("%Y-%m-%d %H:%M:%S", file_mtime) + "\n"
mtime_str_simple = "updated: " + time.strftime("%Y-%m-%d %H:%M", file_mtime)
with open(file_path, 'r') as r_file:
lines = r_file.readlines()
needChange = 0
for line in lines:
if line.startswith("updated") and not line.startswith(mtime_str_simple):
needChange = 1
if needChange:
with open(file_path, "w") as w_file:
for line in lines:
if line.startswith("updated"):
w_file.write(mtime_str)
print(mtime_str.strip(), "has been written to", file_path)
else:
w_file.write(line)
os.system(touch_cmd)
print(touch_str, "has been touched to", file_path, "Result:")
os.system(ls_cmd)