自动创建 Gitalk 关联 Issue

在根目录创建文件夹 scripts,在文件夹中创建文件 gitalk-init.js,内容如下:

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
const axios = require("axios")
const md5 = require("md5")

const options = {
owner: "starudream",
repo: "blog-page",
accessToken: "<<placeholder>>",
labels: "Gitalk,",
}

const axiosGithub = axios.create({
baseURL: "https://api.github.com",
headers: {
"Accept": "application/json",
},
})

const getIssueByLabels = (id) => {
return axiosGithub.get(`/repos/${options.owner}/${options.repo}/issues`, {
headers: {
Authorization: `token ${options.accessToken}`,
},
params: {
labels: options.labels.concat(id),
t: Date.now(),
},
}).then(res => {
if (res && res.data && res.data.length) {
return res.data[0]
}
return null
})
}

const createIssue = (title, body, id) => {
return axiosGithub.post(`/repos/${options.owner}/${options.repo}/issues`, {
title,
labels: options.labels.concat(id).split(","),
body: body,
}, {
headers: {
Authorization: `token ${options.accessToken}`,
},
}).then(res => {
return res.data
})
}

hexo.extend.generator.register("gitalk-init", locals => {
locals.posts.each(post => {
if (post.layout !== "post" || !post.published || !post.comments) return
const title = post.title + " | " + hexo.config.title
const path = "/" + post.path
const hash = md5(path)
getIssueByLabels(hash).then(res => {
if (res) {
console.log(`【${title}】has existed`)
return
}
createIssue(title, post.permalink, hash).then(res => {
console.log(`【${title}】has created`)
})
})
})
})

然后运行 hexo generate --force 即会自动执行 scripts 内脚本文件。