Repository navigation
Expand file tree
/
Copy pathpre-commit.py
More file actions
182 lines (164 loc) · 6.25 KB
/
Copy pathpre-commit.py
File metadata and controls
182 lines (164 loc) · 6.25 KB
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# =================================================
# Description: 侯爷Blog自动化脚本
# 1. 更新 index.md
# 2. 创建相关 issue 用于启用评论
# Version: 1.0
# Lisence: MIT
# Author: houfukude@gmail.com
# Blog: https://blog.houfukude.eu.org/
# Usage:
# ./pre-commit.py
# Based on https://gist.github.com/JeffPaine/3145490 with tweaks
# Based on https://github.com/zhaoolee/WordPressXMLRPCTools
# =================================================
import argparse
import datetime
import json
import os
import time
from argparse import RawTextHelpFormatter
import requests
from dotenv import load_dotenv
load_dotenv()
USAGE = """侯爷的Blog自动化脚本
通过指定 id 和 title 自动创建 github issue
用法:
./pre-commit.py
"""
USERNAME = os.environ.get('GITHUB_USER')
TOKEN = os.environ.get('GITHUB_TOKEN')
TOOL = os.environ.get('TOOL')
# 默认评论所在的 repo
REPO_NAME = '%s.github.io' % USERNAME
# repo 的issues API地址
URL = 'https://api.github.com/repos/%s/%s/issues' % (USERNAME, REPO_NAME)
print('[INFO] 使用的 URL: %s' % URL)
session= requests.Session()
# 使用 session 来进行授权
session.headers.update({
"Authorization": f"Bearer {TOKEN}",
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28"
})
def find_online_exist():
'''找到现在已经存在的评论'''
exist_labels = []
# GitHub 默认每页只返回 30 条, 必须翻页否则会漏掉旧文章导致重复创建 issue
params = {'state': 'all', 'per_page': 100, 'page': 1}
while True:
response = session.get(URL, params=params)
if response.status_code != 200:
print('[ERRO] Response:', response.content)
print('[ERRO] 拉取 issue 列表失败, 请检查 .env 中的 GITHUB_TOKEN 是否有效/过期')
return None
data = response.json()
print('[INFO] 第 %d 页找到 %d 个已存在的 issue' %
(params['page'], len(data)))
for each in data:
for label in each["labels"]:
l_name = label["name"]
exist_labels.append(l_name)
if len(data) < params['per_page']:
break
params['page'] += 1
# 去重
exist_labels = list(dict.fromkeys(exist_labels))
print('[INFO] 共找到 %d 个已存在的标签' % len(exist_labels))
return exist_labels
def create_issue(id, title):
'''创建一个在 USERNAME.github.io 下的 issue 用于启用评论'''
if not id:
print('[ERRO] 未传入 id 参数')
return 1
if not title:
print('[ERRO] 未传入 title 参数')
return 1
# print('[INFO] 开始创建 issue {0:s} '.format(title))
# 内容
issue = {
'title': '%s 的评论' % title,
'body': "# %s\nhttps://%s.github.io/index.html?p=%s" % (title, USERNAME, id),
'labels': [TOOL, id]
}
# Post 请求
response = session.post(URL, json=issue)
if response.status_code == 201:
print('[INFO] 创建 issue {0:s} 成功!'.format(title))
return 0
else:
print('[ERRO] 创建 issue {0:s} 失败!'.format(title))
print('[ERRO] Response:', response.content)
return 1
def find_local_articles():
'''在本地遍历 md 目录 寻找最新的文章'''
for root, ds, fs in os.walk("./md/"):
for f in fs:
if f.endswith('.md'):
fullname = os.path.join(root, f)
id = f.removesuffix(".md")
title = read_title(fullname)
modifytime = time.ctime(os.path.getmtime(fullname))
modifytime = datetime.datetime.strptime(
modifytime, '%a %b %d %H:%M:%S %Y')
modifytime.strftime("%m/%d/%Y")
yield {"id": id, "title": title, "modifytime": modifytime}
def read_title(filename):
'''读取标题 默认都是第一行'''
with open(filename, "r", encoding='utf-8') as file:
title = file.readline()
return title.removeprefix("# ").removesuffix("\n")
def update_index(article):
'''读取 index 替换指定标签下的文章'''
# 必须在index.md中存在
REPLACE_TAG = "<!--ARTICLE-->\n\n"
#
print("[INFO] 更新 index 文章: %s 标题为: %s 修改时间: %s" %
(article['id'], article['title'], article['modifytime']))
# MARKDWON 格式的标题参数
insert_info = "## [%s](index.html?p=%s) \n%s\n\n" % (
article['title'], article['id'], article['modifytime'])
# 读取 index.md
content = ""
with open("./md/index.md", "r", encoding='utf-8') as file:
content = file.read()
# 替换
if article['id'] in content:
print("[INFO] 文章 %s 已经存在于 index.md 中" % article['id'])
return False
content = content.replace(REPLACE_TAG, REPLACE_TAG + insert_info)
# 写入 index.md
with open("./md/index.md", "w", encoding='utf-8') as file:
file.write(content)
return True
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description=USAGE, formatter_class=RawTextHelpFormatter)
# parser.add_argument('--id', type=str, default=None)
# parser.add_argument('--title', type=str, default=None)
parser.add_argument('-l', '--local', action='store_true')
args = parser.parse_args()
# print(args)
# if check_env_and_var(args.id, args.title):
# exit(1)
# else:
# result = create_issue(args.id, args.title)
# exit(result)
if not USERNAME or not TOKEN or not TOOL:
print('[ERRO] 请检查 .env 中的 GITHUB_USER / GITHUB_TOKEN / TOOL 变量')
exit(1)
exist_labels = find_online_exist()
if exist_labels is None:
print('[ERRO] 无法获取 issue 列表, 已中止 (认证失败或网络异常)')
exit(1)
if not exist_labels:
print("[INFO] 没有找到已存在的 issue")
exit(0)
for article in find_local_articles():
if article['id'] not in exist_labels:
print("[INFO] 发现新文章: %s 标题为: %s" %
(article['id'], article['title']))
if update_index(article) and not args.local:
# print("[INFO] create_issue")
create_issue(article['id'], article['title'])