This repository has been archived by the owner on Mar 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 301
/
review.ts
1020 lines (890 loc) · 27.9 KB
/
review.ts
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {error, info, warning} from '@actions/core'
// eslint-disable-next-line camelcase
import {context as github_context} from '@actions/github'
import pLimit from 'p-limit'
import {type Bot} from './bot'
import {
Commenter,
COMMENT_REPLY_TAG,
RAW_SUMMARY_END_TAG,
RAW_SUMMARY_START_TAG,
SHORT_SUMMARY_END_TAG,
SHORT_SUMMARY_START_TAG,
SUMMARIZE_TAG
} from './commenter'
import {Inputs} from './inputs'
import {octokit} from './octokit'
import {type Options} from './options'
import {type Prompts} from './prompts'
import {getTokenCount} from './tokenizer'
// eslint-disable-next-line camelcase
const context = github_context
const repo = context.repo
const ignoreKeyword = '@coderabbitai: ignore'
export const codeReview = async (
lightBot: Bot,
heavyBot: Bot,
options: Options,
prompts: Prompts
): Promise<void> => {
const commenter: Commenter = new Commenter()
const openaiConcurrencyLimit = pLimit(options.openaiConcurrencyLimit)
const githubConcurrencyLimit = pLimit(options.githubConcurrencyLimit)
if (
context.eventName !== 'pull_request' &&
context.eventName !== 'pull_request_target'
) {
warning(
`Skipped: current event is ${context.eventName}, only support pull_request event`
)
return
}
if (context.payload.pull_request == null) {
warning('Skipped: context.payload.pull_request is null')
return
}
const inputs: Inputs = new Inputs()
inputs.title = context.payload.pull_request.title
if (context.payload.pull_request.body != null) {
inputs.description = commenter.getDescription(
context.payload.pull_request.body
)
}
// if the description contains ignore_keyword, skip
if (inputs.description.includes(ignoreKeyword)) {
info('Skipped: description contains ignore_keyword')
return
}
// as gpt-3.5-turbo isn't paying attention to system message, add to inputs for now
inputs.systemMessage = options.systemMessage
// get SUMMARIZE_TAG message
const existingSummarizeCmt = await commenter.findCommentWithTag(
SUMMARIZE_TAG,
context.payload.pull_request.number
)
let existingCommitIdsBlock = ''
let existingSummarizeCmtBody = ''
if (existingSummarizeCmt != null) {
existingSummarizeCmtBody = existingSummarizeCmt.body
inputs.rawSummary = commenter.getRawSummary(existingSummarizeCmtBody)
inputs.shortSummary = commenter.getShortSummary(existingSummarizeCmtBody)
existingCommitIdsBlock = commenter.getReviewedCommitIdsBlock(
existingSummarizeCmtBody
)
}
const allCommitIds = await commenter.getAllCommitIds()
// find highest reviewed commit id
let highestReviewedCommitId = ''
if (existingCommitIdsBlock !== '') {
highestReviewedCommitId = commenter.getHighestReviewedCommitId(
allCommitIds,
commenter.getReviewedCommitIds(existingCommitIdsBlock)
)
}
if (
highestReviewedCommitId === '' ||
highestReviewedCommitId === context.payload.pull_request.head.sha
) {
info(
`Will review from the base commit: ${
context.payload.pull_request.base.sha as string
}`
)
highestReviewedCommitId = context.payload.pull_request.base.sha
} else {
info(`Will review from commit: ${highestReviewedCommitId}`)
}
// Fetch the diff between the highest reviewed commit and the latest commit of the PR branch
const incrementalDiff = await octokit.repos.compareCommits({
owner: repo.owner,
repo: repo.repo,
base: highestReviewedCommitId,
head: context.payload.pull_request.head.sha
})
// Fetch the diff between the target branch's base commit and the latest commit of the PR branch
const targetBranchDiff = await octokit.repos.compareCommits({
owner: repo.owner,
repo: repo.repo,
base: context.payload.pull_request.base.sha,
head: context.payload.pull_request.head.sha
})
const incrementalFiles = incrementalDiff.data.files
const targetBranchFiles = targetBranchDiff.data.files
if (incrementalFiles == null || targetBranchFiles == null) {
warning('Skipped: files data is missing')
return
}
// Filter out any file that is changed compared to the incremental changes
const files = targetBranchFiles.filter(targetBranchFile =>
incrementalFiles.some(
incrementalFile => incrementalFile.filename === targetBranchFile.filename
)
)
if (files.length === 0) {
warning('Skipped: files is null')
return
}
// skip files if they are filtered out
const filterSelectedFiles = []
const filterIgnoredFiles = []
for (const file of files) {
if (!options.checkPath(file.filename)) {
info(`skip for excluded path: ${file.filename}`)
filterIgnoredFiles.push(file)
} else {
filterSelectedFiles.push(file)
}
}
if (filterSelectedFiles.length === 0) {
warning('Skipped: filterSelectedFiles is null')
return
}
const commits = incrementalDiff.data.commits
if (commits.length === 0) {
warning('Skipped: commits is null')
return
}
// find hunks to review
const filteredFiles: Array<
[string, string, string, Array<[number, number, string]>] | null
> = await Promise.all(
filterSelectedFiles.map(file =>
githubConcurrencyLimit(async () => {
// retrieve file contents
let fileContent = ''
if (context.payload.pull_request == null) {
warning('Skipped: context.payload.pull_request is null')
return null
}
try {
const contents = await octokit.repos.getContent({
owner: repo.owner,
repo: repo.repo,
path: file.filename,
ref: context.payload.pull_request.base.sha
})
if (contents.data != null) {
if (!Array.isArray(contents.data)) {
if (
contents.data.type === 'file' &&
contents.data.content != null
) {
fileContent = Buffer.from(
contents.data.content,
'base64'
).toString()
}
}
}
} catch (e: any) {
warning(
`Failed to get file contents: ${
e as string
}. This is OK if it's a new file.`
)
}
let fileDiff = ''
if (file.patch != null) {
fileDiff = file.patch
}
const patches: Array<[number, number, string]> = []
for (const patch of splitPatch(file.patch)) {
const patchLines = patchStartEndLine(patch)
if (patchLines == null) {
continue
}
const hunks = parsePatch(patch)
if (hunks == null) {
continue
}
const hunksStr = `
---new_hunk---
\`\`\`
${hunks.newHunk}
\`\`\`
---old_hunk---
\`\`\`
${hunks.oldHunk}
\`\`\`
`
patches.push([
patchLines.newHunk.startLine,
patchLines.newHunk.endLine,
hunksStr
])
}
if (patches.length > 0) {
return [file.filename, fileContent, fileDiff, patches] as [
string,
string,
string,
Array<[number, number, string]>
]
} else {
return null
}
})
)
)
// Filter out any null results
const filesAndChanges = filteredFiles.filter(file => file !== null) as Array<
[string, string, string, Array<[number, number, string]>]
>
if (filesAndChanges.length === 0) {
error('Skipped: no files to review')
return
}
let statusMsg = `<details>
<summary>Commits</summary>
Files that changed from the base of the PR and between ${highestReviewedCommitId} and ${
context.payload.pull_request.head.sha
} commits.
</details>
${
filesAndChanges.length > 0
? `
<details>
<summary>Files selected (${filesAndChanges.length})</summary>
* ${filesAndChanges
.map(([filename, , , patches]) => `${filename} (${patches.length})`)
.join('\n* ')}
</details>
`
: ''
}
${
filterIgnoredFiles.length > 0
? `
<details>
<summary>Files ignored due to filter (${filterIgnoredFiles.length})</summary>
* ${filterIgnoredFiles.map(file => file.filename).join('\n* ')}
</details>
`
: ''
}
`
// update the existing comment with in progress status
const inProgressSummarizeCmt = commenter.addInProgressStatus(
existingSummarizeCmtBody,
statusMsg
)
// add in progress status to the summarize comment
await commenter.comment(`${inProgressSummarizeCmt}`, SUMMARIZE_TAG, 'replace')
const summariesFailed: string[] = []
const doSummary = async (
filename: string,
fileContent: string,
fileDiff: string
): Promise<[string, string, boolean] | null> => {
info(`summarize: ${filename}`)
const ins = inputs.clone()
if (fileDiff.length === 0) {
warning(`summarize: file_diff is empty, skip ${filename}`)
summariesFailed.push(`${filename} (empty diff)`)
return null
}
ins.filename = filename
ins.fileDiff = fileDiff
// render prompt based on inputs so far
const summarizePrompt = prompts.renderSummarizeFileDiff(
ins,
options.reviewSimpleChanges
)
const tokens = getTokenCount(summarizePrompt)
if (tokens > options.lightTokenLimits.requestTokens) {
info(`summarize: diff tokens exceeds limit, skip ${filename}`)
summariesFailed.push(`${filename} (diff tokens exceeds limit)`)
return null
}
// summarize content
try {
const [summarizeResp] = await lightBot.chat(summarizePrompt, {})
if (summarizeResp === '') {
info('summarize: nothing obtained from openai')
summariesFailed.push(`${filename} (nothing obtained from openai)`)
return null
} else {
if (options.reviewSimpleChanges === false) {
// parse the comment to look for triage classification
// Format is : [TRIAGE]: <NEEDS_REVIEW or APPROVED>
// if the change needs review return true, else false
const triageRegex = /\[TRIAGE\]:\s*(NEEDS_REVIEW|APPROVED)/
const triageMatch = summarizeResp.match(triageRegex)
if (triageMatch != null) {
const triage = triageMatch[1]
const needsReview = triage === 'NEEDS_REVIEW'
// remove this line from the comment
const summary = summarizeResp.replace(triageRegex, '').trim()
info(`filename: ${filename}, triage: ${triage}`)
return [filename, summary, needsReview]
}
}
return [filename, summarizeResp, true]
}
} catch (e: any) {
warning(`summarize: error from openai: ${e as string}`)
summariesFailed.push(`${filename} (error from openai: ${e as string})})`)
return null
}
}
const summaryPromises = []
const skippedFiles = []
for (const [filename, fileContent, fileDiff] of filesAndChanges) {
if (options.maxFiles <= 0 || summaryPromises.length < options.maxFiles) {
summaryPromises.push(
openaiConcurrencyLimit(
async () => await doSummary(filename, fileContent, fileDiff)
)
)
} else {
skippedFiles.push(filename)
}
}
const summaries = (await Promise.all(summaryPromises)).filter(
summary => summary !== null
) as Array<[string, string, boolean]>
if (summaries.length > 0) {
const batchSize = 10
// join summaries into one in the batches of batchSize
// and ask the bot to summarize the summaries
for (let i = 0; i < summaries.length; i += batchSize) {
const summariesBatch = summaries.slice(i, i + batchSize)
for (const [filename, summary] of summariesBatch) {
inputs.rawSummary += `---
${filename}: ${summary}
`
}
// ask chatgpt to summarize the summaries
const [summarizeResp] = await heavyBot.chat(
prompts.renderSummarizeChangesets(inputs),
{}
)
if (summarizeResp === '') {
warning('summarize: nothing obtained from openai')
} else {
inputs.rawSummary = summarizeResp
}
}
}
// final summary
const [summarizeFinalResponse] = await heavyBot.chat(
prompts.renderSummarize(inputs),
{}
)
if (summarizeFinalResponse === '') {
info('summarize: nothing obtained from openai')
}
if (options.disableReleaseNotes === false) {
// final release notes
const [releaseNotesResponse] = await heavyBot.chat(
prompts.renderSummarizeReleaseNotes(inputs),
{}
)
if (releaseNotesResponse === '') {
info('release notes: nothing obtained from openai')
} else {
let message = '### Summary by CodeRabbit\n\n'
message += releaseNotesResponse
try {
await commenter.updateDescription(
context.payload.pull_request.number,
message
)
} catch (e: any) {
warning(`release notes: error from github: ${e.message as string}`)
}
}
}
// generate a short summary as well
const [summarizeShortResponse] = await heavyBot.chat(
prompts.renderSummarizeShort(inputs),
{}
)
inputs.shortSummary = summarizeShortResponse
let summarizeComment = `${summarizeFinalResponse}
${RAW_SUMMARY_START_TAG}
${inputs.rawSummary}
${RAW_SUMMARY_END_TAG}
${SHORT_SUMMARY_START_TAG}
${inputs.shortSummary}
${SHORT_SUMMARY_END_TAG}
---
<details>
<summary>Uplevel your code reviews with CodeRabbit Pro</summary>
### CodeRabbit Pro
If you like this project, please support us by purchasing the [Pro version](https://coderabbit.ai). The Pro version has advanced context, superior noise reduction and several proprietary improvements compared to the open source version. Moreover, CodeRabbit Pro is free for open source projects.
</details>
`
statusMsg += `
${
skippedFiles.length > 0
? `
<details>
<summary>Files not processed due to max files limit (${
skippedFiles.length
})</summary>
* ${skippedFiles.join('\n* ')}
</details>
`
: ''
}
${
summariesFailed.length > 0
? `
<details>
<summary>Files not summarized due to errors (${
summariesFailed.length
})</summary>
* ${summariesFailed.join('\n* ')}
</details>
`
: ''
}
`
if (!options.disableReview) {
const filesAndChangesReview = filesAndChanges.filter(([filename]) => {
const needsReview =
summaries.find(
([summaryFilename]) => summaryFilename === filename
)?.[2] ?? true
return needsReview
})
const reviewsSkipped = filesAndChanges
.filter(
([filename]) =>
!filesAndChangesReview.some(
([reviewFilename]) => reviewFilename === filename
)
)
.map(([filename]) => filename)
// failed reviews array
const reviewsFailed: string[] = []
let lgtmCount = 0
let reviewCount = 0
const doReview = async (
filename: string,
fileContent: string,
patches: Array<[number, number, string]>
): Promise<void> => {
info(`reviewing ${filename}`)
// make a copy of inputs
const ins: Inputs = inputs.clone()
ins.filename = filename
// calculate tokens based on inputs so far
let tokens = getTokenCount(prompts.renderReviewFileDiff(ins))
// loop to calculate total patch tokens
let patchesToPack = 0
for (const [, , patch] of patches) {
const patchTokens = getTokenCount(patch)
if (tokens + patchTokens > options.heavyTokenLimits.requestTokens) {
info(
`only packing ${patchesToPack} / ${patches.length} patches, tokens: ${tokens} / ${options.heavyTokenLimits.requestTokens}`
)
break
}
tokens += patchTokens
patchesToPack += 1
}
let patchesPacked = 0
for (const [startLine, endLine, patch] of patches) {
if (context.payload.pull_request == null) {
warning('No pull request found, skipping.')
continue
}
// see if we can pack more patches into this request
if (patchesPacked >= patchesToPack) {
info(
`unable to pack more patches into this request, packed: ${patchesPacked}, total patches: ${patches.length}, skipping.`
)
if (options.debug) {
info(`prompt so far: ${prompts.renderReviewFileDiff(ins)}`)
}
break
}
patchesPacked += 1
let commentChain = ''
try {
const allChains = await commenter.getCommentChainsWithinRange(
context.payload.pull_request.number,
filename,
startLine,
endLine,
COMMENT_REPLY_TAG
)
if (allChains.length > 0) {
info(`Found comment chains: ${allChains} for ${filename}`)
commentChain = allChains
}
} catch (e: any) {
warning(
`Failed to get comments: ${e as string}, skipping. backtrace: ${
e.stack as string
}`
)
}
// try packing comment_chain into this request
const commentChainTokens = getTokenCount(commentChain)
if (
tokens + commentChainTokens >
options.heavyTokenLimits.requestTokens
) {
commentChain = ''
} else {
tokens += commentChainTokens
}
ins.patches += `
${patch}
`
if (commentChain !== '') {
ins.patches += `
---comment_chains---
\`\`\`
${commentChain}
\`\`\`
`
}
ins.patches += `
---end_change_section---
`
}
if (patchesPacked > 0) {
// perform review
try {
const [response] = await heavyBot.chat(
prompts.renderReviewFileDiff(ins),
{}
)
if (response === '') {
info('review: nothing obtained from openai')
reviewsFailed.push(`${filename} (no response)`)
return
}
// parse review
const reviews = parseReview(response, patches, options.debug)
for (const review of reviews) {
// check for LGTM
if (
!options.reviewCommentLGTM &&
(review.comment.includes('LGTM') ||
review.comment.includes('looks good to me'))
) {
lgtmCount += 1
continue
}
if (context.payload.pull_request == null) {
warning('No pull request found, skipping.')
continue
}
try {
reviewCount += 1
await commenter.bufferReviewComment(
filename,
review.startLine,
review.endLine,
`${review.comment}`
)
} catch (e: any) {
reviewsFailed.push(`${filename} comment failed (${e as string})`)
}
}
} catch (e: any) {
warning(
`Failed to review: ${e as string}, skipping. backtrace: ${
e.stack as string
}`
)
reviewsFailed.push(`${filename} (${e as string})`)
}
} else {
reviewsSkipped.push(`${filename} (diff too large)`)
}
}
const reviewPromises = []
for (const [filename, fileContent, , patches] of filesAndChangesReview) {
if (options.maxFiles <= 0 || reviewPromises.length < options.maxFiles) {
reviewPromises.push(
openaiConcurrencyLimit(async () => {
await doReview(filename, fileContent, patches)
})
)
} else {
skippedFiles.push(filename)
}
}
await Promise.all(reviewPromises)
statusMsg += `
${
reviewsFailed.length > 0
? `<details>
<summary>Files not reviewed due to errors (${reviewsFailed.length})</summary>
* ${reviewsFailed.join('\n* ')}
</details>
`
: ''
}
${
reviewsSkipped.length > 0
? `<details>
<summary>Files skipped from review due to trivial changes (${
reviewsSkipped.length
})</summary>
* ${reviewsSkipped.join('\n* ')}
</details>
`
: ''
}
<details>
<summary>Review comments generated (${reviewCount + lgtmCount})</summary>
* Review: ${reviewCount}
* LGTM: ${lgtmCount}
</details>
---
<details>
<summary>Tips</summary>
### Chat with <img src="https://avatars.githubusercontent.com/in/347564?s=41&u=fad245b8b4c7254fe63dd4dcd4d662ace122757e&v=4" alt="Image description" width="20" height="20"> CodeRabbit Bot (\`@coderabbitai\`)
- Reply on review comments left by this bot to ask follow-up questions. A review comment is a comment on a diff or a file.
- Invite the bot into a review comment chain by tagging \`@coderabbitai\` in a reply.
### Code suggestions
- The bot may make code suggestions, but please review them carefully before committing since the line number ranges may be misaligned.
- You can edit the comment made by the bot and manually tweak the suggestion if it is slightly off.
### Pausing incremental reviews
- Add \`@coderabbitai: ignore\` anywhere in the PR description to pause further reviews from the bot.
</details>
`
// add existing_comment_ids_block with latest head sha
summarizeComment += `\n${commenter.addReviewedCommitId(
existingCommitIdsBlock,
context.payload.pull_request.head.sha
)}`
// post the review
await commenter.submitReview(
context.payload.pull_request.number,
commits[commits.length - 1].sha,
statusMsg
)
}
// post the final summary comment
await commenter.comment(`${summarizeComment}`, SUMMARIZE_TAG, 'replace')
}
const splitPatch = (patch: string | null | undefined): string[] => {
if (patch == null) {
return []
}
const pattern = /(^@@ -(\d+),(\d+) \+(\d+),(\d+) @@).*$/gm
const result: string[] = []
let last = -1
let match: RegExpExecArray | null
while ((match = pattern.exec(patch)) !== null) {
if (last === -1) {
last = match.index
} else {
result.push(patch.substring(last, match.index))
last = match.index
}
}
if (last !== -1) {
result.push(patch.substring(last))
}
return result
}
const patchStartEndLine = (
patch: string
): {
oldHunk: {startLine: number; endLine: number}
newHunk: {startLine: number; endLine: number}
} | null => {
const pattern = /(^@@ -(\d+),(\d+) \+(\d+),(\d+) @@)/gm
const match = pattern.exec(patch)
if (match != null) {
const oldBegin = parseInt(match[2])
const oldDiff = parseInt(match[3])
const newBegin = parseInt(match[4])
const newDiff = parseInt(match[5])
return {
oldHunk: {
startLine: oldBegin,
endLine: oldBegin + oldDiff - 1
},
newHunk: {
startLine: newBegin,
endLine: newBegin + newDiff - 1
}
}
} else {
return null
}
}
const parsePatch = (
patch: string
): {oldHunk: string; newHunk: string} | null => {
const hunkInfo = patchStartEndLine(patch)
if (hunkInfo == null) {
return null
}
const oldHunkLines: string[] = []
const newHunkLines: string[] = []
let newLine = hunkInfo.newHunk.startLine
const lines = patch.split('\n').slice(1) // Skip the @@ line
// Remove the last line if it's empty
if (lines[lines.length - 1] === '') {
lines.pop()
}
// Skip annotations for the first 3 and last 3 lines
const skipStart = 3
const skipEnd = 3
let currentLine = 0
const removalOnly = !lines.some(line => line.startsWith('+'))
for (const line of lines) {
currentLine++
if (line.startsWith('-')) {
oldHunkLines.push(`${line.substring(1)}`)
} else if (line.startsWith('+')) {
newHunkLines.push(`${newLine}: ${line.substring(1)}`)
newLine++
} else {
// context line
oldHunkLines.push(`${line}`)
if (
removalOnly ||
(currentLine > skipStart && currentLine <= lines.length - skipEnd)
) {
newHunkLines.push(`${newLine}: ${line}`)
} else {
newHunkLines.push(`${line}`)
}
newLine++
}
}
return {
oldHunk: oldHunkLines.join('\n'),
newHunk: newHunkLines.join('\n')
}
}
interface Review {
startLine: number
endLine: number
comment: string
}
function parseReview(
response: string,
patches: Array<[number, number, string]>,
debug = false
): Review[] {
const reviews: Review[] = []
response = sanitizeResponse(response.trim())
const lines = response.split('\n')
const lineNumberRangeRegex = /(?:^|\s)(\d+)-(\d+):\s*$/
const commentSeparator = '---'
let currentStartLine: number | null = null
let currentEndLine: number | null = null
let currentComment = ''
function storeReview(): void {
if (currentStartLine !== null && currentEndLine !== null) {
const review: Review = {
startLine: currentStartLine,
endLine: currentEndLine,
comment: currentComment
}
let withinPatch = false
let bestPatchStartLine = -1
let bestPatchEndLine = -1
let maxIntersection = 0
for (const [startLine, endLine] of patches) {
const intersectionStart = Math.max(review.startLine, startLine)
const intersectionEnd = Math.min(review.endLine, endLine)
const intersectionLength = Math.max(
0,
intersectionEnd - intersectionStart + 1
)
if (intersectionLength > maxIntersection) {
maxIntersection = intersectionLength
bestPatchStartLine = startLine
bestPatchEndLine = endLine
withinPatch =
intersectionLength === review.endLine - review.startLine + 1
}
if (withinPatch) break
}
if (!withinPatch) {
if (bestPatchStartLine !== -1 && bestPatchEndLine !== -1) {
review.comment = `> Note: This review was outside of the patch, so it was mapped to the patch with the greatest overlap. Original lines [${review.startLine}-${review.endLine}]
${review.comment}`
review.startLine = bestPatchStartLine
review.endLine = bestPatchEndLine
} else {
review.comment = `> Note: This review was outside of the patch, but no patch was found that overlapped with it. Original lines [${review.startLine}-${review.endLine}]
${review.comment}`
review.startLine = patches[0][0]
review.endLine = patches[0][1]
}
}
reviews.push(review)
info(
`Stored comment for line range ${currentStartLine}-${currentEndLine}: ${currentComment.trim()}`
)
}
}
function sanitizeCodeBlock(comment: string, codeBlockLabel: string): string {
const codeBlockStart = `\`\`\`${codeBlockLabel}`
const codeBlockEnd = '```'
const lineNumberRegex = /^ *(\d+): /gm
let codeBlockStartIndex = comment.indexOf(codeBlockStart)
while (codeBlockStartIndex !== -1) {
const codeBlockEndIndex = comment.indexOf(
codeBlockEnd,
codeBlockStartIndex + codeBlockStart.length
)
if (codeBlockEndIndex === -1) break
const codeBlock = comment.substring(
codeBlockStartIndex + codeBlockStart.length,
codeBlockEndIndex
)
const sanitizedBlock = codeBlock.replace(lineNumberRegex, '')
comment =
comment.slice(0, codeBlockStartIndex + codeBlockStart.length) +
sanitizedBlock +
comment.slice(codeBlockEndIndex)
codeBlockStartIndex = comment.indexOf(
codeBlockStart,
codeBlockStartIndex +
codeBlockStart.length +
sanitizedBlock.length +
codeBlockEnd.length
)
}
return comment
}
function sanitizeResponse(comment: string): string {
comment = sanitizeCodeBlock(comment, 'suggestion')
comment = sanitizeCodeBlock(comment, 'diff')
return comment
}
for (const line of lines) {
const lineNumberRangeMatch = line.match(lineNumberRangeRegex)
if (lineNumberRangeMatch != null) {
storeReview()
currentStartLine = parseInt(lineNumberRangeMatch[1], 10)
currentEndLine = parseInt(lineNumberRangeMatch[2], 10)
currentComment = ''
if (debug) {
info(`Found line number range: ${currentStartLine}-${currentEndLine}`)
}
continue
}