-
-
Notifications
You must be signed in to change notification settings - Fork 52
/
index.js
354 lines (317 loc) · 10.8 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
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
const core = require('@actions/core');
const github = require('@actions/github');
const { getCoverageReport } = require('./parse');
const { getCoverageXmlReport } = require('./parseXml');
const {
getSummaryReport,
getParsedXml,
getNotSuccessTest,
} = require('./junitXml');
const { getMultipleReport } = require('./multiFiles');
const MAX_COMMENT_LENGTH = 65536;
const FILE_STATUSES = Object.freeze({
ADDED: 'added',
MODIFIED: 'modified',
REMOVED: 'removed',
RENAMED: 'renamed',
});
const main = async () => {
const token = core.getInput('github-token', { required: true });
const title = core.getInput('title', { required: false });
const badgeTitle = core.getInput('badge-title', { required: false });
const hideBadge = core.getBooleanInput('hide-badge', { required: false });
const hideReport = core.getBooleanInput('hide-report', { required: false });
const createNewComment = core.getBooleanInput('create-new-comment', {
required: false,
});
const hideComment = core.getBooleanInput('hide-comment', { required: false });
const reportOnlyChangedFiles = core.getBooleanInput(
'report-only-changed-files',
{ required: false }
);
const removeLinkFromBadge = core.getBooleanInput('remove-link-from-badge', {
required: false,
});
const uniqueIdForComment = core.getInput('unique-id-for-comment', {
required: false,
});
const defaultBranch = core.getInput('default-branch', { required: false });
const covFile = core.getInput('pytest-coverage-path', { required: false });
const covXmlFile = core.getInput('pytest-xml-coverage-path', {
required: false,
});
const pathPrefix = core.getInput('coverage-path-prefix', { required: false });
const xmlFile = core.getInput('junitxml-path', { required: false });
const xmlTitle = core.getInput('junitxml-title', { required: false });
const multipleFiles = core.getMultilineInput('multiple-files', {
required: false,
});
const { context, repository } = github;
const { repo, owner } = context.repo;
const { eventName, payload } = context;
const watermarkUniqueId = uniqueIdForComment
? `| ${uniqueIdForComment} `
: '';
const WATERMARK = `<!-- Pytest Coverage Comment: ${context.job} ${watermarkUniqueId}-->\n`;
let finalHtml = '';
const options = {
token,
repository: repository || `${owner}/${repo}`,
prefix: `${process.env.GITHUB_WORKSPACE}/`,
pathPrefix,
covFile,
covXmlFile,
xmlFile,
title,
badgeTitle,
hideBadge,
hideReport,
createNewComment,
hideComment,
reportOnlyChangedFiles,
removeLinkFromBadge,
defaultBranch,
xmlTitle,
multipleFiles,
};
options.repoUrl =
payload.repository?.html_url || `https://github.com/${options.repository}`;
if (eventName === 'pull_request') {
options.commit = payload.pull_request.head.sha;
options.head = payload.pull_request.head.ref;
options.base = payload.pull_request.base.ref;
} else if (eventName === 'push') {
options.commit = payload.after;
options.head = context.ref;
}
if (options.reportOnlyChangedFiles) {
const changedFiles = await getChangedFiles(options);
options.changedFiles = changedFiles;
// when github event come different from `pull_request` or `push`
if (!changedFiles) {
options.reportOnlyChangedFiles = false;
}
}
let report = options.covXmlFile
? getCoverageXmlReport(options)
: getCoverageReport(options);
const { coverage, color, html, warnings } = report;
const summaryReport = getSummaryReport(options);
if (summaryReport && summaryReport.html) {
core.setOutput('coverageHtml', summaryReport.html);
}
if (html) {
const newOptions = { ...options, commit: defaultBranch };
const output = getCoverageReport(newOptions);
core.setOutput('coverageHtml', output.html);
}
// set to output junitxml values
if (summaryReport) {
const parsedXml = getParsedXml(options);
const { errors, failures, skipped, tests, time } = parsedXml;
const valuesToExport = { errors, failures, skipped, tests, time };
Object.entries(valuesToExport).forEach(([key, value]) => {
core.info(`${key}: ${value}`);
core.setOutput(key, value);
});
const notSuccessTestInfo = getNotSuccessTest(options);
core.setOutput('notSuccessTestInfo', JSON.stringify(notSuccessTestInfo));
core.setOutput('summaryReport', JSON.stringify(summaryReport));
}
let multipleFilesHtml = '';
if (multipleFiles && multipleFiles.length) {
multipleFilesHtml = `\n\n${getMultipleReport(options)}`;
}
if (
!options.hideReport &&
html.length + summaryReport.length > MAX_COMMENT_LENGTH
) {
// generate new html without report
// prettier-ignore
core.warning(`Your comment is too long (maximum is ${MAX_COMMENT_LENGTH} characters), coverage report will not be added.`);
// prettier-ignore
core.warning(`Try add: "--cov-report=term-missing:skip-covered", or add "hide-report: true", or add "report-only-changed-files: true", or switch to "multiple-files" mode`);
report = getSummaryReport({ ...options, hideReport: true });
}
finalHtml += html;
finalHtml += finalHtml.length ? `\n\n${summaryReport}` : summaryReport;
finalHtml += multipleFilesHtml
? `\n\n${multipleFilesHtml}`
: multipleFilesHtml;
core.setOutput('summaryReport', JSON.stringify(finalHtml));
if (coverage) {
core.startGroup(options.covFile);
core.info(`coverage: ${coverage}`);
core.info(`color: ${color}`);
core.info(`warnings: ${warnings}`);
core.setOutput('coverage', coverage);
core.setOutput('color', color);
core.setOutput('warnings', warnings);
core.endGroup();
}
if (!finalHtml || options.hideComment) {
core.info('Nothing to report');
return;
}
const body = WATERMARK + finalHtml;
const octokit = github.getOctokit(token);
const issue_number = payload.pull_request ? payload.pull_request.number : 0;
if (eventName === 'push') {
core.info('Create commit comment');
await octokit.repos.createCommitComment({
repo,
owner,
commit_sha: options.commit,
body,
});
} else if (eventName === 'pull_request') {
if (createNewComment) {
core.info('Creating a new comment');
await octokit.issues.createComment({
repo,
owner,
issue_number,
body,
});
} else {
// Now decide if we should issue a new comment or edit an old one
const { data: comments } = await octokit.issues.listComments({
repo,
owner,
issue_number,
});
const comment = comments.find(
(c) =>
c.user.login === 'github-actions[bot]' && c.body.startsWith(WATERMARK)
);
if (comment) {
core.info('Founded previous comment, updating');
await octokit.issues.updateComment({
repo,
owner,
comment_id: comment.id,
body,
});
} else {
core.info('No previous comment founded, creating a new one');
await octokit.issues.createComment({
repo,
owner,
issue_number,
body,
});
}
}
} else {
if (!options.hideComment) {
// prettier-ignore
core.warning(`This action supports comments only on \`pull_request\` and \`push\` events. \`${eventName}\` events are not supported.\nYou can use the output of the action.`)
}
}
};
// generate object of all files that changed based on commit through Github API
const getChangedFiles = async (options) => {
try {
const { context } = github;
const { eventName, payload } = context;
const { repo, owner } = context.repo;
const octokit = github.getOctokit(options.token);
// Define the base and head commits to be extracted from the payload
let base, head;
switch (eventName) {
case 'pull_request':
base = payload.pull_request.base.sha;
head = payload.pull_request.head.sha;
break;
case 'push':
base = payload.before;
head = payload.after;
break;
default:
// prettier-ignore
core.warning(`\`report-only-changed-files: true\` supports only on \`pull_request\` and \`push\`, \`${eventName}\` events are not supported.`)
return null;
}
core.startGroup('Changed files');
// Log the base and head commits
core.info(`Base commit: ${base}`);
core.info(`Head commit: ${head}`);
let response = null;
// that is first commit, we cannot get diff
if (base === '0000000000000000000000000000000000000000') {
response = await octokit.rest.repos.getCommit({
owner,
repo,
ref: head,
});
} else {
// https://developer.github.com/v3/repos/commits/#compare-two-commits
response = await octokit.rest.repos.compareCommits({
base,
head,
owner,
repo,
});
}
// Ensure that the request was successful.
if (response.status !== 200) {
core.setFailed(
`The GitHub API for comparing the base and head commits for this ${eventName} event returned ${response.status}, expected 200. ` +
"Please submit an issue on this action's GitHub repo."
);
}
// Get the changed files from the response payload.
const files = response.data.files;
const all = [],
added = [],
modified = [],
removed = [],
renamed = [],
addedModified = [];
for (const file of files) {
const { filename: filenameOriginal, status } = file;
const filename = filenameOriginal.replace(options.pathPrefix, '');
all.push(filename);
switch (status) {
case FILE_STATUSES.ADDED:
added.push(filename);
addedModified.push(filename);
break;
case FILE_STATUSES.MODIFIED:
modified.push(filename);
addedModified.push(filename);
break;
case FILE_STATUSES.REMOVED:
removed.push(filename);
break;
case FILE_STATUSES.RENAMED:
renamed.push(filename);
break;
default:
// prettier-ignore
core.setFailed(`One of your files includes an unsupported file status '${status}', expected ${Object.values(FILE_STATUSES).join(',')}.`);
}
}
core.info(`All: ${all.join(',')}`);
core.info(`Added: ${added.join(', ')}`);
core.info(`Modified: ${modified.join(', ')}`);
core.info(`Removed: ${removed.join(', ')}`);
core.info(`Renamed: ${renamed.join(', ')}`);
core.info(`Added or modified: ${addedModified.join(', ')}`);
core.endGroup();
return {
all: all,
[FILE_STATUSES.ADDED]: added,
[FILE_STATUSES.MODIFIED]: modified,
[FILE_STATUSES.REMOVED]: removed,
[FILE_STATUSES.RENAMED]: renamed,
AddedOrModified: addedModified,
};
} catch (error) {
core.setFailed(error.message);
}
};
main().catch((err) => {
core.error(err);
core.setFailed(err.message);
});