写了一个脚本,检测到有变动,自己维护pubDatetime的值,不用每次都手动修改了,hah
569 ·
0 ·
2023-05-16 23:49:31
最新编辑原因:
#!/usr/bin/env python3

import os
import re
from datetime import datetime
import pytz

# 定义替换规则
pattern = re.compile(r"pubDatetime:\s*[\d\-T:]+Z")

utc_time = datetime.utcnow()  # 获取当前的UTC时间

# 创建时区对象
utc_timezone = pytz.timezone('UTC')
beijing_timezone = pytz.timezone('Asia/Shanghai')

# 将UTC时间转换为北京时间
beijing_time = utc_time.replace(tzinfo=utc_timezone).astimezone(beijing_timezone)

# 格式化输出北京时间
new_datetime = beijing_time.strftime("%Y-%m-%dT%H:%M:%SZ")

# 递归扫描目录下的所有.md文件
def traverse_and_update(path):
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.endswith(".md"):
                filepath = os.path.join(root, file)
                # 检查文件是否有变动            
                modFile = os.popen(f"git status --porcelain").read().strip()
                if os.path.exists(filepath) and modFile:
                    fileName = filepath.split('/')[-1]
                    if fileName in modFile:
                        # 替换pubDatetime值为当前时间戳,ISO 8601格式
                        with open(filepath, "r+") as f:
                            content = f.read()
                            f.seek(0)
                            f.write(re.sub(pattern, f"pubDatetime: {new_datetime}", content))
                            f.truncate()
                        print(f"File {filepath} has been updated.")
                    continue
                    

# 检查当前目录是否为git仓库
if os.path.isdir(".git"):
    # 进入src/content/blog目录
    os.chdir("src/content/blog")

    traverse_and_update(".")

本作品系原创,采用《署名-非商业性使用-禁止演绎4.0 国际》许可协议.转载请说明出处
本文链接:https://www.upupor.com/u/bwjg31L 复制

无内容

推荐阅读