-
Notifications
You must be signed in to change notification settings - Fork 724
Expand file tree
/
Copy pathpullRequestModel.ts
More file actions
2084 lines (1814 loc) · 71.6 KB
/
pullRequestModel.ts
File metadata and controls
2084 lines (1814 loc) · 71.6 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
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as buffer from 'buffer';
import * as path from 'path';
import equals from 'fast-deep-equal';
import gql from 'graphql-tag';
import * as vscode from 'vscode';
import { Repository } from '../api/api';
import { COPILOT_ACCOUNTS, DiffSide, IComment, IReviewThread, SubjectType, ViewedState } from '../common/comment';
import { getGitChangeType, getModifiedContentFromDiffHunk, parseDiff } from '../common/diffHunk';
import { commands } from '../common/executeCommands';
import { GitChangeType, InMemFileChange, SlimFileChange } from '../common/file';
import { GitHubRef } from '../common/githubRef';
import Logger from '../common/logger';
import { Remote } from '../common/remote';
import { ITelemetry } from '../common/telemetry';
import { ClosedEvent, EventType, ReviewEvent, TimelineEvent } from '../common/timelineEvent';
import { resolvePath, Schemes, toGitHubCommitUri, toPRUri, toReviewUri } from '../common/uri';
import { formatError, isDescendant } from '../common/utils';
import { InMemFileChangeModel, RemoteFileChangeModel } from '../view/fileChangeModel';
import { OctokitCommon } from './common';
import { ConflictResolutionModel } from './conflictResolutionModel';
import { CredentialStore } from './credentials';
import { FolderRepositoryManager } from './folderRepositoryManager';
import { GitHubRepository } from './githubRepository';
import {
AddCommentResponse,
AddReactionResponse,
AddReviewThreadResponse,
DeleteReactionResponse,
DeleteReviewResponse,
DequeuePullRequestResponse,
EditCommentResponse,
EnqueuePullRequestResponse,
FileContentResponse,
GetReviewRequestsResponse,
LatestReviewCommitResponse,
MarkPullRequestReadyForReviewResponse,
PendingReviewIdResponse,
PullRequestCommentsResponse,
PullRequestFilesResponse,
PullRequestMergabilityResponse,
ReactionGroup,
ResolveReviewThreadResponse,
ReviewThread,
StartReviewResponse,
SubmitReviewResponse,
TimelineEventsResponse,
UnresolveReviewThreadResponse,
} from './graphql';
import {
AccountType,
GithubItemStateEnum,
IAccount,
IGitTreeItem,
IRawFileChange,
IRawFileContent,
ISuggestedReviewer,
ITeam,
MergeMethod,
MergeQueueEntry,
PullRequest,
PullRequestChecks,
PullRequestMergeability,
PullRequestReviewRequirement,
ReadyForReview,
ReviewEventEnum,
} from './interface';
import { IssueChangeEvent, IssueModel } from './issueModel';
import { compareCommits } from './loggingOctokit';
import {
convertRESTPullRequestToRawPullRequest,
convertRESTReviewEvent,
getReactionGroup,
insertNewCommitsSinceReview,
parseAccount,
parseCombinedTimelineEvents,
parseGraphQLComment,
parseGraphQLReaction,
parseGraphQLReviewers,
parseGraphQLReviewEvent,
parseGraphQLReviewThread,
parseMergeability,
parseMergeQueueEntry,
RestAccount,
restPaginate,
} from './utils';
interface IPullRequestModel {
head: GitHubRef | null;
}
export interface IResolvedPullRequestModel extends IPullRequestModel {
head: GitHubRef;
}
export interface ReviewThreadChangeEvent {
added: IReviewThread[];
changed: IReviewThread[];
removed: IReviewThread[];
}
export interface FileViewedStateChangeEvent {
changed: {
fileName: string;
viewed: ViewedState;
}[];
}
export type FileViewedState = { [key: string]: ViewedState };
const BATCH_SIZE = 100;
export class PullRequestModel extends IssueModel<PullRequest> implements IPullRequestModel {
static override ID = 'PullRequestModel';
public isDraft?: boolean;
public reviewers?: (IAccount | ITeam)[];
public localBranchName?: string;
public mergeBase?: string;
public mergeQueueEntry?: MergeQueueEntry;
public conflicts?: string[];
public suggestedReviewers?: ISuggestedReviewer[];
public hasChangesSinceLastReview?: boolean;
private _showChangesSinceReview: boolean;
private _hasPendingReview: boolean = false;
private _onDidChangePendingReviewState: vscode.EventEmitter<boolean> = this._register(new vscode.EventEmitter<boolean>());
public onDidChangePendingReviewState = this._onDidChangePendingReviewState.event;
private _reviewThreadsCache: IReviewThread[] = [];
private _reviewThreadsCacheInitialized = false;
private _onDidChangeReviewThreads = this._register(new vscode.EventEmitter<ReviewThreadChangeEvent>());
public onDidChangeReviewThreads = this._onDidChangeReviewThreads.event;
private _fileChangeViewedState: FileViewedState = {};
private _viewedFiles: Set<string> = new Set();
private _unviewedFiles: Set<string> = new Set();
private _onDidChangeFileViewedState = this._register(new vscode.EventEmitter<FileViewedStateChangeEvent>());
public onDidChangeFileViewedState = this._onDidChangeFileViewedState.event;
private _onDidChangeChangesSinceReview = this._register(new vscode.EventEmitter<void>());
public onDidChangeChangesSinceReview = this._onDidChangeChangesSinceReview.event;
private _hasComments: boolean;
private _comments: readonly IComment[] | undefined;
// Whether the pull request is currently checked out locally
private _isActive: boolean;
public get isActive(): boolean {
return this._isActive;
}
public set isActive(isActive: boolean) {
this._isActive = isActive;
}
constructor(
private readonly credentialStore: CredentialStore,
telemetry: ITelemetry,
githubRepository: GitHubRepository,
remote: Remote,
item: PullRequest,
isActive?: boolean,
) {
super(telemetry, githubRepository, remote, item, true);
this.isActive = !!isActive;
this._showChangesSinceReview = false;
this.update(item);
}
public clear() {
this.comments = [];
this._reviewThreadsCacheInitialized = false;
this._reviewThreadsCache = [];
}
public async initializeReviewThreadCache(): Promise<void> {
await this.getReviewThreads();
this._reviewThreadsCacheInitialized = true;
}
public get reviewThreadsCache(): IReviewThread[] {
return this._reviewThreadsCache;
}
public get reviewThreadsCacheReady(): boolean {
return this._reviewThreadsCacheInitialized;
}
public get hasPendingReview(): boolean {
return this._hasPendingReview;
}
public set hasPendingReview(hasPendingReview: boolean) {
if (this._hasPendingReview !== hasPendingReview) {
this._hasPendingReview = hasPendingReview;
this._onDidChangePendingReviewState.fire(this._hasPendingReview);
}
}
public get showChangesSinceReview() {
return this._showChangesSinceReview;
}
public set showChangesSinceReview(isChangesSinceReview: boolean) {
if (this._showChangesSinceReview !== isChangesSinceReview) {
this._showChangesSinceReview = isChangesSinceReview;
this._fileChanges.clear();
this._onDidChangeChangesSinceReview.fire();
}
}
get comments(): readonly IComment[] {
return this._comments ?? [];
}
set comments(comments: readonly IComment[]) {
this._comments = comments;
this._onDidChange.fire({ comments: true });
}
get fileChangeViewedState(): FileViewedState {
return this._fileChangeViewedState;
}
public isRemoteHeadDeleted?: boolean;
public head: GitHubRef | null;
public isRemoteBaseDeleted?: boolean;
public base: GitHubRef;
protected override stateToStateEnum(state: string) {
let newState = GithubItemStateEnum.Closed;
if (state.toLowerCase() === 'open') {
newState = GithubItemStateEnum.Open;
} else if (state.toLowerCase() === 'merged' || this.item.merged) {
newState = GithubItemStateEnum.Merged;
}
return newState;
}
protected override doUpdate(item: PullRequest): IssueChangeEvent {
const changes = super.doUpdate(item) as IssueChangeEvent;
if (this.isDraft !== item.isDraft) {
changes.draft = true;
this.isDraft = item.isDraft;
}
this.suggestedReviewers = item.suggestedReviewers;
if (item.isRemoteHeadDeleted != null) {
this.isRemoteHeadDeleted = item.isRemoteHeadDeleted;
}
if (item.head) {
this.head = new GitHubRef(item.head.ref, item.head.label, item.head.sha, item.head.repo.cloneUrl, item.head.repo.owner, item.head.repo.name, item.head.repo.isInOrganization);
}
if (item.isRemoteBaseDeleted != null) {
this.isRemoteBaseDeleted = item.isRemoteBaseDeleted;
}
if (item.base) {
this.base = new GitHubRef(item.base.ref, item.base!.label, item.base!.sha, item.base!.repo.cloneUrl, item.base.repo.owner, item.base.repo.name, item.base.repo.isInOrganization);
}
if (item.mergeQueueEntry !== undefined) {
this.mergeQueueEntry = item.mergeQueueEntry ?? undefined;
}
if (item.hasComments !== undefined) {
this._hasComments = item.hasComments;
}
return changes;
}
/**
* Validate if the pull request has a valid HEAD.
* Use only when the method can fail silently, otherwise use `validatePullRequestModel`
*/
isResolved(): this is IResolvedPullRequestModel {
return !!this.head;
}
/**
* Validate if the pull request has a valid HEAD. Show a warning message to users when the pull request is invalid.
* @param message Human readable action execution failure message.
*/
validatePullRequestModel(message?: string): this is IResolvedPullRequestModel {
if (!!this.head) {
return true;
}
const reason = vscode.l10n.t('There is no upstream branch for Pull Request #{0}. View it on GitHub for more details', this.number);
if (message) {
message += `: ${reason}`;
} else {
message = reason;
}
const openString = vscode.l10n.t('Open on GitHub');
vscode.window.showWarningMessage(message, openString).then(action => {
if (action && action === openString) {
vscode.commands.executeCommand('vscode.open', vscode.Uri.parse(this.html_url));
}
});
return false;
}
protected override updateIssueInput(id: string): Object {
return {
pullRequestId: id,
};
}
protected override updateIssueSchema(schema: any): any {
return schema.UpdatePullRequest;
}
/**
* Approve the pull request.
* @param message Optional approval comment text.
*/
async approve(repository: Repository, message?: string): Promise<ReviewEvent> {
// Check that the remote head of the PR branch matches the local head of the PR branch
let remoteHead: string | undefined;
let localHead: string | undefined;
let rejectMessage: string | undefined;
if (this.isActive) {
localHead = repository.state.HEAD?.commit;
remoteHead = (await this.githubRepository.getPullRequest(this.number))?.head?.sha;
rejectMessage = vscode.l10n.t('The remote head of the PR branch has changed. Please pull the latest changes from the remote branch before approving.');
} else {
localHead = this.head?.sha;
remoteHead = (await this.githubRepository.getPullRequest(this.number))?.head?.sha;
rejectMessage = vscode.l10n.t('The remote head of the PR branch has changed. Please refresh the pull request before approving.');
}
if (!remoteHead || remoteHead !== localHead) {
return Promise.reject(rejectMessage);
}
const action: Promise<ReviewEvent> = (await this.getPendingReviewId())
? this.submitReview(ReviewEventEnum.Approve, message)
: this.createReview(ReviewEventEnum.Approve, message);
return action.then(x => {
/* __GDPR__
"pr.approve" : {}
*/
this._telemetry.sendTelemetryEvent('pr.approve');
this._onDidChange.fire({ comments: true, timeline: true });
return x;
});
}
/**
* Request changes on the pull request.
* @param message Optional comment text to leave with the review.
*/
async requestChanges(message?: string): Promise<ReviewEvent> {
const action: ReviewEvent = (await this.getPendingReviewId())
? await this.submitReview(ReviewEventEnum.RequestChanges, message)
: await this.createReview(ReviewEventEnum.RequestChanges, message);
/* __GDPR__
"pr.requestChanges" : {}
*/
this._telemetry.sendTelemetryEvent('pr.requestChanges');
this._onDidChange.fire({ timeline: true, comments: true });
return action;
}
/**
* Close the pull request.
*/
override async close(): Promise<{ item: PullRequest; closedEvent: ClosedEvent }> {
const { octokit, remote } = await this.githubRepository.ensure();
const ret = await octokit.call(octokit.api.pulls.update, {
owner: remote.owner,
repo: remote.repositoryName,
pull_number: this.number,
state: 'closed',
});
/* __GDPR__
"pr.close" : {}
*/
this._telemetry.sendTelemetryEvent('pr.close');
const user = await this.githubRepository.getAuthenticatedUser();
this.state = this.stateToStateEnum(ret.data.state);
// Fire the event with a delay as GitHub needs some time to propagate the changes, we want to make sure any listeners of the event will get the right info when they query
setTimeout(() => this._onDidChange.fire({ state: true }), 1500);
return {
item: convertRESTPullRequestToRawPullRequest(ret.data, this.githubRepository),
closedEvent: {
createdAt: ret.data.closed_at ?? '',
event: EventType.Closed,
id: `${ret.data.id}`,
actor: {
login: user.login,
avatarUrl: user.avatarUrl,
url: user.url
}
}
};
}
/**
* Create a new review.
* @param event The type of review to create, an approval, request for changes, or comment.
* @param message The summary comment text.
*/
private async createReview(event: ReviewEventEnum, message?: string): Promise<ReviewEvent> {
const { octokit, remote } = await this.githubRepository.ensure();
const { data } = await octokit.call(octokit.api.pulls.createReview, {
owner: remote.owner,
repo: remote.repositoryName,
pull_number: this.number,
event: event,
body: message,
});
this._onDidChange.fire({ timeline: true });
return convertRESTReviewEvent(data, this.githubRepository);
}
/**
* Submit an existing review.
* @param event The type of review to create, an approval, request for changes, or comment.
* @param body The summary comment text.
*/
async submitReview(event?: ReviewEventEnum, body?: string): Promise<ReviewEvent> {
let pendingReviewId = await this.getPendingReviewId();
const { mutate, schema } = await this.githubRepository.ensure();
if (!pendingReviewId && (event === ReviewEventEnum.Comment)) {
// Create a new review so that we can comment on it.
pendingReviewId = await this.startReview();
}
if (pendingReviewId) {
const { data } = await mutate<SubmitReviewResponse>({
mutation: schema.SubmitReview,
variables: {
id: pendingReviewId,
event: event || ReviewEventEnum.Comment,
body,
},
});
this.hasPendingReview = false;
await this.updateDraftModeContext();
const reviewEvent = parseGraphQLReviewEvent(data!.submitPullRequestReview.pullRequestReview, this.githubRepository);
const threadWithComment = this._reviewThreadsCache.find(thread =>
thread.comments.length ? (thread.comments[0].pullRequestReviewId === reviewEvent.id) : undefined,
);
if (threadWithComment) {
threadWithComment.comments = reviewEvent.comments;
threadWithComment.viewerCanResolve = true;
this._onDidChangeReviewThreads.fire({ added: [], changed: [threadWithComment], removed: [] });
}
this._onDidChange.fire({ timeline: true, comments: true });
return reviewEvent;
} else {
throw new Error(`Submitting review failed, no pending review for current pull request: ${this.number}.`);
}
}
/**
* Query to see if there is an existing review.
*/
async getPendingReviewId(): Promise<string | undefined> {
const { query, schema } = await this.githubRepository.ensure();
const currentUser = (await this.githubRepository.getAuthenticatedUser()).login;
try {
const { data } = await query<PendingReviewIdResponse>({
query: schema.GetPendingReviewId,
variables: {
pullRequestId: this.item.graphNodeId,
author: currentUser,
},
});
return data.node.reviews.nodes.length > 0 ? data.node.reviews.nodes[0].id : undefined;
} catch (error) {
return;
}
}
async getViewerLatestReviewCommit(): Promise<{ sha: string } | undefined> {
Logger.debug(`Fetch viewers latest review commit`, IssueModel.ID);
const { query, remote, schema } = await this.githubRepository.ensure();
try {
const { data } = await query<LatestReviewCommitResponse>({
query: schema.LatestReviewCommit,
variables: {
owner: remote.owner,
name: remote.repositoryName,
number: this.number,
},
});
if (data.repository === null) {
Logger.error('Unexpected null repository while getting last review commit', PullRequestModel.ID);
}
return data.repository?.pullRequest.viewerLatestReview ? {
sha: data.repository?.pullRequest.viewerLatestReview.commit.oid,
} : undefined;
}
catch (e) {
return undefined;
}
}
/**
* Delete an existing in progress review.
*/
async deleteReview(): Promise<{ deletedReviewId: number; deletedReviewComments: IComment[] }> {
const pendingReviewId = await this.getPendingReviewId();
const { mutate, schema } = await this.githubRepository.ensure();
const { data } = await mutate<DeleteReviewResponse>({
mutation: schema.DeleteReview,
variables: {
input: { pullRequestReviewId: pendingReviewId },
},
});
const { comments, databaseId } = data!.deletePullRequestReview.pullRequestReview;
this.hasPendingReview = false;
await this.updateDraftModeContext();
this.getReviewThreads();
this._onDidChange.fire({ timeline: true });
return {
deletedReviewId: databaseId,
deletedReviewComments: comments.nodes.map(comment => parseGraphQLComment(comment, false, this.githubRepository)),
};
}
/**
* Start a new review.
* @param initialComment The comment text and position information to begin the review with
* @param commitId The optional commit id to start the review on. Defaults to using the current head commit.
*/
async startReview(commitId?: string): Promise<string> {
const { mutate, schema } = await this.githubRepository.ensure();
const { data } = await mutate<StartReviewResponse>({
mutation: schema.StartReview,
variables: {
input: {
body: '',
pullRequestId: this.item.graphNodeId,
commitOID: commitId || this.head?.sha,
},
},
});
if (!data) {
throw new Error('Failed to start review');
}
this.hasPendingReview = true;
return data.addPullRequestReview.pullRequestReview.id;
}
/**
* Creates a new review thread, either adding it to an existing pending review, or creating
* a new review.
* @param body The body of the thread's first comment.
* @param commentPath The path to the file being commented on.
* @param startLine The start line on which to add the comment.
* @param endLine The end line on which to add the comment.
* @param side The side the comment should be deleted on, i.e. the original or modified file.
* @param suppressDraftModeUpdate If a draft mode change should event should be suppressed. In the
* case of a single comment add, the review is created and then immediately submitted, so this prevents
* a "Pending" label from flashing on the comment.
* @returns The new review thread object.
*/
async createReviewThread(
body: string,
commentPath: string,
startLine: number | undefined,
endLine: number | undefined,
side: DiffSide,
suppressDraftModeUpdate?: boolean,
): Promise<IReviewThread | undefined> {
if (!this.validatePullRequestModel('Creating comment failed')) {
return;
}
const pendingReviewId = await this.getPendingReviewId();
const { mutate, schema } = await this.githubRepository.ensure();
const { data } = await mutate<AddReviewThreadResponse>({
mutation: schema.AddReviewThread,
variables: {
input: {
path: commentPath,
body,
pullRequestId: this.graphNodeId,
pullRequestReviewId: pendingReviewId,
startLine: startLine === endLine ? undefined : startLine,
line: (endLine === undefined) ? 0 : endLine,
side,
subjectType: (startLine === undefined || endLine === undefined) ? SubjectType.FILE : SubjectType.LINE
}
}
}, { mutation: schema.LegacyAddReviewThread, deleteProps: ['subjectType'] });
if (!data) {
throw new Error('Creating review thread failed.');
}
if (!data.addPullRequestReviewThread.thread) {
throw new Error('File has been deleted.');
}
if (!suppressDraftModeUpdate) {
this.hasPendingReview = true;
await this.updateDraftModeContext();
}
const thread = data.addPullRequestReviewThread.thread;
const newThread = parseGraphQLReviewThread(thread, this.githubRepository);
this._reviewThreadsCache.push(newThread);
this._onDidChangeReviewThreads.fire({ added: [newThread], changed: [], removed: [] });
this._onDidChange.fire({ timeline: true });
return newThread;
}
/**
* Creates a new comment in reply to an existing comment
* @param body The text of the comment to be created
* @param inReplyTo The id of the comment this is in reply to
* @param isSingleComment Whether this is a single comment, i.e. one that
* will be immediately submitted and so should not show a pending label
* @param commitId The commit id the comment was made on
* @returns The new comment
*/
async createCommentReply(
body: string,
inReplyTo: string,
isSingleComment: boolean,
commitId?: string,
): Promise<IComment | undefined> {
if (!this.validatePullRequestModel('Creating comment failed')) {
return;
}
let pendingReviewId = await this.getPendingReviewId();
if (!pendingReviewId) {
pendingReviewId = await this.startReview(commitId);
}
const { mutate, schema } = await this.githubRepository.ensure();
const { data } = await mutate<AddCommentResponse>({
mutation: schema.AddComment,
variables: {
input: {
pullRequestReviewId: pendingReviewId,
body,
inReplyTo,
commitOID: commitId || this.head?.sha,
},
},
});
if (!data) {
throw new Error('Creating comment reply failed.');
}
const { comment } = data.addPullRequestReviewComment;
const newComment = parseGraphQLComment(comment, false, this.githubRepository);
if (isSingleComment) {
newComment.isDraft = false;
}
const threadWithComment = this._reviewThreadsCache.find(thread =>
thread.comments.some(comment => comment.graphNodeId === inReplyTo),
);
if (threadWithComment) {
threadWithComment.comments.push(newComment);
this._onDidChangeReviewThreads.fire({ added: [], changed: [threadWithComment], removed: [] });
}
this._onDidChange.fire({ timeline: true, comments: true });
return newComment;
}
/**
* Check whether there is an existing pending review and update the context key to control what comment actions are shown.
*/
async validateDraftMode(): Promise<boolean> {
const inDraftMode = !!(await this.getPendingReviewId());
if (inDraftMode !== this.hasPendingReview) {
this.hasPendingReview = inDraftMode;
}
await this.updateDraftModeContext();
return inDraftMode;
}
private async updateDraftModeContext() {
if (this.isActive) {
await vscode.commands.executeCommand('setContext', 'reviewInDraftMode', this.hasPendingReview);
}
}
/**
* Get the timeline events of a pull request, including comments, reviews, commits, merges, deletes, and assigns.
*/
async getTimelineEvents(pullRequestModel: PullRequestModel): Promise<TimelineEvent[]> {
const getTimelineEvents = async () => {
Logger.debug(`Fetch timeline events of PR #${pullRequestModel.number} - enter`, PullRequestModel.ID);
const { query, remote, schema } = await this.githubRepository.ensure();
try {
const { data } = await query<TimelineEventsResponse>({
query: schema.TimelineEvents,
variables: {
owner: remote.owner,
name: remote.repositoryName,
number: pullRequestModel.number,
},
});
if (data.repository === null) {
Logger.error('Unexpected null repository when fetching timeline', PullRequestModel.ID);
}
return data;
} catch (e) {
Logger.error(`Failed to get pull request timeline events: ${e}`, PullRequestModel.ID);
console.log(e);
return undefined;
}
};
const [data, latestReviewCommitInfo, currentUser, reviewThreads] = await Promise.all([
getTimelineEvents(),
this.getViewerLatestReviewCommit(),
(await this.githubRepository.getAuthenticatedUser()).login,
pullRequestModel.getReviewThreads()
]);
const ret = data?.repository?.pullRequest.timelineItems.nodes ?? [];
const events = await parseCombinedTimelineEvents(ret, await this.getCopilotTimelineEvents(pullRequestModel, true), this.githubRepository);
this.addReviewTimelineEventComments(events, reviewThreads);
insertNewCommitsSinceReview(events, latestReviewCommitInfo?.sha, currentUser, pullRequestModel.head);
Logger.debug(`Fetch timeline events of PR #${pullRequestModel.number} - done`, PullRequestModel.ID);
pullRequestModel.timelineEvents = events;
return events;
}
private addReviewTimelineEventComments(events: TimelineEvent[], reviewThreads: IReviewThread[]): void {
interface CommentNode extends IComment {
childComments?: CommentNode[];
}
const reviewEvents = events.filter((e): e is ReviewEvent => e.event === EventType.Reviewed);
const reviewComments = reviewThreads.reduce((previous, current) => (previous as IComment[]).concat(current.comments), []);
const reviewEventsById = reviewEvents.reduce((index, evt) => {
index[evt.id] = evt;
evt.comments = [];
return index;
}, {} as { [key: number]: ReviewEvent });
const commentsById = reviewComments.reduce((index, evt) => {
index[evt.id] = evt;
return index;
}, {} as { [key: number]: CommentNode });
const roots: CommentNode[] = [];
let i = reviewComments.length;
while (i-- > 0) {
const c: CommentNode = reviewComments[i];
if (!c.inReplyToId) {
roots.unshift(c);
continue;
}
const parent = commentsById[c.inReplyToId];
parent.childComments = parent.childComments || [];
parent.childComments = [c, ...(c.childComments || []), ...parent.childComments];
}
roots.forEach(c => {
const review = reviewEventsById[c.pullRequestReviewId!];
if (review) {
review.comments = review.comments.concat(c).concat(c.childComments || []);
}
});
reviewThreads.forEach(thread => {
if (!thread.prReviewDatabaseId || !reviewEventsById[thread.prReviewDatabaseId]) {
return;
}
const prReviewThreadEvent = reviewEventsById[thread.prReviewDatabaseId];
prReviewThreadEvent.reviewThread = {
threadId: thread.id,
canResolve: thread.viewerCanResolve,
canUnresolve: thread.viewerCanUnresolve,
isResolved: thread.isResolved
};
});
const pendingReview = reviewEvents.filter(r => r.state?.toLowerCase() === 'pending')[0];
if (pendingReview) {
// Ensures that pending comments made in reply to other reviews are included for the pending review
pendingReview.comments = reviewComments.filter(c => c.isDraft);
}
}
/**
* Edit an existing review comment.
* @param comment The comment to edit
* @param text The new comment text
*/
async editReviewComment(comment: IComment, text: string): Promise<IComment> {
const { mutate, schema } = await this.githubRepository.ensure();
let threadWithComment = this._reviewThreadsCache.find(thread =>
thread.comments.some(c => c.graphNodeId === comment.graphNodeId),
);
if (!threadWithComment) {
return this.editIssueComment(comment, text);
}
const { data } = await mutate<EditCommentResponse>({
mutation: schema.EditComment,
variables: {
input: {
pullRequestReviewCommentId: comment.graphNodeId,
body: text,
},
},
});
if (!data) {
throw new Error('Editing review comment failed.');
}
const newComment = parseGraphQLComment(
data.updatePullRequestReviewComment.pullRequestReviewComment,
!!comment.isResolved,
this.githubRepository
);
if (threadWithComment) {
const index = threadWithComment.comments.findIndex(c => c.graphNodeId === comment.graphNodeId);
threadWithComment.comments.splice(index, 1, newComment);
this._onDidChangeReviewThreads.fire({ added: [], changed: [threadWithComment], removed: [] });
this._onDidChange.fire({ timeline: true });
}
return newComment;
}
/**
* Deletes a review comment.
* @param commentId The comment id to delete
*/
async deleteReviewComment(commentId: string): Promise<void> {
try {
const { octokit, remote } = await this.githubRepository.ensure();
const id = Number(commentId);
const threadIndex = this._reviewThreadsCache.findIndex(thread => thread.comments.some(c => c.id === id));
if (threadIndex === -1) {
this.deleteIssueComment(commentId);
} else {
await octokit.call(octokit.api.pulls.deleteReviewComment, {
owner: remote.owner,
repo: remote.repositoryName,
comment_id: id,
});
if (threadIndex > -1) {
const threadWithComment = this._reviewThreadsCache[threadIndex];
const index = threadWithComment.comments.findIndex(c => c.id === id);
threadWithComment.comments.splice(index, 1);
if (threadWithComment.comments.length === 0) {
this._reviewThreadsCache.splice(threadIndex, 1);
this._onDidChangeReviewThreads.fire({ added: [], changed: [], removed: [threadWithComment] });
} else {
this._onDidChangeReviewThreads.fire({ added: [], changed: [threadWithComment], removed: [] });
}
this._onDidChange.fire({ timeline: true });
}
}
} catch (e) {
throw new Error(formatError(e));
}
}
private async getFileContent(owner: string, sha: string, file: string): Promise<string | undefined> {
Logger.debug(`Fetch file content - enter`, GitHubRepository.ID);
const { query, remote, schema } = await this.githubRepository.ensure();
const { data } = await query<FileContentResponse>({
query: schema.GetFileContent,
variables: {
owner,
name: remote.repositoryName,
expression: `${sha}:${file}`
}
});
if (!data.repository?.object.text) {
return undefined;
}
Logger.debug(`Fetch file content - end`, GitHubRepository.ID);
return data.repository.object.text;
}
public async compareBaseBranchForMerge(headOwner: string, headRef: string, baseOwner: string, baseRef: string): Promise<IRawFileChange[]> {
const { octokit, remote } = await this.githubRepository.ensure();
// Get the files that would change as part of the merge
const compareData = await octokit.call(octokit.api.repos.compareCommits, {
repo: remote.repositoryName,
owner: headOwner,
base: `${headOwner}:${headRef}`, // flip base and head because we are comparing for a merge to update the PR
head: `${baseOwner}:${baseRef}`,
});
return compareData?.data?.files?.filter<IRawFileChange>((change): change is IRawFileChange => change !== undefined) ?? [];
}
private async getUpdateBranchFiles(baseCommitSha: string, headTreeSha: string, model: ConflictResolutionModel): Promise<IGitTreeItem[]> {
if (this.item.mergeable === PullRequestMergeability.Conflict && (!model.resolvedConflicts || model.resolvedConflicts.size === 0)) {
throw new Error('Pull Request has conflicts but no resolutions were provided.');
}
const { octokit } = await this.githubRepository.ensure();
// Get the files that would change as part of the merge
const compareData = await this.compareBaseBranchForMerge(model.prHeadOwner, model.prHeadBranchName, model.prBaseOwner, baseCommitSha);
const baseTreeSha = (await octokit.call(octokit.api.repos.getCommit, { owner: model.prBaseOwner, repo: model.repositoryName, ref: baseCommitSha })).data.commit.tree.sha;
const baseTree = await octokit.call(octokit.api.git.getTree, { owner: model.prBaseOwner, repo: model.repositoryName, tree_sha: baseTreeSha, recursive: 'true' });
const files: IGitTreeItem[] = (await Promise.all(compareData.map(async (file) => {
if (!file) {
return;
}
const baseTreeData = baseTree.data.tree.find(f => f.path === file.filename);
const baseMode: '100644' | '100755' | '120000' = baseTreeData?.mode as any ?? '100644';
const headTree = await octokit.call(octokit.api.git.getTree, { owner: model.prHeadOwner, repo: model.repositoryName, tree_sha: headTreeSha, recursive: 'true' });
const headTreeData = headTree.data.tree.find(f => f.path === file.filename);
const headMode: '100644' | '100755' | '120000' = headTreeData?.mode as any ?? '100644';
if (file.status === 'removed') {
// The file was removed so we use a null sha to indicate that (per GitHub's API).
// If we've made it this far, we already know that there are no conflicts in the file and it's safe to delete.
return { path: file.filename, sha: null, mode: headTreeData?.mode ?? '100644' };
}
const treeItem: IGitTreeItem = {
path: file.filename,
mode: baseMode
};
const resolvedConflict = model.resolvedConflicts.get(file.filename);
if (resolvedConflict?.resolvedContents !== undefined) {
if (file.status !== 'modified') {
throw new Error(`Only modified file are supported for conflict resolution ${file.filename}: ${file.status}`);
}
if (baseMode !== headMode) {
throw new Error(`Conflict resolution not supported for file with different modes ${file.filename}: ${baseMode} -> ${headMode}`);
}
if (file.previous_filename) {
throw new Error('Conflict resolution not supported for renamed files');
}
treeItem.content = resolvedConflict.resolvedContents;
return treeItem;
}
if ((!file.previous_filename || !this._fileChanges.has(file.previous_filename)) && !this._fileChanges.has(file.filename)) {
// File is not part of the PR, so we don't need to bother getting any content and can just use the sha
treeItem.sha = file.sha;
return treeItem;
}
// File is part of the PR. We have to apply the patch of the base to the head content.
const { data: headData }: { data: IRawFileContent } = await octokit.call(octokit.api.repos.getContent, {
owner: model.prHeadOwner,