forked from microsoft/vscode-pull-request-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreviewManager.ts
More file actions
1304 lines (1092 loc) · 45.9 KB
/
Copy pathreviewManager.ts
File metadata and controls
1304 lines (1092 loc) · 45.9 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 nodePath from 'path';
import * as vscode from 'vscode';
import { parseDiff, parsePatch } from '../common/diffHunk';
import { getDiffLineByPosition, getLastDiffLine, mapCommentsToHead, mapHeadLineToDiffHunkPosition, mapOldPositionToNew, getZeroBased, getAbsolutePosition } from '../common/diffPositionMapping';
import { toReviewUri, fromReviewUri, fromPRUri, ReviewUriParams } from '../common/uri';
import { groupBy, formatError } from '../common/utils';
import { Comment } from '../common/comment';
import { GitChangeType, InMemFileChange } from '../common/file';
import { IPullRequestModel, IPullRequestManager, ITelemetry } from '../github/interface';
import { Repository, GitErrorCodes, Branch } from '../typings/git';
import { PullRequestChangesTreeDataProvider } from './prChangesTreeDataProvider';
import { GitContentProvider } from './gitContentProvider';
import { DiffChangeType } from '../common/diffHunk';
import { GitFileChangeNode, RemoteFileChangeNode, gitFileChangeNodeFilter } from './treeNodes/fileChangeNode';
import Logger from '../common/logger';
import { PullRequestsTreeDataProvider } from './prsTreeDataProvider';
import { providePRDocumentComments, PRNode } from './treeNodes/pullRequestNode';
import { PullRequestOverviewPanel } from '../github/pullRequestOverview';
import { Remote, parseRepositoryRemotes } from '../common/remote';
import { RemoteQuickPickItem } from './quickpick';
export class ReviewManager implements vscode.DecorationProvider {
private static _instance: ReviewManager;
private _documentCommentProvider: vscode.Disposable;
private _workspaceCommentProvider: vscode.Disposable;
private _disposables: vscode.Disposable[];
private _comments: Comment[] = [];
private _localFileChanges: (GitFileChangeNode)[] = [];
private _obsoleteFileChanges: (GitFileChangeNode | RemoteFileChangeNode)[] = [];
private _lastCommitSha: string;
private _updateMessageShown: boolean = false;
private _validateStatusInProgress: Promise<void>;
private _onDidChangeDocumentCommentThreads = new vscode.EventEmitter<vscode.CommentThreadChangedEvent>();
private _onDidChangeWorkspaceCommentThreads = new vscode.EventEmitter<vscode.CommentThreadChangedEvent>();
private _prsTreeDataProvider: PullRequestsTreeDataProvider;
private _prFileChangesProvider: PullRequestChangesTreeDataProvider;
private _statusBarItem: vscode.StatusBarItem;
private _prNumber: number;
private _previousRepositoryState: {
HEAD: Branch | undefined;
remotes: Remote[];
};
constructor(
private _context: vscode.ExtensionContext,
onShouldReload: vscode.Event<any>,
private _repository: Repository,
private _prManager: IPullRequestManager,
private _telemetry: ITelemetry
) {
this._documentCommentProvider = null;
this._workspaceCommentProvider = null;
this._disposables = [];
let gitContentProvider = new GitContentProvider(_repository);
gitContentProvider.registerTextDocumentContentFallback(this.provideTextDocumentContent.bind(this));
this._disposables.push(vscode.workspace.registerTextDocumentContentProvider('review', gitContentProvider));
this._disposables.push(vscode.commands.registerCommand('review.openFile', (value: GitFileChangeNode | vscode.Uri) => {
let params: ReviewUriParams;
let filePath: string;
if (value instanceof GitFileChangeNode) {
params = fromReviewUri(value.filePath);
filePath = value.filePath.path;
} else {
params = fromReviewUri(value);
filePath = value.path;
}
const activeTextEditor = vscode.window.activeTextEditor;
const opts: vscode.TextDocumentShowOptions = {
preserveFocus: false,
viewColumn: vscode.ViewColumn.Active
};
// Check if active text editor has same path as other editor. we cannot compare via
// URI.toString() here because the schemas can be different. Instead we just go by path.
if (activeTextEditor && activeTextEditor.document.uri.path === filePath) {
opts.selection = activeTextEditor.selection;
}
vscode.commands.executeCommand('vscode.open', vscode.Uri.file(nodePath.resolve(this._repository.rootUri.fsPath, params.path)), opts);
}));
this._disposables.push(vscode.commands.registerCommand('pr.openChangedFile', (value: GitFileChangeNode) => {
const openDiff = vscode.workspace.getConfiguration().get('git.openDiffOnClick');
if (openDiff) {
return vscode.commands.executeCommand('pr.openDiffView', value);
} else {
return vscode.commands.executeCommand('review.openFile', value);
}
}));
this._disposables.push(_repository.state.onDidChange(e => {
const oldHead = this._previousRepositoryState.HEAD;
const newHead = this._repository.state.HEAD;
if (!oldHead && !newHead) {
// both oldHead and newHead are undefined
return;
}
let sameUpstream;
if (!oldHead || !newHead) {
sameUpstream = false;
} else {
sameUpstream = !!oldHead.upstream
? newHead.upstream && oldHead.upstream.name === newHead.upstream.name && oldHead.upstream.remote === newHead.upstream.remote
: !newHead.upstream;
}
const sameHead = sameUpstream // falsy if oldHead or newHead is undefined.
&& oldHead.ahead === newHead.ahead
&& oldHead.behind === newHead.behind
&& oldHead.commit === newHead.commit
&& oldHead.name === newHead.name
&& oldHead.remote === newHead.remote
&& oldHead.type === newHead.type;
let remotes = parseRepositoryRemotes(this._repository);
const sameRemotes = this._previousRepositoryState.remotes.length === remotes.length
&& this._previousRepositoryState.remotes.every(remote => remotes.some(r => remote.equals(r)));
if (!sameHead || !sameRemotes) {
this._previousRepositoryState = {
HEAD: this._repository.state.HEAD,
remotes: remotes
};
if (sameHead && !sameRemotes) {
let oldHeadRemote = this._previousRepositoryState.remotes.find(remote => remote.remoteName === oldHead.remote);
let newHeadRemote = remotes.find(remote => remote.remoteName === oldHead.remote);
if ((!oldHeadRemote && !newHeadRemote) || (oldHeadRemote && newHeadRemote && oldHeadRemote.equals(newHeadRemote))
) {
return;
}
}
this.updateState();
}
}));
this._disposables.push(vscode.commands.registerCommand('pr.refreshChanges', _ => {
this.updateComments();
PullRequestOverviewPanel.refresh();
this.prFileChangesProvider.refresh();
}));
this._disposables.push(vscode.commands.registerCommand('pr.refreshPullRequest', (prNode: PRNode) => {
if (prNode.pullRequestModel.equals(this._prManager.activePullRequest)) {
this.updateComments();
}
PullRequestOverviewPanel.refresh();
this._prsTreeDataProvider.refresh(prNode);
}));
this._prsTreeDataProvider = new PullRequestsTreeDataProvider(onShouldReload, _prManager, this._telemetry);
this._disposables.push(this._prsTreeDataProvider);
this._disposables.push(vscode.window.registerDecorationProvider(this));
this._previousRepositoryState = {
HEAD: _repository.state.HEAD,
remotes: parseRepositoryRemotes(this._repository)
};
this.updateState();
this.pollForStatusChange();
}
static get instance() {
return ReviewManager._instance;
}
get prFileChangesProvider() {
if (!this._prFileChangesProvider) {
this._prFileChangesProvider = new PullRequestChangesTreeDataProvider(this._context);
this._disposables.push(this._prFileChangesProvider);
}
return this._prFileChangesProvider;
}
get statusBarItem() {
if (!this._statusBarItem) {
this._statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
}
return this._statusBarItem;
}
set repository(repository: Repository) {
this._repository = repository;
this.updateState();
}
private pollForStatusChange() {
setTimeout(async () => {
if (!this._validateStatusInProgress) {
await this.updateComments();
}
this.pollForStatusChange();
}, 1000 * 30);
}
private async updateState() {
if (!this._validateStatusInProgress) {
this._validateStatusInProgress = this.validateState();
return this._validateStatusInProgress;
} else {
return this._validateStatusInProgress.then(_ => this._validateStatusInProgress = this.validateState());
}
}
private async validateState() {
await this._prManager.updateRepositories();
let branch = this._repository.state.HEAD;
if (!branch) {
this.clear(true);
return;
}
let matchingPullRequestMetadata = await this._prManager.getMatchingPullRequestMetadataForBranch();
if (!matchingPullRequestMetadata) {
Logger.appendLine(`Review> no matching pull request metadata found for current branch ${this._repository.state.HEAD.name}`);
this.clear(true);
return;
}
const hasPushedChanges = branch.commit !== this._lastCommitSha && branch.ahead === 0 && branch.behind === 0;
if (this._prNumber === matchingPullRequestMetadata.prNumber && !hasPushedChanges) {
return;
}
let remote = branch.upstream ? branch.upstream.remote : null;
if (!remote) {
Logger.appendLine(`Review> current branch ${this._repository.state.HEAD.name} hasn't setup remote yet`);
this.clear(true);
return;
}
// we switch to another PR, let's clean up first.
Logger.appendLine(`Review> current branch ${this._repository.state.HEAD.name} is associated with pull request #${matchingPullRequestMetadata.prNumber}`);
this.clear(false);
this._prNumber = matchingPullRequestMetadata.prNumber;
this._lastCommitSha = null;
const { owner, repositoryName } = matchingPullRequestMetadata;
const pr = await this._prManager.resolvePullRequest(owner, repositoryName, this._prNumber);
if (!pr) {
this._prNumber = null;
Logger.appendLine('Review> This PR is no longer valid');
return;
}
this._prManager.activePullRequest = pr;
this._lastCommitSha = pr.head.sha;
await this.getPullRequestData(pr);
await this.prFileChangesProvider.showPullRequestFileChanges(this._prManager, pr, this._localFileChanges, this._comments);
this._onDidChangeDecorations.fire();
Logger.appendLine(`Review> register comments provider`);
this.registerCommentProvider();
this.statusBarItem.text = '$(git-branch) Pull Request #' + this._prNumber;
this.statusBarItem.command = 'pr.openDescription';
Logger.appendLine(`Review> display pull request status bar indicator and refresh pull request tree view.`);
this.statusBarItem.show();
vscode.commands.executeCommand('pr.refreshList');
this._validateStatusInProgress = null;
}
private findMatchedFileByUri(document: vscode.TextDocument): GitFileChangeNode {
const uri = document.uri;
let fileName: string;
let isOutdated = false;
if (uri.scheme === 'review') {
const query = fromReviewUri(uri);
isOutdated = query.isOutdated;
fileName = query.path;
}
if (uri.scheme === 'file') {
fileName = uri.path;
}
if (uri.scheme === 'pr') {
fileName = fromPRUri(uri).fileName;
}
const fileChangesToSearch = isOutdated ? this._obsoleteFileChanges : this._localFileChanges;
const matchedFiles = gitFileChangeNodeFilter(fileChangesToSearch).filter(fileChange => {
if (uri.scheme === 'review' || uri.scheme === 'pr') {
return fileChange.fileName === fileName;
} else {
let absoluteFilePath = vscode.Uri.file(nodePath.resolve(this._repository.rootUri.fsPath, fileChange.fileName));
let targetFilePath = vscode.Uri.file(fileName);
return absoluteFilePath.fsPath === targetFilePath.fsPath;
}
});
if (matchedFiles && matchedFiles.length) {
return matchedFiles[0];
}
}
private async replyToCommentThread(document: vscode.TextDocument, range: vscode.Range, thread: vscode.CommentThread, text: string) {
try {
const matchedFile = this.findMatchedFileByUri(document);
if (!matchedFile) {
throw new Error('Unable to find matching file');
}
const comment = await this._prManager.createCommentReply(this._prManager.activePullRequest, text, thread.threadId);
thread.comments.push({
commentId: comment.id.toString(),
body: new vscode.MarkdownString(comment.body),
userName: comment.user.login,
gravatar: comment.user.avatar_url,
canEdit: comment.canEdit,
canDelete: comment.canDelete
});
matchedFile.comments.push(comment);
this._comments.push(comment);
const workspaceThread = Object.assign({}, thread, { resource: vscode.Uri.file(thread.resource.fsPath) });
this._onDidChangeWorkspaceCommentThreads.fire({
added: [],
changed: [workspaceThread],
removed: []
});
return thread;
} catch (e) {
throw new Error(formatError(e));
}
}
private async createNewCommentThread(document: vscode.TextDocument, range: vscode.Range, text: string) {
try {
const uri = document.uri;
const matchedFile = this.findMatchedFileByUri(document);
const query = uri.query === '' ? undefined : fromReviewUri(uri);
const isBase = query && query.base;
// git diff sha -- fileName
const contentDiff = await this._repository.diffWith(this._lastCommitSha, matchedFile.fileName);
const position = mapHeadLineToDiffHunkPosition(matchedFile.diffHunks, contentDiff, range.start.line + 1, isBase);
if (position < 0) {
throw new Error('Comment position cannot be negative');
}
// there is no thread Id, which means it's a new thread
let rawComment = await this._prManager.createComment(this._prManager.activePullRequest, text, matchedFile.fileName, position);
let comment = {
commentId: rawComment.id.toString(),
body: new vscode.MarkdownString(rawComment.body),
userName: rawComment.user.login,
gravatar: rawComment.user.avatar_url,
canEdit: rawComment.canEdit,
canDelete: rawComment.canDelete
};
let commentThread: vscode.CommentThread = {
threadId: comment.commentId.toString(),
resource: vscode.Uri.file(nodePath.resolve(this._repository.rootUri.fsPath, rawComment.path)),
range: range,
comments: [comment]
};
matchedFile.comments.push(rawComment);
this._comments.push(rawComment);
const workspaceThread = Object.assign({}, commentThread, { resource: vscode.Uri.file(commentThread.resource.fsPath) });
this._onDidChangeWorkspaceCommentThreads.fire({
added: [workspaceThread],
changed: [],
removed: []
});
return commentThread;
} catch (e) {
throw new Error(formatError(e));
}
}
private async editComment(document: vscode.TextDocument, comment: vscode.Comment, text: string): Promise<void> {
try {
const matchedFile = this.findMatchedFileByUri(document);
if (!matchedFile) {
throw new Error('Unable to find matching file');
}
const editedComment = await this._prManager.editReviewComment(this._prManager.activePullRequest, comment.commentId, text);
// Update the cached comments of the file
const matchingCommentIndex = matchedFile.comments.findIndex(c => c.id.toString() === comment.commentId);
if (matchingCommentIndex > -1) {
matchedFile.comments.splice(matchingCommentIndex, 1, editedComment);
const changedThreads = this.fileCommentsToCommentThreads(matchedFile, matchedFile.comments.filter(c => c.position === editedComment.position), vscode.CommentThreadCollapsibleState.Expanded);
this._onDidChangeWorkspaceCommentThreads.fire({
added: [],
changed: changedThreads,
removed: []
});
}
// Also update this._comments
const indexInAllComments = this._comments.findIndex(c => c.id.toString() === comment.commentId);
if (indexInAllComments > -1) {
this._comments.splice(indexInAllComments, 1, editedComment);
}
} catch (e) {
throw new Error(formatError(e));
}
}
private async deleteComment(document: vscode.TextDocument, comment: vscode.Comment): Promise<void> {
try {
const matchedFile = this.findMatchedFileByUri(document);
if (!matchedFile) {
throw new Error('Unable to find matching file');
}
await this._prManager.deleteReviewComment(this._prManager.activePullRequest, comment.commentId);
const matchingCommentIndex = matchedFile.comments.findIndex(c => c.id.toString() === comment.commentId);
if (matchingCommentIndex > -1) {
const [ deletedComment ] = matchedFile.comments.splice(matchingCommentIndex, 1);
const updatedThreadComments = matchedFile.comments.filter(c => c.position === deletedComment.position);
// If the deleted comment was the last in its thread, remove the thread
if (updatedThreadComments.length) {
const changedThreads = this.fileCommentsToCommentThreads(matchedFile, updatedThreadComments, vscode.CommentThreadCollapsibleState.Expanded);
this._onDidChangeWorkspaceCommentThreads.fire({
added: [],
changed: changedThreads,
removed: []
});
} else {
this._onDidChangeWorkspaceCommentThreads.fire({
added: [],
changed: [],
removed: [{
threadId: deletedComment.id.toString(),
resource: vscode.Uri.file(nodePath.resolve(this._repository.rootUri.fsPath, deletedComment.path)),
comments: [],
range: null
}]
});
}
}
const indexInAllComments = this._comments.findIndex(c => c.id.toString() === comment.commentId);
if (indexInAllComments > -1) {
this._comments.splice(indexInAllComments, 1);
}
} catch (e) {
throw new Error(formatError(e));
}
}
private async updateComments(): Promise<void> {
const branch = this._repository.state.HEAD;
if (!branch) { return; }
const matchingPullRequestMetadata = await this._prManager.getMatchingPullRequestMetadataForBranch();
if (!matchingPullRequestMetadata) { return; }
const remote = branch.upstream ? branch.upstream.remote : null;
if (!remote) { return; }
const pr = await this._prManager.resolvePullRequest(matchingPullRequestMetadata.owner, matchingPullRequestMetadata.repositoryName, this._prNumber);
if (!pr) {
Logger.appendLine('Review> This PR is no longer valid');
return;
}
if ((pr.head.sha !== this._lastCommitSha || (branch.behind !== undefined && branch.behind > 0)) && !this._updateMessageShown) {
this._updateMessageShown = true;
let result = await vscode.window.showInformationMessage('There are updates available for this branch.', {}, 'Pull');
if (result === 'Pull') {
await vscode.commands.executeCommand('git.pull');
this._updateMessageShown = false;
}
}
const comments = await this._prManager.getPullRequestComments(this._prManager.activePullRequest);
let added: vscode.CommentThread[] = [];
let removed: vscode.CommentThread[] = [];
let changed: vscode.CommentThread[] = [];
const oldCommentThreads = this.allCommentsToCommentThreads(this._comments, vscode.CommentThreadCollapsibleState.Expanded);
const newCommentThreads = this.allCommentsToCommentThreads(comments, vscode.CommentThreadCollapsibleState.Expanded);
oldCommentThreads.forEach(thread => {
// No current threads match old thread, it has been removed
const matchingThreads = newCommentThreads.filter(newThread => newThread.threadId === thread.threadId);
if (matchingThreads.length === 0) {
removed.push(thread);
}
});
function commentsEditedInThread(oldComments: vscode.Comment[], newComments: vscode.Comment[]): boolean {
return oldComments.some(oldComment => {
const matchingComment = newComments.filter(newComment => newComment.commentId === oldComment.commentId);
if (matchingComment.length !== 1) {
return true;
}
if (matchingComment[0].body.value !== oldComment.body.value) {
return true;
}
return false;
});
}
newCommentThreads.forEach(thread => {
const matchingCommentThread = oldCommentThreads.filter(oldComment => oldComment.threadId === thread.threadId);
// No old threads match this thread, it is new
if (matchingCommentThread.length === 0) {
added.push(thread);
if (thread.resource.scheme === 'file') {
thread.collapsibleState = vscode.CommentThreadCollapsibleState.Collapsed;
}
}
// Check if comment has been updated
matchingCommentThread.forEach(match => {
if (match.comments.length !== thread.comments.length || commentsEditedInThread(matchingCommentThread[0].comments, thread.comments)) {
changed.push(thread);
}
});
});
if (added.length || removed.length || changed.length) {
this._onDidChangeDocumentCommentThreads.fire({
added: added,
removed: removed,
changed: changed
});
this._onDidChangeWorkspaceCommentThreads.fire({
added: added,
removed: removed,
changed: changed
});
this._comments = comments;
this._localFileChanges.forEach(change => {
if (change instanceof GitFileChangeNode) {
change.comments = this._comments.filter(comment => change.fileName === comment.path && comment.position !== null);
}
});
this._onDidChangeDecorations.fire();
}
return Promise.resolve(null);
}
private async getPullRequestData(pr: IPullRequestModel): Promise<void> {
try {
this._comments = await this._prManager.getPullRequestComments(pr);
let activeComments = this._comments.filter(comment => comment.position);
let outdatedComments = this._comments.filter(comment => !comment.position);
const data = await this._prManager.getPullRequestChangedFiles(pr);
await this._prManager.fullfillPullRequestMissingInfo(pr);
let headSha = pr.head.sha;
let mergeBase = pr.mergeBase;
const contentChanges = await parseDiff(data, this._repository, mergeBase);
this._localFileChanges = [];
for (let i = 0; i < contentChanges.length; i++) {
let change = contentChanges[i];
let isPartial = false;
let diffHunks = [];
if (change instanceof InMemFileChange) {
isPartial = change.isPartial;
diffHunks = change.diffHunks;
} else {
try {
const patch = await this._repository.diffBetween(pr.base.sha, pr.head.sha, change.fileName);
diffHunks = parsePatch(patch);
} catch (e) {
Logger.appendLine(`Failed to parse patch for outdated comments: ${e}`);
}
}
const uri = vscode.Uri.parse(change.fileName);
let changedItem = new GitFileChangeNode(
pr,
change.status,
change.fileName,
change.blobUrl,
toReviewUri(uri, null, null, change.status === GitChangeType.DELETE ? '' : pr.head.sha, false, { base: false }),
toReviewUri(uri, null, null, change.status === GitChangeType.ADD ? '' : pr.base.sha, false, { base: true }),
isPartial,
diffHunks,
activeComments.filter(comment => comment.path === change.fileName),
headSha
);
this._localFileChanges.push(changedItem);
}
let commitsGroup = groupBy(outdatedComments, comment => comment.original_commit_id);
this._obsoleteFileChanges = [];
for (let commit in commitsGroup) {
let commentsForCommit = commitsGroup[commit];
let commentsForFile = groupBy(commentsForCommit, comment => comment.path);
for (let fileName in commentsForFile) {
let diffHunks = [];
try {
const patch = await this._repository.diffBetween(pr.base.sha, commit, fileName);
diffHunks = parsePatch(patch);
} catch (e) {
Logger.appendLine(`Failed to parse patch for outdated comments: ${e}`);
}
const oldComments = commentsForFile[fileName];
const uri = vscode.Uri.parse(nodePath.join(`commit~${commit.substr(0, 8)}`, fileName));
const obsoleteFileChange = new GitFileChangeNode(
pr,
GitChangeType.MODIFY,
fileName,
null,
toReviewUri(uri, fileName, null, oldComments[0].original_commit_id, true, { base: false }),
toReviewUri(uri, fileName, null, oldComments[0].original_commit_id, true, { base: true }),
false,
diffHunks,
oldComments,
commit
);
this._obsoleteFileChanges.push(obsoleteFileChange);
}
}
return Promise.resolve(null);
} catch (e) {
Logger.appendLine(`Review> ${e}`);
}
}
private outdatedCommentsToCommentThreads(fileChange: GitFileChangeNode, fileComments: Comment[], collapsibleState: vscode.CommentThreadCollapsibleState): vscode.CommentThread[] {
if (!fileComments || !fileComments.length) {
return [];
}
let ret: vscode.CommentThread[] = [];
let sections = groupBy(fileComments, comment => String(comment.position));
for (let i in sections) {
let comments = sections[i];
const firstComment = comments[0];
let diffLine = getDiffLineByPosition(firstComment.diff_hunks, firstComment.original_position);
if (diffLine) {
firstComment.absolutePosition = diffLine.newLineNumber;
}
const pos = new vscode.Position(getZeroBased(firstComment.absolutePosition), 0);
const range = new vscode.Range(pos, pos);
ret.push({
threadId: firstComment.id.toString(),
resource: fileChange.filePath,
range,
comments: comments.map(comment => {
return {
commentId: comment.id.toString(),
body: new vscode.MarkdownString(comment.body),
userName: comment.user.login,
gravatar: comment.user.avatar_url,
command: {
title: 'View Changes',
command: 'pr.viewChanges',
arguments: [
fileChange
]
},
canEdit: comment.canEdit,
canDelete: comment.canDelete
};
}),
collapsibleState: collapsibleState
});
}
return ret;
}
private fileCommentsToCommentThreads(fileChange: GitFileChangeNode, fileComments: Comment[], collapsibleState: vscode.CommentThreadCollapsibleState): vscode.CommentThread[] {
if (!fileChange) {
return [];
}
if (!fileComments || !fileComments.length) {
return [];
}
let ret: vscode.CommentThread[] = [];
let sections = groupBy(fileComments, comment => String(comment.position));
let command: vscode.Command = null;
if (fileChange.status === GitChangeType.DELETE) {
command = {
title: 'View Changes',
command: 'pr.viewChanges',
arguments: [
fileChange
]
};
}
for (let i in sections) {
let comments = sections[i];
const firstComment = comments[0];
const pos = new vscode.Position(getZeroBased(firstComment.absolutePosition), 0);
const range = new vscode.Range(pos, pos);
ret.push({
threadId: firstComment.id.toString(),
resource: vscode.Uri.file(nodePath.resolve(this._repository.rootUri.fsPath, firstComment.path)),
range,
comments: comments.map(comment => {
return {
commentId: comment.id.toString(),
body: new vscode.MarkdownString(comment.body),
userName: comment.user.login,
gravatar: comment.user.avatar_url,
command: command,
canEdit: comment.canEdit,
canDelete: comment.canDelete
};
}),
collapsibleState: collapsibleState
});
}
return ret;
}
private allCommentsToCommentThreads(comments: Comment[], collapsibleState: vscode.CommentThreadCollapsibleState): vscode.CommentThread[] {
if (!comments || !comments.length) {
return [];
}
let fileCommentGroups = groupBy(comments, comment => comment.path);
let ret: vscode.CommentThread[] = [];
for (let file in fileCommentGroups) {
let fileComments = fileCommentGroups[file];
let matchedFiles = gitFileChangeNodeFilter(this._localFileChanges).filter(fileChange => fileChange.fileName === file);
if (matchedFiles && matchedFiles.length) {
return this.fileCommentsToCommentThreads(matchedFiles[0], fileComments, collapsibleState);
} else {
return [];
}
}
return ret;
}
_onDidChangeDecorations: vscode.EventEmitter<vscode.Uri | vscode.Uri[]> = new vscode.EventEmitter<vscode.Uri | vscode.Uri[]>();
onDidChangeDecorations: vscode.Event<vscode.Uri | vscode.Uri[]> = this._onDidChangeDecorations.event;
provideDecoration(uri: vscode.Uri, token: vscode.CancellationToken): vscode.ProviderResult<vscode.DecorationData> {
let fileName = uri.path;
let matchingComments = this._comments.filter(comment => nodePath.resolve(this._repository.rootUri.fsPath, comment.path) === fileName && comment.position !== null);
if (matchingComments && matchingComments.length) {
return {
bubble: false,
title: 'Commented',
letter: '◆',
priority: 2
};
}
return undefined;
}
private registerCommentProvider() {
this._documentCommentProvider = vscode.workspace.registerDocumentCommentProvider({
onDidChangeCommentThreads: this._onDidChangeDocumentCommentThreads.event,
provideDocumentComments: async (document: vscode.TextDocument, token: vscode.CancellationToken): Promise<vscode.CommentInfo> => {
let ranges: vscode.Range[] = [];
let matchingComments: Comment[];
if (document.uri.scheme === 'file') {
// local file, we only provide active comments
// TODO. for comments in deleted ranges, they should show on top of the first line.
const fileName = document.uri.fsPath;
const matchedFiles = gitFileChangeNodeFilter(this._localFileChanges).filter(fileChange => nodePath.resolve(this._repository.rootUri.fsPath, fileChange.fileName) === fileName);
let matchedFile: GitFileChangeNode;
if (matchedFiles && matchedFiles.length) {
matchedFile = matchedFiles[0];
let contentDiff: string;
if (document.isDirty) {
const documentText = document.getText();
const details = await this._repository.getObjectDetails(this._lastCommitSha, matchedFile.fileName);
const idAtLastCommit = details.object;
const idOfCurrentText = await this._repository.hashObject(documentText);
// git diff <blobid> <blobid>
contentDiff = await this._repository.diffBlobs(idAtLastCommit, idOfCurrentText);
} else {
// git diff sha -- fileName
contentDiff = await this._repository.diffWith(this._lastCommitSha, matchedFile.fileName);
}
matchingComments = this._comments.filter(comment => nodePath.resolve(this._repository.rootUri.fsPath, comment.path) === fileName);
matchingComments = mapCommentsToHead(matchedFile.diffHunks, contentDiff, matchingComments);
let diffHunks = matchedFile.diffHunks;
for (let i = 0; i < diffHunks.length; i++) {
let diffHunk = diffHunks[i];
let start = mapOldPositionToNew(contentDiff, diffHunk.newLineNumber);
let end = mapOldPositionToNew(contentDiff, diffHunk.newLineNumber + diffHunk.newLength - 1);
if (start > 0 && end > 0) {
ranges.push(new vscode.Range(start - 1, 0, end - 1, 0));
}
}
}
return {
threads: this.fileCommentsToCommentThreads(matchedFile, matchingComments, vscode.CommentThreadCollapsibleState.Collapsed),
commentingRanges: ranges,
};
}
if (document.uri.scheme === 'pr') {
return providePRDocumentComments(document, this._prNumber, this._localFileChanges);
}
if (document.uri.scheme === 'review') {
// we should check whehter the docuemnt is original or modified.
let query = fromReviewUri(document.uri);
let isBase = query.base;
let matchedFile = this.findMatchedFileChange(this._localFileChanges, document.uri);
if (matchedFile) {
matchingComments = matchedFile.comments;
matchingComments.forEach(comment => { comment.absolutePosition = getAbsolutePosition(comment, matchedFile.diffHunks, isBase); });
let diffHunks = matchedFile.diffHunks;
for (let i = 0; i < diffHunks.length; i++) {
let diffHunk = diffHunks[i];
let startingLine: number;
let length: number;
if (isBase) {
startingLine = getZeroBased(diffHunk.oldLineNumber);
length = getZeroBased(diffHunk.oldLength);
} else {
startingLine = getZeroBased(diffHunk.newLineNumber);
length = getZeroBased(diffHunk.newLength);
}
ranges.push(new vscode.Range(startingLine, 1, startingLine + length, 1));
}
return {
threads: this.fileCommentsToCommentThreads(matchedFile, matchingComments.filter(comment => comment.absolutePosition > 0), vscode.CommentThreadCollapsibleState.Expanded),
commentingRanges: ranges,
};
}
// comments are outdated
matchedFile = this.findMatchedFileChange(this._obsoleteFileChanges, document.uri);
let comments = [];
if (!matchedFile) {
// The file may be a change from a specific commit, check the comments themselves to see if they match it, as obsolete file changs
// may not contain it
try {
query = fromReviewUri(document.uri);
comments = this._comments.filter(comment => comment.path === query.path && `${comment.original_commit_id}^` === query.commit);
} catch (_) {
// Do nothing
}
if (!comments.length) {
return null;
}
} else {
comments = matchedFile.comments;
}
let sections = groupBy(comments, comment => String(comment.original_position)); // comment.position is null in this case.
let ret: vscode.CommentThread[] = [];
for (let i in sections) {
let commentGroup = sections[i];
const firstComment = commentGroup[0];
let diffLine = getLastDiffLine(firstComment.diff_hunk);
const lineNumber = isBase
? diffLine.oldLineNumber
: diffLine.oldLineNumber > 0
? -1
: diffLine.newLineNumber;
if (lineNumber < 0) {
continue;
}
const range = new vscode.Range(new vscode.Position(lineNumber, 0), new vscode.Position(lineNumber, 0));
ret.push({
threadId: firstComment.id,
resource: vscode.Uri.file(nodePath.resolve(this._repository.rootUri.fsPath, firstComment.path)),
range,
comments: commentGroup.map(comment => {
return {
commentId: comment.id,
body: new vscode.MarkdownString(comment.body),
userName: comment.user.login,
gravatar: comment.user.avatar_url,
canEdit: comment.canEdit,
canDelete: comment.canDelete
};
}),
collapsibleState: vscode.CommentThreadCollapsibleState.Expanded
});
return {
threads: ret
};
}
}
},
createNewCommentThread: this.createNewCommentThread.bind(this),
replyToCommentThread: this.replyToCommentThread.bind(this),
editComment: this.editComment.bind(this),
deleteComment: this.deleteComment.bind(this)
});
this._workspaceCommentProvider = vscode.workspace.registerWorkspaceCommentProvider({
onDidChangeCommentThreads: this._onDidChangeWorkspaceCommentThreads.event,
provideWorkspaceComments: async (token: vscode.CancellationToken) => {
const comments = await Promise.all(gitFileChangeNodeFilter(this._localFileChanges).map(async fileChange => {
return this.fileCommentsToCommentThreads(fileChange, fileChange.comments, vscode.CommentThreadCollapsibleState.Expanded);
}));
const outdatedComments = gitFileChangeNodeFilter(this._obsoleteFileChanges).map(fileChange => {
return this.outdatedCommentsToCommentThreads(fileChange, fileChange.comments, vscode.CommentThreadCollapsibleState.Expanded);
});
return [...comments, ...outdatedComments].reduce((prev, curr) => prev.concat(curr), []);
}
});
}
private findMatchedFileChange(fileChanges: (GitFileChangeNode | RemoteFileChangeNode)[], uri: vscode.Uri): GitFileChangeNode {
let query = fromReviewUri(uri);
let matchedFiles = fileChanges.filter(fileChange => {
if (fileChange instanceof RemoteFileChangeNode) {
return false;
}
if (fileChange.fileName !== query.path) {
return false;
}
let q = JSON.parse(fileChange.filePath.query);
if (q.commit === query.commit) {
return true;
}
q = JSON.parse(fileChange.parentFilePath.query);
if (q.commit === query.commit) {
return true;
}