forked from parkerbxyz/suggest-changes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
595 lines (540 loc) · 18.4 KB
/
index.js
File metadata and controls
595 lines (540 loc) · 18.4 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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
// @ts-check
import { debug, getInput, info, setFailed, warning } from '@actions/core'
import { getExecOutput } from '@actions/exec'
import { Octokit } from '@octokit/action'
import { RequestError } from '@octokit/request-error'
import { readFileSync } from 'node:fs'
import { env } from 'node:process'
import parseGitDiff from 'parse-git-diff'
/** @typedef {import('parse-git-diff').AnyLineChange} AnyLineChange */
/** @typedef {import('parse-git-diff').AddedLine} AddedLine */
/** @typedef {import('parse-git-diff').DeletedLine} DeletedLine */
/** @typedef {import('parse-git-diff').UnchangedLine} UnchangedLine */
/** @typedef {import('@octokit/types').Endpoints['GET /repos/{owner}/{repo}/pulls/{pull_number}/comments']['response']['data'][number]} GetReviewComment */
/** @typedef {NonNullable<import('@octokit/types').Endpoints['POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews']['parameters']['comments']>[number]} ReviewCommentInput */
/** @typedef {ReviewCommentInput & { line: number }} ReviewCommentDraft */
/** @typedef {NonNullable<import('@octokit/types').Endpoints['POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews']['parameters']['event']>} ReviewEvent */
/** @typedef {import("@octokit/webhooks-types").PullRequestEvent} PullRequestEvent */
/**
* @typedef {Object} SuggestionBody
* @property {string} body
* @property {number} lineCount
*/
/**
* Type guard to check if a change is an AddedLine
* @param {AnyLineChange} change - The change to check
* @returns {change is AddedLine} True if the change is an AddedLine
*/
function isAddedLine(change) {
return change?.type === 'AddedLine' && typeof change.lineAfter === 'number'
}
/**
* Type guard to check if a change is a DeletedLine
* @param {AnyLineChange} change - The change to check
* @returns {change is DeletedLine} True if the change is a DeletedLine
*/
function isDeletedLine(change) {
return change?.type === 'DeletedLine' && typeof change.lineBefore === 'number'
}
/**
* Type guard to check if a change is an UnchangedLine
* @param {AnyLineChange} change - The change to check
* @returns {change is UnchangedLine} True if the change is an UnchangedLine
*/
function isUnchangedLine(change) {
return (
change?.type === 'UnchangedLine' &&
typeof change.lineBefore === 'number' &&
typeof change.lineAfter === 'number'
)
}
/**
* Generate git diff output with consistent flags
* @param {string[]} gitArgs - Additional git diff arguments
* @returns {Promise<string>} The git diff output
*/
export async function getGitDiff(gitArgs) {
const result = await getExecOutput(
'git',
['diff', '--unified=1', '--ignore-cr-at-eol', ...gitArgs],
{ silent: true, ignoreReturnCode: true }
)
return result.stdout
}
/**
* Create a suggestion fenced block.
* @param {string} content
* @returns {string}
*/
export const createSuggestion = (content) => {
// Quadruple backticks allow for triple backticks in a fenced code block in the suggestion body
// https://docs.github.com/get-started/writing-on-github/working-with-advanced-formatting/creating-and-highlighting-code-blocks#fenced-code-blocks
return `\`\`\`\`suggestion\n${content}\n\`\`\`\``
}
/**
* Format a line range for logging: "start-end" for multi-line, or the single line number.
* startLine is undefined for single-line suggestions; line is always defined.
* @param {number | undefined} startLine
* @param {number} line
* @returns {string}
*/
function formatLineRange(startLine, line) {
return typeof startLine === 'number' && startLine !== line
? `${startLine}-${line}`
: String(line)
}
/**
* Returns true for the known 422 "line must be part of the diff" validation failure.
* Strictly requires an Octokit RequestError so unrelated errors are rethrown.
* @param {unknown} err
* @returns {err is RequestError}
*/
function isLineOutsideDiffError(err) {
return (
err instanceof RequestError &&
err.status === 422 &&
/line must be part of the diff/i.test(String(err.message))
)
}
/**
* Normalize unknown error-like values to a concise string message.
* @param {unknown} err
* @returns {string}
*/
function formatError(err) {
return err instanceof Error ? err.message : String(err)
}
/**
* Filter changes by type for easier processing
* @param {AnyLineChange[]} changes - Array of changes to filter
* @returns {{addedLines: AddedLine[], deletedLines: DeletedLine[], unchangedLines: UnchangedLine[]}}
*/
const filterChangesByType = (changes) => ({
addedLines: changes.filter(isAddedLine),
deletedLines: changes.filter(isDeletedLine),
unchangedLines: changes.filter(isUnchangedLine),
})
/**
* Group changes into logical suggestion groups based on line proximity.
*
* Groups contiguous or nearly contiguous changes together to create logical
* suggestions that make sense when reviewing code. Unchanged lines are included
* for context but don't affect contiguity calculations.
*
* @param {AnyLineChange[]} changes - Array of line changes from git diff
* @returns {AnyLineChange[][]} Array of suggestion groups
*/
export const groupChangesForSuggestions = (changes) => {
if (changes.length === 0) return []
// Group by line proximity using appropriate coordinate systems
// - Deletions use lineBefore (original file line numbers)
// - Additions use lineAfter (new file line numbers)
// - Unchanged use lineBefore (context positioning)
const groups = []
let currentGroup = []
let lastChangedLineNumber = null
for (const change of changes) {
const lineNumber = isDeletedLine(change)
? change.lineBefore
: isAddedLine(change)
? change.lineAfter
: isUnchangedLine(change)
? change.lineBefore
: null
if (lineNumber === null) continue
// Start new group if there's a line gap between actual changes (not unchanged lines)
if (
!isUnchangedLine(change) &&
lastChangedLineNumber !== null &&
lineNumber > lastChangedLineNumber + 1
) {
groups.push(currentGroup)
currentGroup = []
}
currentGroup.push(change)
// Only track line numbers for actual changes (deletions and additions)
if (!isUnchangedLine(change)) {
lastChangedLineNumber = lineNumber
}
}
if (currentGroup.length > 0) groups.push(currentGroup)
return groups
}
/**
* Generate suggestion body and line count for a group of changes
* @param {AnyLineChange[]} changes - Group of related changes
* @returns {SuggestionBody | null} Suggestion body and line count, or null if no suggestion needed
*/
export const generateSuggestionBody = (changes) => {
const { addedLines, deletedLines, unchangedLines } =
filterChangesByType(changes)
// No additions means no content to suggest, except for pure deletions (empty replacement block)
if (addedLines.length === 0) {
if (deletedLines.length === 0) return null
return { body: createSuggestion(''), lineCount: deletedLines.length }
}
// Pure additions: include context if available
if (deletedLines.length === 0) {
const hasContext = unchangedLines.length > 0
const suggestionLines = hasContext
? [unchangedLines[0].content, ...addedLines.map((line) => line.content)]
: addedLines.map((line) => line.content)
return {
body: createSuggestion(suggestionLines.join('\n')),
lineCount: hasContext ? 1 : addedLines.length,
}
}
// Mixed changes: replace deleted content with added content
const suggestionLines = addedLines.map((line) => line.content)
return {
body: createSuggestion(suggestionLines.join('\n')),
lineCount: deletedLines.length,
}
}
/**
* Calculate line positioning for GitHub review comments.
* @param {AnyLineChange[]} groupChanges - The changes in this group
* @param {number} lineCount - Number of lines the suggestion spans
* @param {{start: number}} fromFileRange - File range information
* @returns {{startLine: number, endLine: number}} Line positioning
*/
export const calculateLinePosition = (
groupChanges,
lineCount,
fromFileRange
) => {
// Try to find the best target line in order of preference
const firstDeletedLine = groupChanges.find(isDeletedLine)
const firstUnchangedLine = groupChanges.find(isUnchangedLine)
const startLine =
firstDeletedLine?.lineBefore ?? // Deletions: use original line
firstUnchangedLine?.lineBefore ?? // Pure additions with context: position on context line
fromFileRange.start // Pure additions without context: use file range
return { startLine, endLine: startLine + lineCount - 1 }
}
/**
* Function to generate a unique key for a comment
* @param {ReviewCommentInput | GetReviewComment} comment
* @returns {string}
*/
export const generateCommentKey = (comment) =>
`${comment.path}:${comment.line ?? ''}:${comment.start_line ?? ''}:${
comment.body
}`
/**
* Lazily iterate over all suggestion groups in a parsed diff.
* Yields objects containing path, fromFileRange, and group changes.
* @param {ReturnType<typeof parseGitDiff>} parsedDiff
*/
function* iterateSuggestionGroups(parsedDiff) {
for (const file of parsedDiff.files) {
if (file.type !== 'ChangedFile') continue
const path = file.path
for (const chunk of file.chunks) {
if (chunk.type !== 'Chunk') continue
const { fromFileRange, changes } = chunk
const groups = groupChangesForSuggestions(changes)
for (const group of groups) {
yield { path, fromFileRange, group }
}
}
}
}
/**
* Build a review comment draft from a suggestion group.
* Returns null if the group does not produce a valid suggestion body.
* @param {string} path
* @param {{start: number}} fromFileRange
* @param {AnyLineChange[]} group
* @returns {ReviewCommentDraft | null}
*/
function buildCommentDraft(path, fromFileRange, group) {
const suggestion = generateSuggestionBody(group)
if (!suggestion) return null
const { body, lineCount } = suggestion
const { startLine, endLine } = calculateLinePosition(
group,
lineCount,
fromFileRange
)
return /** @type {ReviewCommentDraft} */ ({
path,
body,
line: endLine,
...(lineCount > 1 && {
start_line: startLine,
start_side: 'RIGHT',
}),
})
}
/**
* Partition an iterable into two arrays based on a predicate.
* @template T
* @param {Iterable<T>} items
* @param {(item: T) => boolean} predicate
* @returns {{pass: T[], fail: T[]}}
*/
function partition(items, predicate) {
/** @type {T[]} */ const pass = []
/** @type {T[]} */ const fail = []
for (const item of items) {
;(predicate(item) ? pass : fail).push(item)
}
return { pass, fail }
}
/**
* Generate GitHub review comments from a parsed diff (exported for testing)
* @param {ReturnType<typeof parseGitDiff>} parsedDiff - Parsed diff from parse-git-diff
* @param {Set<string>} existingCommentKeys - Set of existing comment keys to avoid duplicates
* @returns {Array<ReviewCommentDraft>} Generated comments
*/
export function generateReviewComments(
parsedDiff,
existingCommentKeys = new Set()
) {
const drafts = []
for (const { path, fromFileRange, group } of iterateSuggestionGroups(
parsedDiff
)) {
const draft = buildCommentDraft(path, fromFileRange, group)
if (draft) drafts.push(draft)
}
const { pass: unique, fail: skipped } = partition(
drafts,
(draft) => !existingCommentKeys.has(generateCommentKey(draft))
)
if (skipped.length) {
logCommentList(
'Suggestions skipped because they would duplicate existing suggestions:',
skipped
)
}
return unique
}
/**
* Fetch the canonical PR diff as a string or return null on failure/unavailability.
* @param {Octokit} octokit
* @param {string} owner
* @param {string} repo
* @param {number} pull_number
* @returns {Promise<string | null>}
*/
async function fetchCanonicalDiff(octokit, owner, repo, pull_number) {
if (
!octokit.pulls ||
typeof (/** @type {any} */ octokit.pulls.get) !== 'function'
) {
debug('PR diff filter: pulls.get unavailable; skipping.')
return null
}
try {
const { data } = await /** @type {any} */ (octokit).pulls.get({
owner,
repo,
pull_number,
headers: { accept: 'application/vnd.github.v3.diff' },
})
if (typeof data !== 'string' || !/^diff --git /.test(data)) {
debug('PR diff filter: no usable diff string; skipping.')
return null
}
return data
} catch (err) {
debug(`PR diff fetch failed: ${formatError(err)}`)
return null
}
}
/**
* Build a lookup of valid right-side line numbers per file path.
* @param {ReturnType<typeof parseGitDiff>} parsedDiff
* @returns {Record<string, Set<number>>}
*/
function buildRightSideAnchors(parsedDiff) {
return Object.fromEntries(
parsedDiff.files
.filter((file) => file.type === 'ChangedFile')
.map((file) => [
file.path,
new Set(
file.chunks
.filter((chunk) => chunk.type === 'Chunk')
.flatMap((chunk) =>
chunk.changes
.filter(
(change) => isAddedLine(change) || isUnchangedLine(change)
)
.map((change) => change.lineAfter)
)
),
])
)
}
/**
* Determine if a review comment draft is valid within the PR diff.
* @param {ReviewCommentDraft} comment
* @param {Record<string, Set<number>>} anchors
*/
function isValidSuggestion(comment, anchors) {
const validLines = anchors[comment.path]
if (!validLines) return false
if (!validLines.has(comment.line)) return false
if (comment.start_line !== undefined && !validLines.has(comment.start_line))
return false
return true
}
/**
* Log a list of review comment drafts with a standardized header.
* @param {string} header
* @param {ReviewCommentDraft[]} comments
* @param {(message: string) => void} [logger]
*/
function logCommentList(header, comments, logger = info) {
if (!comments.length) return
logger(`${header} ${comments.length}`)
for (const comment of comments) {
logger(
`- ${comment.path}:${formatLineRange(comment.start_line, comment.line)}`
)
}
}
/**
* Filters suggestion comments using the canonical server-side PR diff.
* Returns a new array containing only valid suggestions and logs summary info.
* Gracefully falls back (returns original comments) if the diff cannot be fetched/parsed.
* @param {Object} params
* @param {Octokit} params.octokit
* @param {string} params.owner
* @param {string} params.repo
* @param {number} params.pull_number
* @param {Array<ReviewCommentDraft>} params.comments
* @returns {Promise<Array<ReviewCommentDraft>>}
*/
async function filterSuggestionsInPullRequestDiff({
octokit,
owner,
repo,
pull_number,
comments,
}) {
const diffString = await fetchCanonicalDiff(octokit, owner, repo, pull_number)
if (!diffString) return comments
let parsedPullRequestDiff
try {
parsedPullRequestDiff = parseGitDiff(diffString)
} catch (err) {
warning(`PR diff parse failed: ${formatError(err)}`)
return comments
}
const rightSideAnchors = buildRightSideAnchors(parsedPullRequestDiff)
const { pass: valid, fail: skipped } = partition(comments, (comment) =>
isValidSuggestion(comment, rightSideAnchors)
)
logCommentList(
'Suggestions skipped because they are outside the pull request diff:',
skipped
)
return valid
}
/**
* Main execution function for the GitHub Action
* @param {Object} options - Configuration options
* @param {Octokit} options.octokit - Octokit instance
* @param {string} options.owner - Repository owner
* @param {string} options.repo - Repository name
* @param {number} options.pull_number - Pull request number
* @param {string} options.commit_id - Commit SHA
* @param {string} options.diff - Git diff output
* @param {ReviewEvent} options.event - Review event type
* @param {string} options.body - Review body
* @returns {Promise<{comments: Array, reviewCreated: boolean}>} Result of the action
*/
export async function run({
octokit,
owner,
repo,
pull_number,
commit_id,
diff,
event,
body,
}) {
debug(`Diff output: ${diff}`)
const existingComments = (
await octokit.pulls.listReviewComments({ owner, repo, pull_number })
).data
const existingCommentKeys = new Set(existingComments.map(generateCommentKey))
// Parse diff after collecting existing comment keys
const parsedDiff = parseGitDiff(diff)
const initialComments = generateReviewComments(
parsedDiff,
existingCommentKeys
)
const comments = await filterSuggestionsInPullRequestDiff({
octokit,
owner,
repo,
pull_number,
comments: initialComments,
})
logCommentList(`Suggestions to be included in review:`, comments)
if (!comments.length) {
return { comments: [], reviewCreated: false }
}
try {
await octokit.pulls.createReview({
owner,
repo,
pull_number,
commit_id,
body,
event,
comments,
})
debug('Batch create succeeded.')
return { comments, reviewCreated: true }
} catch (err) {
if (isLineOutsideDiffError(err)) {
debug(
'Batch review creation failed (422: line must be part of the diff). Returning without review.'
)
return { comments: [], reviewCreated: false }
}
throw err
}
}
// Main entrypoint (only when executed directly)
async function main() {
const octokit = new Octokit({
userAgent: 'suggest-changes',
})
const [owner, repo] = String(env.GITHUB_REPOSITORY).split('/')
/** @type {PullRequestEvent} */
const eventPayload = JSON.parse(
readFileSync(String(env.GITHUB_EVENT_PATH), 'utf8')
)
if (!eventPayload?.pull_request) {
const eventName = String(env.GITHUB_EVENT_NAME)
throw new Error(
[
`This workflow was triggered via ${eventName}.`,
`The ${eventName} event payload does not include the pull_request data required by this action.`,
'Run this action on: pull_request or pull_request_target instead.',
].join('\n')
)
}
const pull_number = Number(eventPayload.pull_request.number)
const commit_id = eventPayload.pull_request.head.sha
const pullRequestFiles = (
await octokit.pulls.listFiles({ owner, repo, pull_number })
).data.map((file) => file.filename)
// Get the diff between the head branch and the base branch (limit to the files in the pull request)
const diff = await getGitDiff(['--', ...pullRequestFiles])
const event = /** @type {ReviewEvent} */ (getInput('event').toUpperCase())
const body = getInput('comment')
await run({ octokit, owner, repo, pull_number, commit_id, diff, event, body })
}
if (import.meta.url === `file://${process.argv[1]}`) {
main().catch((err) =>
setFailed(err instanceof Error ? err.message : String(err))
)
}