-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
252 lines (211 loc) · 8.04 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
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
'use strict';
/* eslint no-console: ["error", { allow: ["warn", "error"] }] */
const lintLib = require('@commitlint/lint');
const defaultConfig = require('@commitlint/config-conventional');
const core = require('@actions/core');
const github = require('@actions/github');
const fs = require('fs');
const path = require('path');
const moment = require('moment');
const lint = lintLib.default;
const defaultConfigRules = defaultConfig.rules;
const validEvent = ['pull_request'];
async function run() {
try {
const token = core.getInput('token', { required: true });
const createComment = core.getBooleanInput('comment');
const deleteComment = core.getBooleanInput('delete_comment');
// load rules from file, if there
const configPath = core.getInput('config_path', { required: true });
// relative to dist/index.js
const filename = path.join(__dirname, '/../', configPath);
core.debug(`Loading config from path: ${filename}`);
const config = fs.existsSync(filename) ? JSON.parse(fs.readFileSync(filename, 'utf8')) : {};
core.debug(`Loaded config is: ${JSON.stringify(config)}`);
const fileRules = config.rules || {};
// load raw rules from action, if there
const rulesRaw = core.getInput('rules');
const yamlRules = rulesRaw ? JSON.parse(rulesRaw) : {};
core.debug(`Default rules: ${JSON.stringify(defaultConfigRules)}`);
core.debug(`File rules: ${JSON.stringify(fileRules)}`);
core.debug(`Yaml rules: ${JSON.stringify(yamlRules)}`);
const ruleSet = {
...defaultConfigRules,
...fileRules,
...yamlRules,
};
core.debug(`Final rules: ${JSON.stringify(ruleSet)}`);
const octokit = new github.getOctokit(token);
const {
eventName,
payload: {
repository: repo,
pull_request: pr,
},
issue: {
number: num,
},
repo: {
owner,
},
} = github.context;
core.debug(`Context ---- payload.repository: ${JSON.stringify(repo)}`);
core.debug(`Context ---- payload.pull_request: ${JSON.stringify(pr)}`);
core.debug(`Context ---- issue.number: ${JSON.stringify(num)}`);
core.debug(`Context ---- repo.owner: ${JSON.stringify(owner)}`);
if (validEvent.indexOf(eventName) < 0) {
core.error(`Invalid event: ${eventName}`);
return;
}
core.debug(`Fetching commits for PR #${num}...`);
const commits = await octokit.rest.pulls.listCommits({
owner: repo.owner.login,
repo: repo.name,
pull_number: pr.number,
});
core.debug(`Processing ${commits.data.length} commits...`);
const reports = await Promise.all(commits.data.map(commit => lint(commit.commit.message, ruleSet)));
core.debug(`Report results: ${JSON.stringify(reports)}`);
let countErrors = 0;
let countWarnings = 0;
const authors = [];
const commitReports = [];
reports.forEach((report, i) => {
const meta = commits.data[i];
const { sha, commit } = meta;
if (!authors.includes(commit.author.name)) {
authors.push(commit.author.name);
}
const shaShort = sha.substring(0, 7);
const relativeTime = moment(commit.author.date).fromNow();
core.debug(` Commit ${shaShort}`);
const msg = `Commit "${commit.message}" ${shaShort} (${commit.author.name} <${commit.author.email}> on ${commit.author.date})`;
core.startGroup(msg);
core.debug(msg);
if (!meta.committer) {
core.warning(`Commit "${commit.message}" ${shaShort} has no committer in metadata.`);
}
// handle missing committer due to deleted account, etc.
const commiterInfo = meta.committer ?
`By **[${commit.author.name} (${meta.committer.login})](https://github.com/${meta.committer.login})** _${relativeTime}_` :
`By **${commit.author.name} (Unknown Login) _${relativeTime}_`;
const headerIcon = report.valid ? '✅' :
report.errors.length ? '❌' : '⚠️';
let commitReportText = `
### ${headerIcon} [Commit ${shaShort}](https://github.com/${owner}/${repo.name}/commit/${sha})
${commiterInfo}
\`\`\`
${commit.message}
\`\`\`
`;
if (!report.valid) {
let errorReportText = '';
report.errors.forEach((err) => {
const ruleDef = ruleSet[err.name];
core.error(`Rule '${err.name}': ${err.message} ("${commit.message}")`);
countErrors++;
errorReportText += `
❌ **ERROR**: ${err.message}
> ["${err.name}"](https://github.com/conventional-changelog/commitlint/blob/master/docs/reference-rules.md#${err.name}): ${JSON.stringify(ruleDef)}
`;
});
let warningReportText = '';
report.warnings.forEach((err) => {
const ruleDef = ruleSet[err.name];
core.warning(`Rule '${err.name}': ${err.message} ("${commit.message}")`);
countWarnings++;
warningReportText += `
⚠️ **Warning**: ${err.message}
> ["${err.name}"](https://github.com/conventional-changelog/commitlint/blob/master/docs/reference-rules.md#${err.name}): ${JSON.stringify(ruleDef)}
`;
});
commitReportText += `
${errorReportText}
${warningReportText}
`;
}
commitReports.push(commitReportText);
core.endGroup();
});
if (countErrors) {
core.setFailed(`Action failed with ${countErrors} errors (and ${countWarnings} warnings)`);
}
if (deleteComment) {
const perPage = 100;
let page = 1;
let hasMore = true;
do {
core.debug(`Fetching page #${page} (max: ${perPage}) of existing comments...`);
const res = await octokit.rest.issues.listComments({
owner,
repo: repo.name,
issue_number: num,
per_page: 100,
page,
});
const relevantComments = res.data.filter(comment => comment.body.includes('## Commit Message Lint Report'));
core.debug(`Fetched ${relevantComments.length} relevant (previous lint report) comments...`);
for (let i = 0; i < relevantComments.length; i++) {
core.debug(`Deleting comment #${relevantComments[i].id}...`);
await octokit.rest.issues.deleteComment({
owner,
repo: repo.name,
comment_id: relevantComments[i].id,
});
}
page++;
if (res.data.length < perPage) {
hasMore = false;
}
} while (hasMore);
}
if (createComment) {
if (countErrors || countWarnings) {
const finalReport = `
# 🚨🚔 Unconventional Commit 👮♀️🙅♂️
🤖 Beep boop! Looks like one or more of your commit messages wasn't quite right.
## Commit Message Lint Report
- ✏️ **${commits.data.length} commit(s)**
- 👤 **${authors.length} author(s)**
- ❌ **${countErrors} lint error(s)**
- ⚠️ **${countWarnings} lint warning(s)**
${commitReports.join('\n')}
## Tips
Be sure to follow the [Conventional Commit](https://www.conventionalcommits.org/en/v1.0.0/) guideline when authoring your commits.
If your most recent commit is to blame, you can edit a single commit with:
\`\`\`
git commit --amend
\`\`\`
To edit & merge multiple commits, you can rebase with \`git rebase -i master\` (be sure your master is up to date).
`;
await octokit.rest.issues.createComment({
owner,
repo: repo.name,
issue_number: num,
body: finalReport,
});
} else {
const finalReport = `
# ✅🙏🏻 Conventional Commit 🥳 🎉
🤖 Beep boop! Congrats, it like all your commit messages conform to the [Conventional Commit](https://www.conventionalcommits.org/en/v1.0.0/) spec! 👏👏👏
Your PR can be closed. Coffee is for closers, so here's a coffee for you: ☕️
## Commit Message Lint Report
- ✏️ **${commits.data.length} commit(s)**
- 👤 **${authors.length} author(s)**
- ❌ **${countErrors} lint error(s)**
- ⚠️ **${countWarnings} lint warning(s)**
`;
await octokit.rest.issues.createComment({
owner,
repo: repo.name,
issue_number: num,
body: finalReport,
});
}
}
} catch (err) {
console.error(err);
core.setFailed(err.message);
}
}
run();