-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathhandler.ts
More file actions
389 lines (352 loc) · 11.8 KB
/
handler.ts
File metadata and controls
389 lines (352 loc) · 11.8 KB
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
import * as core from '@actions/core'
import { context } from '@actions/github'
import {
updateComment,
listComments,
addCommentToIssue,
deleteComment
} from '../client/github'
import { Inputs } from '../types'
import { Report } from '../ctrf/core/types/ctrf'
import { generateViews, annotateFailed } from './core'
import { components } from '@octokit/openapi-types'
import { createCheckRun } from '../client/github/checks'
import { checkReportSize } from '../utils/report-utils'
type IssueComment = components['schemas']['issue-comment']
const UPDATE_EMOJI = '🔄'
/**
* Handles the generation of views and comments for a CTRF report.
*
* - Generates various views of the CTRF report and adds them to the GitHub Actions summary.
* - Adds or updates a comment on the pull request if conditions are met.
* - Writes the summary to the GitHub Actions output if requested.
*
* @param inputs - The user-provided inputs for configuring views and comments.
* @param report - The CTRF report containing test results.
* @returns A promise that resolves when the operations are completed.
*/
export async function handleViewsAndComments(
inputs: Inputs,
report: Report
): Promise<void> {
core.startGroup(`📝 Generating reports`)
const INVISIBLE_MARKER = inputs.commentTag
? `<!-- CTRF PR COMMENT TAG: ${inputs.commentTag} -->`
: `<!-- CTRF PR COMMENT TAG: DEFAULT -->`
generateViews(inputs, report)
core.setOutput('summary', core.summary.stringify())
const { reportJson, isSafeToOutput } = checkReportSize(report, 'report')
if (isSafeToOutput) {
core.setOutput('report', reportJson)
}
if (shouldAddCommentToPullRequest(inputs, report)) {
await postOrUpdatePRComment(inputs, INVISIBLE_MARKER)
}
if (inputs.issue) {
await postOrUpdateIssueComment(inputs, INVISIBLE_MARKER)
}
if (inputs.statusCheck) {
await createStatusCheck(inputs, report)
}
if (inputs.summary && !inputs.pullRequestReport) {
await core.summary.write()
}
core.endGroup()
}
/**
* Determines if a comment should be added to the pull request based on inputs and report data.
*
* @param inputs - The user-provided inputs for configuring pull request comments.
* @param report - The CTRF report containing test results.
* @returns `true` if a comment should be added, otherwise `false`.
*/
export function shouldAddCommentToPullRequest(
inputs: Inputs,
report: Report
): boolean {
const shouldAddComment =
(inputs.onFailOnly && report.results.summary.failed > 0) ||
!inputs.onFailOnly
return (
(inputs.pullRequestReport || inputs.pullRequest) &&
(context.eventName === 'pull_request' ||
context.eventName === 'pull_request_target') &&
shouldAddComment
)
}
/**
* Handles the annotation of failed tests in the CTRF report.
*
* - Annotates all failed tests in the GitHub Actions log if annotation is enabled in inputs.
*
* @param inputs - The user-provided inputs for configuring annotations.
* @param report - The CTRF report containing test results.
*/
export function handleAnnotations(inputs: Inputs, report: Report): void {
if (inputs.annotate) {
core.startGroup(`🔍 Annotating failed tests`)
core.info('Annotating failed tests')
annotateFailed(report)
core.endGroup()
}
}
/**
* Posts or updates a comment on either a PR or Issue.
*
* @param owner - The owner of the repository
* @param repo - The repository name
* @param issue_number - The PR or issue number
* @param body - The comment body to post
* @param marker - The unique marker to identify existing comments
* @param updateConfig - Configuration for update behavior
*/
export async function handleComment(
owner: string,
repo: string,
issue_number: number,
body: string,
marker: string,
updateConfig: {
shouldUpdate: boolean
shouldOverwrite: boolean
alwaysLatestComment: boolean
}
): Promise<void> {
let finalBody = body
const { comment: existingComment, isLatest } =
await findExistingMarkedComment(owner, repo, issue_number, marker)
if (updateConfig.alwaysLatestComment && existingComment && !isLatest) {
await addCommentToIssue(owner, repo, issue_number, `${body}\n${marker}`)
await deleteComment(existingComment.id, owner, repo, issue_number)
return
}
if (existingComment) {
if (updateConfig.shouldUpdate && !updateConfig.shouldOverwrite) {
finalBody = `${existingComment.body}\n\n---\n\n${body}\n${marker}`
} else if (updateConfig.shouldOverwrite) {
finalBody = `${body}\n\n${UPDATE_EMOJI} This comment has been updated`
}
}
if (!finalBody.includes(marker)) {
finalBody = `${finalBody}\n${marker}`
}
if (
existingComment &&
(updateConfig.shouldUpdate || updateConfig.shouldOverwrite)
) {
await updateComment(
existingComment.id,
owner,
repo,
issue_number,
finalBody
)
} else {
await addCommentToIssue(owner, repo, issue_number, finalBody)
}
}
/**
* Posts or updates a comment on a pull request.
*
* @param inputs - The user-provided inputs for configuring the comment behavior.
* @param marker - The unique marker used to identify existing comments.
* @returns A promise that resolves when the comment operation is completed.
*/
async function postOrUpdatePRComment(
inputs: Inputs,
marker: string
): Promise<void> {
core.info('Posting or updating PR comment')
const newSummary = core.summary.stringify()
try {
await handleComment(
context.repo.owner,
context.repo.repo,
context.issue.number,
newSummary,
marker,
{
shouldUpdate: inputs.updateComment,
shouldOverwrite: inputs.overwriteComment,
alwaysLatestComment: inputs.alwaysLatestComment
}
)
} catch (error) {
if (
error instanceof Error &&
error.message.includes('Resource not accessible by integration')
) {
core.endGroup()
core.warning(
`${error.message}\n` +
'Unable to post PR comment - this is likely a permissions issue.\n' +
'Required permission: "pull-requests: write" needs to be set in your workflow permissions.\n' +
'Add this to your workflow file:\n\n' +
'jobs:\n' +
' build:\n' +
' runs-on: ubuntu-latest\n' +
' permissions:\n' +
' pull-requests: write\n\n' +
'See documentation: https://docs.github.com/en/actions/security-for-github-actions/security-guides/automatic-token-authentication#modifying-the-permissions-for-the-github_token\n\n' +
'For forked PRs, you should use the pull_request_target event instead of pull_request.'
)
} else if (error instanceof Error) {
core.warning(`Failed to post PR comment: ${error.message}`)
}
}
}
/**
* Posts or updates a comment on an issue.
*
* @param inputs - The user-provided inputs for configuring the comment behavior.
* @param marker - The unique marker used to identify existing comments.
* @returns A promise that resolves when the comment operation is completed.
*/
async function postOrUpdateIssueComment(
inputs: Inputs,
marker: string
): Promise<void> {
core.info('Posting or updating issue comment')
const newSummary = core.summary.stringify()
try {
await handleComment(
context.repo.owner,
context.repo.repo,
parseInt(inputs.issue),
newSummary,
marker,
{
shouldUpdate: inputs.updateComment,
shouldOverwrite: inputs.overwriteComment,
alwaysLatestComment: inputs.alwaysLatestComment
}
)
} catch (error) {
if (
error instanceof Error &&
error.message.includes('Resource not accessible by integration')
) {
core.endGroup()
core.warning(
`${error.message}\n` +
'Unable to post issue comment - this is likely a permissions issue.\n' +
'Required permission: "issues: write" needs to be set in your workflow permissions.\n' +
'Add this to your workflow file:\n\n' +
'jobs:\n' +
' build:\n' +
' runs-on: ubuntu-latest\n' +
' permissions:\n' +
' issues: write\n\n' +
'See documentation: https://docs.github.com/en/actions/security-for-github-actions/security-guides/automatic-token-authentication#modifying-the-permissions-for-the-github_token'
)
} else if (error instanceof Error) {
core.warning(`Failed to post issue comment: ${error.message}`)
}
}
}
/**
* Formats the test summary into a string like "10 passed, 1 failed, 2 skipped".
* @param summary - The test summary object
* @returns Formatted summary string
*/
function formatTestSummary(summary: { passed: number; failed: number; skipped: number; pending: number; other: number }): string {
const parts: string[] = []
if (summary.passed > 0) {
parts.push(`${summary.passed} passed`)
}
if (summary.failed > 0) {
parts.push(`${summary.failed} failed`)
}
if (summary.skipped > 0) {
parts.push(`${summary.skipped} skipped`)
}
if (summary.pending > 0) {
parts.push(`${summary.pending} pending`)
}
if (summary.other > 0) {
parts.push(`${summary.other} other`)
}
if (parts.length === 0) {
return 'No tests'
}
return parts.join(', ')
}
/**
* Creates a status check for a action.
*
* @param inputs - The user-provided inputs for configuring the status check.
* @param report - The CTRF report containing test results.
*/
export async function createStatusCheck(
inputs: Inputs,
report: Report
): Promise<void> {
core.info('Creating status check')
let summary = core.summary.stringify()
if (summary.length > 65000) {
core.warning('Summary is too long to create a status check. Truncating...')
summary = summary.slice(0, 65000)
}
try {
const formattedSummary = formatTestSummary(report.results.summary)
await createCheckRun(
context.repo.owner,
context.repo.repo,
context.sha,
inputs.statusCheckName,
'completed',
report.results.summary.failed > 0 ? 'failure' : 'success',
formattedSummary,
summary
)
} catch (error) {
if (
error instanceof Error &&
error.message.includes('Resource not accessible by integration')
) {
core.endGroup()
core.warning(
`${error.message}\n` +
'Unable to create status check - this is likely a permissions issue.\n' +
'Required permission: "checks: write" needs to be set in your workflow permissions.\n' +
'Add this to your workflow file:\n\n' +
'jobs:\n' +
' build:\n' +
' runs-on: ubuntu-latest\n' +
' permissions:\n' +
' checks: write\n\n' +
'See documentation: https://docs.github.com/en/actions/security-for-github-actions/security-guides/automatic-token-authentication#modifying-the-permissions-for-the-github_token'
)
} else if (error instanceof Error) {
core.warning(`Failed to create status check: ${error.message}`)
}
}
}
/**
* Searches for an existing PR comment containing a given marker.
*
* @param owner - The owner of the repository.
* @param repo - The repository name.
* @param issue_number - The pull request number.
* @param marker - The unique marker used to identify the comment.
* @returns Object containing the comment if found and whether it's the latest comment.
*/
export async function findExistingMarkedComment(
owner: string,
repo: string,
issue_number: number,
marker: string
): Promise<{ comment: IssueComment | undefined; isLatest: boolean }> {
const comments = await listComments(owner, repo, issue_number)
const markedComment = [...comments]
.reverse()
.find(
(comment: IssueComment) => comment.body && comment.body.includes(marker)
)
const isLatest = Boolean(
markedComment &&
comments.length > 0 &&
markedComment.id === comments[comments.length - 1].id
)
return { comment: markedComment, isLatest }
}