/
index.js
100 lines (92 loc) · 2.31 KB
/
index.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
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
const core = require('@actions/core')
const github = require('@actions/github')
const fs = require('fs')
const { readFile } = fs.promises
const { parser } = require('@conventional-commits/parser')
const api = module.exports = {
addLabels,
isPullRequest,
main,
removeLabels
}
async function main () {
const { visit } = await import('unist-util-visit')
const labelMap = JSON.parse(core.getInput('type_labels'))
if (!process.env.GITHUB_EVENT_PATH) {
console.warn('no event payload found')
return
}
const payload = JSON.parse(
await readFile(process.env.GITHUB_EVENT_PATH, 'utf8')
)
if (!api.isPullRequest(payload)) {
console.info('skipping non pull_request')
}
let titleAst
try {
titleAst = parser(payload.pull_request.title)
} catch (err) {
console.warn(err.message)
return
}
const cc = {
breaking: false
}
// <type>, "(", <scope>, ")", ["!"], ":", <whitespace>*, <text>
visit(titleAst, (node) => {
switch (node.type) {
case 'type':
cc.type = node.value
break
case 'scope':
cc.scope = node.value
break
case 'breaking-change':
cc.breaking = true
break
default:
break
}
})
const labels = []
if (cc.breaking) labels.push(labelMap.breaking)
if (labelMap[cc.type]) labels.push(labelMap[cc.type])
if (labels.length) {
await api.removeLabels(Object.values(labelMap), payload)
await api.addLabels(labels, payload)
}
}
function isPullRequest (payload) {
return !!payload.pull_request
}
async function addLabels (labels, payload) {
const octokit = getOctokit()
await octokit.rest.issues.addLabels({
owner: payload.repository.owner.login,
repo: payload.repository.name,
issue_number: payload.pull_request.number,
labels
})
}
async function removeLabels (labels, payload) {
const octokit = getOctokit()
await octokit.rest.issues.removeLabels({
owner: payload.repository.owner.login,
repo: payload.repository.name,
issue_number: payload.pull_request.number,
labels
})
}
let cachedOctokit
function getOctokit () {
if (!cachedOctokit) {
const token = core.getInput('token')
const octokit = github.getOctokit(token)
cachedOctokit = octokit
}
return cachedOctokit
}
main()
.catch((err) => {
core.setFailed(err.message)
})