山高水长
首页
  • 分类
  • 标签
  • 归档
友情链接
GitHub (opens new window)

山高水长

首页
  • 分类
  • 标签
  • 归档
友情链接
GitHub (opens new window)
  • 博客搭建记录
  • 优化autoFrontmatter代码
  • 部署到云服务器
  • blog
Shanya
2022-07-22

优化autoFrontmatter代码

# 优化autoFrontmatter代码

autoFrontmatter 是用来为文章自动生成frontMatter的,可以更好让我们的文章链接固定。
其实Vdoing主题本身是有自动生成frontMatter功能的,但是需要在dev或者build的时候生效,但是我们所有的编译交予gihub的自动工作流程,因此我写了这个脚本在执行deploy的时候生成frontMatter.

以前的代码比较粗糙,这次借着优化博客仓库的机会顺便将此代码优化一下。

优化内容:

  • 一些功能行函数独立出来
  • 引入正则表达式

详细代码如下:

import contextlib
import os
import re
import random
import time
import glob

# 作者名及主页链接
AUTHOR = 'Shanya'
LINK = 'https://github.com/shanyaliux'


# 判断一个字符串是否为数字
def isNumber(s):
    with contextlib.suppress(ValueError):
        float(s)
        return True
    with contextlib.suppress(TypeError, ValueError):
        import unicodedata
        unicodedata.numeric(s)
        return True
    return False


# 生成一个新的permalink
def getNewPermalink():
    return hex(random.randint(1118481, 16777215))[2:]


# 得到所有的已有的permalink
def getExistsPermalinks(docsList):
    permalinks = []
    for doc in docsList:
        fileName = doc.split(os.sep)[-1]

        if doc.split(os.sep)[1] != '_posts' and (not isNumber(fileName.split('.')[0]) or fileName.split('.')[-2] == 'friends'):
            continue

        with open(doc, encoding="utf-8", errors='ignore') as f:

            content = f.read()
            result = re.finditer(r'---+', content)

            positions = [i.span() for i in result]

            if not positions:
                continue

            temp = content[positions[0][1] + 1: positions[0][1] + 6]
            if temp != 'title':
                continue

            frontMatter = content[positions[0][1]: positions[1][0]]
            permalinkSpan = re.search(r'permalink', frontMatter).span()
            categoriesSpan = re.search(r'categories', frontMatter).span()
            permalink = frontMatter[permalinkSpan[1] + 1: categoriesSpan[0] - 1]
            permalink = permalink.strip('/').split('/')[-1]
            permalinks.append(permalink)
    return permalinks


# 生成新的FrontMatter
def getFrontMatter(title, ct, permalink):
    date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())

    frontMatter = '---\n' + f'title: {title}\n'
    frontMatter += f'date: {date}\n'
    frontMatter += f'permalink: /pages/{permalink}/\n'
    frontMatter += f'categories: \n - {ct}\n'
    frontMatter += f'tags: \n - {ct}\n'
    frontMatter += f'author: \n name: {AUTHOR}\n link: {LINK}\n'
    frontMatter += '---\n\n'

    return frontMatter


if __name__=="__main__":

    docsPath = r'docs'
    docsList = glob.glob(f'{docsPath}/**/*.md', recursive=True)

    permalinks = getExistsPermalinks(docsList)

    for doc in docsList:
        fileName = doc.split(os.sep)[-1]

        if doc.split(os.sep)[1] != '_posts' and (not isNumber(fileName.split('.')[0]) or fileName.split('.')[-2] == 'friends'):
            continue

        with open(doc, 'r+', encoding="utf-8", errors='ignore') as f:

            content = f.read()
            result = re.finditer(r'---+', content)
            if positions := [i.span() for i in result]:
                temp = content[positions[0][1] + 1: positions[0][1] + 6]
                if temp == 'title':
                    continue

            print(doc)

            if doc.split(os.sep)[1] != '_posts':
                ct = doc.split(os.sep)[1].split('.')[1]
                title = fileName.split('.')[1]
            else:
                ct = doc.split(os.sep)[2]
                title = doc.split(os.sep)[-1].split('.')[0]
            permalink = getNewPermalink()
            while permalink in permalinks:
                permalink = getNewPermalink()
            frontMatter = getFrontMatter(title, ct, permalink)
            f.seek(0, 0)
            f.write(frontMatter + content)

    print('done!')
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
编辑 (opens new window)
#blog
上次更新: 2022/09/30, 04:53:04
博客搭建记录
部署到云服务器

← 博客搭建记录 部署到云服务器→

最近更新
01
FCOS
09-30
02
Python执行终端命令
09-13
03
Android Compose 权限请求
08-12
更多文章>
Theme by Vdoing | Copyright © 2020-2022 Shanya | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式