Hexo Gitalk 评论自动初始化

Attson Lv3

Hexo Gitalk 评论自动初始化

背景

如果使用 Gitalk 评论插件,需要作者为每篇文章手动操作一下初始化,生成对应文章的issue,才能进行评论。

偷懒的程序员当然不喜欢这么繁琐的流程,所以需要一个自动化工具

自动化实现流程

执行效果

具体代码

https://github.com/attson/hexo-gitalk-init

  • 无需安装其他的依赖,让你的hexo项目更干净
  • 不需要依赖或修改sitemap
  • 更适合自动化
  • 代码强迫症福音 no any warning
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448

const fs = require('fs');
const path = require('path');
const readline = require('readline');
const https = require('https');

let config = {}

if (fs.existsSync(path.join(__dirname, 'gitalk_init.json'))) {
config = JSON.parse(fs.readFileSync(path.join(__dirname, 'gitalk_init.json')).toString('utf-8'))

Object.keys(config).forEach(key => {
const value = config[key];

const reg = /{process\.env\.[a-zA-Z_\-}]*/gm

value.match(reg).forEach(match => {
config[key].replace(match, process.env[match.substring(13, match.length - 1)])
})
})
} else {
// 配置信息
config = {
// GitHub repository 所有者,可以是个人或者组织。对应Gitalk配置中的owner
username: process.env.GITHUB_REPOSITORY_OWNER,

// 储存评论issue的github仓库名,仅需要仓库名字即可。对应 Gitalk配置中的repo
repo: process.env.GITALK_INIT_REPO,

// 从 GitHub 的 Personal access tokens 页面,点击 Generate new token
token: process.env.GITALK_TOKEN,

// 是否启用缓存,启用缓存会将已经初始化的数据写入配置的 outputCacheFile 文件,下一次直接通过缓存文件 outputCacheFile 判断
enableCache: process.env.GITALK_INIT_CACHE || true,
// 缓存文件输出的位置
cacheFile: process.env.GITALK_INIT_CACHE_FILE || path.join(__dirname, './public/gitalk-init-cache.json'),

// 只用于获取缓存的来源,缓存仍然会写到 cacheFile. 读取优先级 cacheFile > cacheRemote. 故cacheFile文件存在时,忽略 cacheRemote
cacheRemote: process.env.GITALK_INIT_CACHE_REMOTE,
// 通过远程读取文件,这样就不需要在本地的博客源文件中保存(保存在静态站点的public中)
// output 到 public 目的就是将文件放在静态站点里面,下一次构建时,可以从远程读取

postsDir: process.env.GITALK_INIT_POSTS_DIR || 'source/_posts'
};
}

function configInit(config) {
if (config.repo === undefined) {
config.repo = `${config.username}.github.io`
}

if (config.cacheRemote === undefined) {
config.cacheRemote = `https://${config.repo}/gitalk-init-cache.json`
}
}

configInit(config)

const hostname = 'api.github.com'
const apiPath = '/repos/' + config.username + '/' + config.repo + '/issues';

const autoGitalkInit = {
gitalkCache: null,
gitalkIdGenerator: null,
getFiles (dir, files_) {
files_ = files_ || [];
const files = fs.readdirSync(dir);
for (let i in files) {
let name = dir + '/' + files[i];
if (fs.statSync(name).isDirectory()) {
this.getFiles(name, files_);
} else {
if (name.endsWith('.md')) {
files_.push(name);
}
}
}
return files_;
},
async readItem(file) {
const fileStream = fs.createReadStream(file);

const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity,
});
// Note: we use the crlfDelay option to recognize all instances of CR LF
// ('\r\n') in input.txt as a single line break.

let start = false;

let post = {};

for await (const line of rl) {
if (start === true) {
if (line.trim() === '---') {
break
} else {
const items = line.split(':')
if (['title', 'desc', 'date', 'comment'].indexOf(items[0].trim()) !== -1) {
post[items[0].trim()] = items[1].trim()
}
}
} else {
if (line.trim() === '---') {
start = true
}
}
}

fileStream.close()

if (Object.keys(post).length === 0) {
console.log(`gitalk: warn read empty from: ${file}`);

return null
}
if (post['comment'] === false || post['comment'] === 'false') {
console.log(`gitalk: ignore by comment = ${post['comment']} : ${file}`);
return null
}

if (!('title' in post)) {
console.log(`gitalk: ignore because the title miss: ${file}`);
return null
}

if (!('date' in post)) {
console.log(`gitalk: ignore because the date miss: ${file}`);
return null
}

const regex = /^\d{4}-\d{2}-\d{2} \d{2}$/gm;

if (!(regex.test(post['date']))) {
console.log(`gitalk: ignore because the date ${post['date']} invalid: ${file}`);
return false;
}

// pathname /year/month/day/file_without_extend/
post['pathname'] = '/' + post['date'].substring(0, 10).replace(/[-|\s]/g, '/') + `/${path.basename(file, '.md')}/`
post['desc'] = post['title']

return post
},

async readPosts(dir) {
const posts = [];
for (let file of this.getFiles(dir)) {
const post = await this.readItem(file);
if (post != null) {
posts.push(post)
}
}

return posts
},

// 调用github接口初始化
gitalkInitInvoke({pathname, id, title, desc}) {
const options = {
'method': 'POST',
'hostname': hostname,
'path': apiPath,
'headers': {
'Authorization': 'token ' + config.token,
'Content-Type': 'application/json',
'User-Agent': config.username + '/' + config.repo,
},
'maxRedirects': 20
};

const link = `https://${config.repo}${pathname}`

//创建issue
const reqBody = {
'title': title,
'labels': ['Gitalk', id],
'body': `[${link}](${link}})\r\n\r\n${desc}`
};

return new Promise(resolve => {
let req = https.request(options, function (res) {
const chunks = [];

res.on('data', function (chunk) {
chunks.push(chunk);
});

res.on('end', function () {
console.log(Buffer.concat(chunks).toString())

return resolve([false, true]);
});

res.on('error', function (error) {
return resolve([error, false]);
});
});

req.write(JSON.stringify(reqBody))

req.end();
})
},

/**
* 通过github api 请求判断是否已经初始化
* @param {string} id gitalk 初始化的id
* @return {Promise<[boolean, boolean]>} 第一个值表示是否出错,第二个值 false 表示没初始化, true 表示已经初始化
*/
getIsInitByGitHub (id) {
const options = {
'method': 'GET',
'hostname': hostname,
'path': apiPath + '?labels=Gitalk,' + id,
'headers': {
'Authorization': 'token ' + config.token,
'Accept': 'application/json',
// https://docs.github.com/en/rest/overview/resources-in-the-rest-api?apiVersion=2022-11-28#user-agent-required
'User-Agent': config.username + '/' + config.repo,
},
'maxRedirects': 20
};

return new Promise((resolve) => {
const req = https.request(options, function (res) {
const chunks = [];

res.on('data', function (chunk) {
chunks.push(chunk);
});

res.on('end', function () {
const res = JSON.parse(Buffer.concat(chunks).toString());
if (res.length > 0) {
return resolve([false, true]);
} else {
return resolve([false, false]);
}
});

res.on('error', function (error) {
return resolve([error, false]);
});
});

req.end();
})
},

// 根据缓存,判断链接是否已经初始化
// 第一个值表示是否出错,第二个值 false 表示没初始化, true 表示已经初始化
async idIsInit (id) {
if (!config.enableCache) {
return this.getIsInitByGitHub(id);
}
// 如果通过缓存查询到的数据是未初始化,则再通过请求判断是否已经初始化,防止多次初始化

const cacheRes = await this.getIsInitByCache(id)
if (cacheRes === false) {
console.log(id + ' 缓存不存在, 从github获取状态...')

return this.getIsInitByGitHub(id);
}
return [false, true];
},

/**
* 通过远程地址获取缓存内容
* @returns {Promise<Object>}
*/
getRemoteCache() {
return new Promise((resolve, reject) => {
const req = https.get(config.cacheRemote, function (res) {
const chunks = [];

res.on('data', function (chunk) {
chunks.push(chunk);
});

res.on('end', function () {
return resolve(JSON.parse(Buffer.concat(chunks).toString()));
});

res.on('error', function (error) {
return reject(error);
});
});

req.end();
})
},
/**
* 通过缓存判断是否已经初始化, 优先加载缓存文件,文件不存在则尝试从 cacheRemote 获取
* @param {string} gitalkId 初始化的id
* @return {Promise<boolean>} false 表示没初始化, true 表示已经初始化
*/
async getIsInitByCache(gitalkId){
if (this.gitalkCache === null) {
// 判断缓存文件是否存在
this.gitalkCache = false;
try {
this.gitalkCache = JSON.parse(fs.readFileSync(config.cacheFile).toString('utf-8'));

console.log('读取缓存文件成功 ' + config.cacheFile)
} catch (e) {
console.log('读取缓存文件失败 ' + config.cacheFile + ' : ' + e.message)

if (config.cacheRemote) {
console.log('正在从 ' + config.cacheRemote + ' 读取文件')
try {
this.gitalkCache = await this.getRemoteCache()
console.log('读取缓存文件成功 ' + config.cacheRemote)
} catch (e) {
console.log('读取缓存文件失败 ' + config.cacheRemote + ' : ' + e.message)
}
}
}
}

const that = this

return Promise.resolve(function (gitalkId) {
if (!that.gitalkCache) {
return false;
}
return !!that.gitalkCache.find(({id: itemId}) => (itemId === gitalkId));
}(gitalkId));
},

/**
* 写入内容
* @param {string} fileName 文件名
* @param {string} content 内容
* @param flag
*/
async write(fileName, content, flag = 'w+') {
return new Promise((resolve) => {
fs.open(fileName, flag, function (err, fd) {
if (err) {
resolve([err, false]);
return;
}
fs.writeFile(fd, content, function (err) {
if (err) {
resolve([err, false]);
return;
}
fs.close(fd, (err) => {
if (err) {
resolve([err, false]);
}
});
resolve([false, true]);
});
});
});
},
// 生成 GitalkId
getGitalkId(pathname, title, desc, date) {
if (this.gitalkIdGenerator == null) {
if (fs.existsSync("get-gitalk-id.js")) {
this.gitalkIdGenerator = require(path.join(__dirname, "get-gitalk-id.js")).getGitalkId
} else {
this.gitalkIdGenerator = function (pathname) {
let id = pathname

// github issue label max 50
if (id.length > 50) {
id = id.substring(0, 50 - 3) + '...'
}

return id
}
}
}

return this.gitalkIdGenerator(pathname, title, desc, date)
},
async start(postDir) {
const posts = await this.readPosts(postDir);
// 报错的数据
const errorData = [];
// 已经初始化的数据
const initializedData = [];
// 成功初始化数据
const successData = [];
for (const item of posts) {
const {pathname, title, desc, date} = item;
const id = this.getGitalkId(pathname, title, desc, date);
const [err, res] = await this.idIsInit(id);
if (err) {
console.log(`Error: 查询评论异常 [ ${title} ] , 信息:`, err || '无');
errorData.push({
...item,
info: '查询评论异常',
});
continue;
}
if (res === true) {
console.log(`--- Gitalk 已经初始化 --- [ ${title} ] `);
initializedData.push({id});
continue;
}
console.log(`Gitalk 初始化开始... [ ${title} ] `);
const [e, r] = await this.gitalkInitInvoke({
id,
pathname,
title,
desc
});
if (e || !r) {
console.log(`Error: Gitalk 初始化异常 [ ${title} ] , 信息:`, e || '无');
errorData.push({
...item,
info: '初始化异常',
});
continue;
}
successData.push({
id,
});
console.log(`Gitalk 初始化成功! [ ${title} ] `);
}

console.log(''); // 空输出,用于换行
console.log('--------- 运行结果 ---------');
console.log(''); // 空输出,用于换行

if (errorData.length !== 0) {
console.log(`报错数据: ${errorData.length} 条。`);
console.log(JSON.stringify(errorData, null, 2))
}

console.log(`本次成功: ${successData.length} 条。`);

// 写入缓存
if (config.enableCache) {
console.log(`写入缓存: ${(initializedData.length + successData.length)} 条,已初始化 ${initializedData.length} 条,本次成功: ${successData.length} 条。参考文件 ${config.cacheFile}。`);
await this.write(config.cacheFile, JSON.stringify(initializedData.concat(successData), null, 2));
} else {
console.log(`已初始化: ${initializedData.length} 条。`);
}
},
}

autoGitalkInit.start(config.postsDir).then(() => console.log('end'));

使用方式

手动执行

执行本地文件

  1. 在项目根目录新增js文件 gitalk_init.js
  2. 执行命令
1
GITHUB_REPOSITORY_OWNER=attson GITALK_TOKEN=<GITALK_TOKEN> node gitalk_init.js

或者使用 release 文件

1
GITHUB_REPOSITORY_OWNER=attson GITALK_TOKEN=<GITALK_TOKEN> curl -sL https://raw.githubusercontent.com/attson/hexo-gitalk-init/v1.0.0/gitalk_init.js | node

github workflows 中集成

执行本地文件

1
2
- name: GITALK_INIT
run: GITALK_TOKEN=${{ secrets.BUILD_GITHUB_IO_GITALK }} node gitalk_init.js

或者使用 release 文件

ci 中使用,推荐增加 md5 值校验

1
2
3
4
5
6
7
8
- name: GITALK_INIT
run: |
if [[ $(wget https://raw.githubusercontent.com/attson/hexo-gitalk-init/v1.0.2/gitalk_init.js && cat gitalk_init.js | md5sum | cut -d ' ' -f 1) = "dec43e4fe531f8006bd0606a76a87973" ]]; then
GITALK_TOKEN=${{ secrets.BUILD_GITHUB_IO_GITALK }} node gitalk_init.js
else
echo "check md5 fail."
exit 1
fi

参数说明

字段 说明 默认值(env存在,则默认使用env的值) 说明
username GitHub repository 所有者 (必填) process.env.GITHUB_REPOSITORY_OWNER GitHub repository 所有者,可以是个人或者组织。对应Gitalk配置中的owner
repo 储存评论issue的github仓库名 process.env.GITALK_INIT_REPO
|| ${this.username}.github.io
储存评论issue的github仓库名,仅需要仓库名字即可。对应 Gitalk配置中的repo
token GitHub 的 Personal access token (必填) process.env.GITALK_TOKEN 从 GitHub 的 Personal access tokens 页面,点击 Generate new token
enableCache 是否启用缓存 process.env.GITALK_INIT_CACHE || true 是否启用缓存,启用缓存会将已经初始化的数据写入配置的 outputCacheFile 文件,下一次直接通过缓存文件 outputCacheFile 判断
cacheFile 缓存文件输出的位置 process.env.GITALK_INIT_CACHE_FILE
|| path.join(__dirname, ‘./public/gitalk-init-cache.json’)
cacheRemote 获取缓存的远程地址 process.env.GITALK_INIT_CACHE_REMOTE
|| https://${this.repo}/gitalk-init-cache.json
只用于获取缓存的来源,缓存仍然会写到 cacheFile. 读取优先级 cacheFile > cacheRemote. 故cacheFile文件存在时,忽略 cacheRemote
postsDir hexo posts 文件路径 process.env.GITALK_INIT_POSTS_DIR
|| ‘source/_posts’
  1. 所有参数支持使用环境变量配置 (推荐)
  2. 所有参数支持使用自定义的 gitalk_init.json 文件
    • 配置文件中value支持环境变量占位
1
2
3
4
{
"username": "attson",
"token": "{{process.env.GITALK_TOKEN}}"
}
  • 标题: Hexo Gitalk 评论自动初始化
  • 作者: Attson
  • 创建于 : 2023-01-10 21:22:21
  • 更新于 : 2023-10-18 16:13:23
  • 链接: https://attson.github.io/p/gitalk-init.html
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
 评论