hexo博客文章增加修改历史change log

hexo是一款基于Nodejs的静态博客生成器,我们内部用来做知识库,项目托管在内部的gitlab,为了提升大家的贡献积极性,考虑在知识库的页面增加贡献者说明

读取日志

知识库的思想是多人协作,因为已经用git记录了,所以我们可以从git读取change log, 可以通过git log读取

git log -15 --pretty=format:"%an   %aI   %s" file

  • 15 指定最多15条
  • --pretty=format 格式化
  • %an 用户
  • %aI 时间
  • %s 日志

python读取日志并append到博客的markdown

读取日志:

def get_change_log(md):
    logs = excute_command('git log -15 --pretty=format:"%an   %aI   %s" '+ md).split("\n")
    result = []
    for log in logs:
        result.append(log.split('   '))
    return result

def excute_command(cmd):
    process = os.popen(cmd) # return file
    output = process.read().decode('utf-8')
    process.close()
    return output

注意上面是python2的代码

然后,在写个程序遍历markdown,并追加日志到markdown:

def walk_files(dir):
    files = os.listdir(dir)
    files.sort()
    # 先处理文件
    for file in files:
        filename = os.path.join(dir, file)
        if not os.path.isdir(filename):
            if not file.endswith(".md"):
                continue
            logs = get_change_log(os.path.join(dir, file))
            append_change_log(filename, logs)
                
    for file in files:
        filename = os.path.join(dir, file)
        if os.path.isdir(filename):
            walk_files(filename) 

def append_change_log(filename, logs):
    change_log = ['## 修改历史','', '| 序号 | 贡献者 |  时间  | 修改内容 |', '| ---- | --- | --- |---  |']
    index = 1
    for log in logs: 
        if len(log) == 3:
            change_log.append('| %s | %s | %s | %s |' % (index, log[0], log[1], log[2]))
            index = index + 1
    with open(filename, 'a+') as f:
        for log in change_log:
            f.write(log)
            f.write("\n")

CI集成

在gitlab的ci里,在hexo build之前,需要先执行python:

build:hexo:
  image: cicd-hf-hexo:1.0
  stage: build
  script:
  - python gen-changelog.py
  - npm run clean
  - npm run build
  only:
  - master

最终效果如下:

posted @ 2021-12-14 18:51  JadePeng  阅读(176)  评论(0编辑  收藏  举报