-
Notifications
You must be signed in to change notification settings - Fork 64
/
action.js
339 lines (313 loc) · 9.97 KB
/
action.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
const core = require("@actions/core");
const github = require("@actions/github");
const { escapeMarkdown } = require("./utils");
const { processCoverage } = require("./cobertura");
const client = new github.getOctokit(
core.getInput("repo_token", { required: true }),
);
const credits = "Generated by :monkey: cobertura-action";
async function action(payload) {
const { pullRequestNumber, commit } = await pullRequestInfo(payload);
if (!commit) {
core.error("Found no commit.");
return;
}
const path = core.getInput("path", { required: true });
const skipCovered = JSON.parse(
core.getInput("skip_covered", { required: true }),
);
const showLine = JSON.parse(core.getInput("show_line", { required: true }));
const showBranch = JSON.parse(
core.getInput("show_branch", { required: true }),
);
const minimumCoverage = parseInt(
core.getInput("minimum_coverage", { required: true }),
);
const failBelowThreshold = JSON.parse(
core.getInput("fail_below_threshold", { required: false }) || "false",
);
const showClassNames = JSON.parse(
core.getInput("show_class_names", { required: true }),
);
const showMissing = JSON.parse(
core.getInput("show_missing", { required: true }),
);
let showMissingMaxLength = core.getInput("show_missing_max_length", {
required: false,
});
showMissingMaxLength = showMissingMaxLength
? parseInt(showMissingMaxLength)
: -1;
const linkMissingLines = JSON.parse(
core.getInput("link_missing_lines", { required: false }) || "false",
);
const linkMissingLinesSourceDir =
core.getInput("link_missing_lines_source_dir", { required: false }) || null;
const onlyChangedFiles = JSON.parse(
core.getInput("only_changed_files", { required: true }),
);
const reportName = core.getInput("report_name", { required: false });
const changedFiles = onlyChangedFiles
? await listChangedFiles(pullRequestNumber)
: null;
const reports = await processCoverage(path, { skipCovered });
const comment = markdownReport(reports, commit, {
minimumCoverage,
showLine,
showBranch,
showClassNames,
showMissing,
showMissingMaxLength,
linkMissingLines,
linkMissingLinesSourceDir,
filteredFiles: changedFiles,
reportName,
});
const belowThreshold = reports.some(
(report) => Math.floor(report.total) < minimumCoverage,
);
if (pullRequestNumber) {
await addComment(pullRequestNumber, comment, reportName);
}
await addCheck(
comment,
reportName,
commit,
failBelowThreshold ? (belowThreshold ? "failure" : "success") : "neutral",
);
if (failBelowThreshold && belowThreshold) {
core.setFailed("Minimum coverage requirement was not satisfied");
}
}
function formatFileUrl(sourceDir, fileName, commit) {
const repo = github.context.repo;
sourceDir = sourceDir ? sourceDir : "";
// Strip leading and trailing slashes.
sourceDir = sourceDir.replace(/\/$/, "").replace(/^\//, "");
const path = (sourceDir ? `${sourceDir}/` : "") + fileName;
const githubUrl = process.env["GITHUB_SERVER_URL"] || "https://github.com";
return `${githubUrl}/${repo.owner}/${repo.repo}/blob/${commit}/${path}`;
}
function formatRangeText([start, end]) {
return `${start}` + (start === end ? "" : `-${end}`);
}
function tickWrap(string) {
return "`" + string + "`";
}
function cropRangeList(separator, showMissingMaxLength, ranges) {
if (showMissingMaxLength <= 0) return [ranges, false];
let accumulatedJoin = "";
for (const [index, range] of ranges.entries()) {
accumulatedJoin += `${separator}${range}`;
if (index === 0) continue;
if (accumulatedJoin.length > showMissingMaxLength)
return [ranges.slice(0, index), true];
}
return [ranges, false];
}
function linkRange(fileUrl, range) {
const [start, end] = range.slice(1, -1).split("-", 2);
const rangeReference = `L${start}` + (end ? `-L${end}` : "");
// Insert plain=1 to disabled rendered views.
const url = `${fileUrl}?plain=1#${rangeReference}`;
return `[${range}](${url})`;
}
function formatMissingLines(
fileUrl,
lineRanges,
showMissingMaxLength,
showMissingLineLinks,
) {
const formatted = lineRanges.map(formatRangeText);
const separator = " ";
// Apply cropping before inserting ticks and linking, so that only non-syntax
// characters are counted.
const [cropped, isCropped] = cropRangeList(
separator,
showMissingMaxLength,
formatted,
);
const wrapped = cropped.map(tickWrap);
const linked = showMissingLineLinks
? wrapped.map((range) => linkRange(fileUrl, range))
: wrapped;
const joined = linked.join(separator) + (isCropped ? " …" : "");
return joined || " ";
}
function markdownReport(reports, commit, options) {
const {
minimumCoverage = 100,
showLine = false,
showBranch = false,
showClassNames = false,
showMissing = false,
showMissingMaxLength = -1,
linkMissingLines = false,
linkMissingLinesSourceDir = null,
filteredFiles = null,
reportName = "Coverage Report",
} = options || {};
const status = (total) =>
total >= minimumCoverage ? ":white_check_mark:" : ":x:";
// Setup files
const files = [];
let output = "";
for (const report of reports) {
const folder = reports.length <= 1 ? "" : ` ${report.folder}`;
for (const file of report.files.filter(
(file) => filteredFiles == null || filteredFiles.includes(file.filename),
)) {
const fileTotal = Math.floor(file.total);
const fileLines = Math.floor(file.line);
const fileBranch = Math.floor(file.branch);
files.push([
escapeMarkdown(showClassNames ? file.name : file.filename),
`\`${fileTotal}%\``,
showLine ? `\`${fileLines}%\`` : undefined,
showBranch ? `\`${fileBranch}%\`` : undefined,
status(fileTotal),
showMissing && file.missing
? formatMissingLines(
formatFileUrl(linkMissingLinesSourceDir, file.filename, commit),
file.missing,
showMissingMaxLength,
linkMissingLines,
)
: undefined,
]);
}
// Construct table
/*
| File | Coverage | |
|---------------|:--------:|:------------------:|
| **All files** | `78%` | :x: |
| foo.py | `80%` | :white_check_mark: |
| bar.py | `75%` | :x: |
_Minimum allowed coverage is `80%`_
*/
const total = Math.floor(report.total);
const linesTotal = Math.floor(report.line);
const branchTotal = Math.floor(report.branch);
const table = [
[
"File",
"Coverage",
showLine ? "Lines" : undefined,
showBranch ? "Branches" : undefined,
" ",
showMissing ? "Missing" : undefined,
],
[
"-",
":-:",
showLine ? ":-:" : undefined,
showBranch ? ":-:" : undefined,
":-:",
showMissing ? ":-:" : undefined,
],
[
"**All files**",
`\`${total}%\``,
showLine ? `\`${linesTotal}%\`` : undefined,
showBranch ? `\`${branchTotal}%\`` : undefined,
status(total),
showMissing ? " " : undefined,
],
...files,
]
.map((row) => {
return `| ${row.filter(Boolean).join(" | ")} |`;
})
.join("\n");
const titleText = `<strong>${reportName}${folder}</strong>`;
output += `${titleText}\n\n${table}\n\n`;
}
const minimumCoverageText = `_Minimum allowed coverage is \`${minimumCoverage}%\`_`;
const footerText = `<p align="right">${credits} against ${commit} </p>`;
output += `${minimumCoverageText}\n\n${footerText}`;
return output;
}
async function addComment(pullRequestNumber, body, reportName) {
const comments = await client.rest.issues.listComments({
issue_number: pullRequestNumber,
...github.context.repo,
});
const commentFilter = reportName ? reportName : credits;
const comment = comments.data.find((comment) =>
comment.body.includes(commentFilter),
);
if (comment != null) {
await client.rest.issues.updateComment({
comment_id: comment.id,
body: body,
...github.context.repo,
});
} else {
await client.rest.issues.createComment({
issue_number: pullRequestNumber,
body: body,
...github.context.repo,
});
}
}
async function addCheck(body, reportName, sha, conclusion) {
const checkName = reportName ? reportName : "coverage";
await client.rest.checks.create({
name: checkName,
head_sha: sha,
status: "completed",
conclusion: conclusion,
output: {
title: checkName,
summary: body,
},
...github.context.repo,
});
}
async function listChangedFiles(pullRequestNumber) {
const files = await client.rest.pulls.listFiles({
pull_number: pullRequestNumber,
...github.context.repo,
});
return files.data.map((file) => file.filename);
}
async function pullRequestInfo(payload = {}) {
let commit = null;
let pullRequestNumber = core.getInput("pull_request_number", {
required: false,
});
if (pullRequestNumber) {
// Use the supplied PR
pullRequestNumber = parseInt(pullRequestNumber);
const { data } = await client.rest.pulls.get({
pull_number: pullRequestNumber,
...github.context.repo,
});
commit = data.head.sha;
} else if (payload.workflow_run) {
// Fetch all open PRs and match the commit hash.
commit = payload.workflow_run.head_commit.id;
const { data } = await client.rest.pulls.list({
...github.context.repo,
state: "open",
});
pullRequestNumber = data
.filter((d) => d.head.sha === commit)
.reduce((n, d) => d.number, "");
} else if (payload.pull_request) {
// Try to find the PR from payload
const { pull_request: pullRequest } = payload;
pullRequestNumber = pullRequest.number;
commit = pullRequest.head.sha;
} else if (payload.after) {
commit = payload.after;
}
return { pullRequestNumber, commit };
}
module.exports = {
action,
markdownReport,
addComment,
addCheck,
listChangedFiles,
};