把md文件和图片资源从gridea迁移到hexo

gridea用了半年,开始试试hexo。这是一个迁移脚本。

这是deepseek完成的作业。

完整脚本

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

def sync_files(src_dir, dst_dir):
"""同步源目录到目标目录(增量模式)"""
if not os.path.isdir(src_dir):
print(f"错误:源目录不存在 {src_dir}")
return False

if not os.path.exists(dst_dir):
print(f"创建目标目录 {dst_dir}")
os.makedirs(dst_dir)

print(f"正在同步 {src_dir} -> {dst_dir}")

total = copied = skipped = 0

for root, _, files in os.walk(src_dir):
for filename in files:
total += 1
src_path = os.path.join(root, filename)
rel_path = os.path.relpath(src_path, src_dir)
dst_path = os.path.join(dst_dir, rel_path)

# 检查是否需要复制
if not os.path.exists(dst_path):
copy_reason = "新文件"
else:
# 比较修改时间和文件大小
src_stat = os.stat(src_path)
dst_stat = os.stat(dst_path)

if src_stat.st_mtime > dst_stat.st_mtime or src_stat.st_size != dst_stat.st_size:
copy_reason = "已更新"
else:
skipped += 1
continue

# 确保目标目录存在
os.makedirs(os.path.dirname(dst_path), exist_ok=True)

# 执行复制
try:
shutil.copy2(src_path, dst_path)
print(f"已复制 ({copy_reason}): {rel_path}")
copied += 1
except Exception as e:
print(f"复制失败 {rel_path}: {str(e)}")

print(f"同步完成. 总计: {total}, 已复制: {copied}, 已跳过: {skipped}")
return True

def main():
# 同步图片目录
sync_files(
r"E:\documents\Gridea\post-images",
r"D:\hexo\blog\source\post-images"
)

# 同步文章目录
sync_files(
r"E:\documents\Gridea\posts",
r"D:\hexo\blog\source\_posts"
)

if __name__ == "__main__":
main()

保存为 sync_hexo.py,直接运行。

特点:

  • 简洁实现:完全去除了日志系统,只保留必要的控制台输出;
  • 双目录同步:同时处理图片目录和文章目录;
  • 增量同步:通过比较文件修改时间和大小,只复制有变动的文件;
  • 自动创建目录:如果目标目录不存在会自动创建;
  • 错误处理:会捕获并显示复制过程中出现的错误。

注意事项

确保源目录路径正确(特别是Gridea的默认路径可能有变化)。

就是任性,用gridea客户端写,用hexo生成网站。