forked from microsoft/vscode-pull-request-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpullRequestManager.ts
More file actions
1032 lines (870 loc) · 35.3 KB
/
Copy pathpullRequestManager.ts
File metadata and controls
1032 lines (870 loc) · 35.3 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 vscode from 'vscode';
import * as Github from '@octokit/rest';
import { CredentialStore } from './credentials';
import { Comment } from '../common/comment';
import { Remote, parseRepositoryRemotes } from '../common/remote';
import { TimelineEvent, EventType, isReviewEvent, isCommitEvent } from '../common/timelineEvent';
import { GitHubRepository, PULL_REQUEST_PAGE_SIZE } from './githubRepository';
import { IPullRequestManager, IPullRequestModel, IPullRequestsPagingOptions, PRType, ReviewEvent, ITelemetry, IPullRequestEditData, PullRequest, IRawFileChange } from './interface';
import { PullRequestGitHelper } from './pullRequestGitHelper';
import { PullRequestModel } from './pullRequestModel';
import { parserCommentDiffHunk } from '../common/diffHunk';
import { GitHubManager } from '../authentication/githubServer';
import { formatError, uniqBy, Predicate, groupBy } from '../common/utils';
import { Repository, RefType, UpstreamRef, Branch } from '../typings/git';
import Logger from '../common/logger';
interface PageInformation {
pullRequestPage: number;
hasMorePages: boolean;
}
interface RestErrorResult {
errors: RestError[];
message: string;
}
interface RestError {
code: string;
field: string;
resource: string;
}
export class NoGitHubReposError extends Error {
constructor(public repository: Repository) {
super();
}
get message() {
return `${this.repository.rootUri.toString()} has no GitHub remotes`;
}
}
export class DetachedHeadError extends Error {
constructor(public repository: Repository) {
super();
}
get message() {
return `${this.repository.rootUri.toString()} has a detached HEAD (create a branch first)`;
}
}
export class BadUpstreamError extends Error {
constructor(
public branchName: string,
public upstreamRef: UpstreamRef,
public problem: string) {
super();
}
get message() {
const {upstreamRef: {remote, name}, branchName, problem} = this;
return `The upstream ref ${remote}/${name} for branch ${branchName} ${problem}.`;
}
}
const SETTINGS_NAMESPACE = 'githubPullRequests';
const LOG_LEVEL_SETTING = 'includeRemotes';
const enum IncludeRemote {
Default,
All
}
export class PullRequestManager implements IPullRequestManager {
static ID = 'PullRequestManager';
private _activePullRequest?: IPullRequestModel;
private _credentialStore: CredentialStore;
private _githubRepositories: GitHubRepository[];
private _githubManager: GitHubManager;
private _repositoryPageInformation: Map<string, PageInformation> = new Map<string, PageInformation>();
private _includeRemotes: IncludeRemote;
private _onDidChangeActivePullRequest = new vscode.EventEmitter<void>();
readonly onDidChangeActivePullRequest: vscode.Event<void> = this._onDidChangeActivePullRequest.event;
constructor(
private _repository: Repository,
private readonly _telemetry: ITelemetry,
) {
this._githubRepositories = [];
this._credentialStore = new CredentialStore(this._telemetry);
this._githubManager = new GitHubManager();
this._includeRemotes = IncludeRemote.Default;
vscode.workspace.onDidChangeConfiguration(() => {
let oldIncludeRemote = this._includeRemotes;
this.getIncludeRemoteConfig();
if (this._includeRemotes !== oldIncludeRemote) {
this.updateRepositories();
}
});
this.getIncludeRemoteConfig();
}
private getIncludeRemoteConfig() {
let includeRemotes = vscode.workspace.getConfiguration(SETTINGS_NAMESPACE).get<string>(LOG_LEVEL_SETTING);
switch (includeRemotes) {
case 'default':
this._includeRemotes = IncludeRemote.Default;
break;
case 'all':
this._includeRemotes = IncludeRemote.All;
default:
break;
}
}
get activePullRequest() {
return this._activePullRequest;
}
set activePullRequest(pullRequest: IPullRequestModel) {
this._activePullRequest = pullRequest;
this._onDidChangeActivePullRequest.fire();
}
get repository(): Repository {
return this._repository;
}
set repository(repository: Repository) {
this._repository = repository;
}
async clearCredentialCache(): Promise<void> {
this._credentialStore.reset();
}
async updateRepositories(): Promise<void> {
Logger.debug('update repositories', PullRequestManager.ID);
const remotes = parseRepositoryRemotes(this.repository);
const potentialRemotes = remotes.filter(remote => remote.host);
let gitHubRemotes = await Promise.all(potentialRemotes.map(remote => this._githubManager.isGitHub(remote.gitProtocol.normalizeUri())))
.then(results => potentialRemotes.filter((_, index, __) => results[index]))
.catch(e => {
Logger.appendLine(`Resolving GitHub remotes failed: ${formatError(e)}`);
vscode.window.showErrorMessage(`Resolving GitHub remotes failed: ${formatError(e)}`);
return [];
});
gitHubRemotes = uniqBy(gitHubRemotes, remote => remote.gitProtocol.normalizeUri().toString());
if (gitHubRemotes.length) {
await vscode.commands.executeCommand('setContext', 'github:hasGitHubRemotes', true);
Logger.appendLine('Found GitHub remote');
} else {
await vscode.commands.executeCommand('setContext', 'github:hasGitHubRemotes', false);
Logger.appendLine('No GitHub remotes found');
return;
}
let serverAuthPromises = [];
for (let server of uniqBy(gitHubRemotes, remote => remote.gitProtocol.normalizeUri().authority)) {
serverAuthPromises.push(this._credentialStore.hasOctokit(server).then(authd => {
if (!authd) {
this._credentialStore.loginWithConfirmation(server);
}
}));
}
// Make sure authentication is set up for all the servers that the remotes are pointing to
// this will ask the user to sign in if there's no credentials for a server, once per server
await Promise.all(serverAuthPromises).catch(e => {
Logger.appendLine(`serverAuthPromises failed: ${formatError(e)}`);
});
let repositories = [];
let resolveRemotePromises = [];
let userCreatedRemoteNames = this._includeRemotes === IncludeRemote.All ? (gitHubRemotes as Remote[]) : await PullRequestGitHelper.getUserCreatedRemotes(this.repository, (gitHubRemotes as Remote[]));
userCreatedRemoteNames.forEach(remote => {
const repository = new GitHubRepository(remote, this._credentialStore);
resolveRemotePromises.push(repository.resolveRemote());
repositories.push(repository);
});
return Promise.all(resolveRemotePromises).then(_ => {
this._githubRepositories = repositories;
for (let repository of this._githubRepositories) {
const remoteId = repository.remote.url.toString();
if (!this._repositoryPageInformation.get(remoteId)) {
this._repositoryPageInformation.set(remoteId, {
pullRequestPage: 1,
hasMorePages: null
});
}
}
return Promise.resolve();
});
}
getGitHubRemotes(): Remote[] {
const githubRepositories = this._githubRepositories;
if (!githubRepositories || !githubRepositories.length) {
return [];
}
return githubRepositories.map(repository => repository.remote);
}
async authenticate(): Promise<boolean> {
let ret = false;
this._credentialStore.reset();
for (let repository of uniqBy(this._githubRepositories, x => x.remote.normalizedHost)) {
ret = await repository.authenticate() || ret;
}
return ret;
}
async getLocalPullRequests(): Promise<IPullRequestModel[]> {
const githubRepositories = this._githubRepositories;
if (!githubRepositories || !githubRepositories.length) {
return [];
}
const localBranches = this.repository.state.refs
.filter(r => r.type === RefType.Head && r.name)
.map(r => r.name);
const promises = localBranches.map(async localBranchName => {
const matchingPRMetadata = await PullRequestGitHelper.getMatchingPullRequestMetadataForBranch(this.repository, localBranchName);
if (matchingPRMetadata) {
const { owner, prNumber } = matchingPRMetadata;
const githubRepo = githubRepositories.find(repo => repo.remote.owner.toLocaleLowerCase() === owner.toLocaleLowerCase());
if (githubRepo) {
const pullRequest: PullRequestModel = await githubRepo.getPullRequest(prNumber);
if (pullRequest) {
pullRequest.localBranchName = localBranchName;
return pullRequest;
}
}
}
return Promise.resolve(null);
});
return Promise.all(promises).then(values => {
return values.filter(value => value !== null);
});
}
async deleteLocalPullRequest(pullRequest: PullRequestModel, force?: boolean): Promise<void> {
await this.repository.deleteBranch(pullRequest.localBranchName, force);
let remoteName: string = null;
try {
remoteName = await this.repository.getConfig(`branch.${pullRequest.localBranchName}.remote`);
} catch (e) {}
if (!remoteName) {
return;
}
// If the extension created a remote for the branch, remove it if there are no other branches associated with it
const isPRRemote = await PullRequestGitHelper.isRemoteCreatedForPullRequest(this.repository, remoteName);
if (isPRRemote) {
const configs = await this.repository.getConfigs();
const hasOtherAssociatedBranches = configs
.some(({ key, value }) => /^branch.*\.remote$/.test(key) && value === remoteName);
if (!hasOtherAssociatedBranches) {
await this.repository.removeRemote(remoteName);
}
}
this._telemetry.on('branch.delete');
}
async getPullRequests(type: PRType, options: IPullRequestsPagingOptions = { fetchNextPage: false }): Promise<[IPullRequestModel[], boolean]> {
let githubRepositories = this._githubRepositories;
if (!githubRepositories || !githubRepositories.length) {
return [[], false];
}
if (!options.fetchNextPage) {
for (let repository of this._githubRepositories) {
this._repositoryPageInformation.set(repository.remote.url.toString(), {
pullRequestPage: 1,
hasMorePages: null
});
}
}
githubRepositories = githubRepositories.filter(repo => this._repositoryPageInformation.get(repo.remote.url.toString()).hasMorePages !== false);
let pullRequests: PullRequestModel[] = [];
let numPullRequests = 0;
let hasMorePages = false;
for (let i = 0; i < githubRepositories.length; i++) {
if (numPullRequests >= PULL_REQUEST_PAGE_SIZE) {
hasMorePages = true;
break;
}
const githubRepository = githubRepositories[i];
const remote = githubRepository.remote.remoteName;
const shouldLoad = this._includeRemotes === IncludeRemote.All || !(await PullRequestGitHelper.isRemoteCreatedForPullRequest(this.repository, remote));
if (shouldLoad) {
const pageInformation = this._repositoryPageInformation.get(githubRepository.remote.url.toString());
while (numPullRequests < PULL_REQUEST_PAGE_SIZE && pageInformation.hasMorePages !== false) {
const pullRequestData = await githubRepository.getPullRequests(type, pageInformation.pullRequestPage);
if (!pullRequestData) {
break;
}
numPullRequests += pullRequestData.pullRequests.length;
pullRequests = pullRequests.concat(...pullRequestData.pullRequests);
pageInformation.hasMorePages = pullRequestData.hasMorePages;
hasMorePages = hasMorePages || pageInformation.hasMorePages;
pageInformation.pullRequestPage++;
}
}
}
return [pullRequests, hasMorePages];
}
public mayHaveMorePages(): boolean {
return this._githubRepositories.some(repo => this._repositoryPageInformation.get(repo.remote.url.toString()).hasMorePages !== false);
}
async getStatusChecks(pullRequest: IPullRequestModel): Promise<Github.ReposGetCombinedStatusForRefResponse> {
const { remote, octokit } = await (pullRequest as PullRequestModel).githubRepository.ensure();
const result = await octokit.repos.getCombinedStatusForRef({
owner: remote.owner,
repo: remote.repositoryName,
ref: pullRequest.head.sha
});
return result.data;
}
async getPullRequestComments(pullRequest: IPullRequestModel): Promise<Comment[]> {
Logger.debug(`Fetch comments of PR #${pullRequest.prNumber} - enter`, PullRequestManager.ID);
const { remote, octokit } = await (pullRequest as PullRequestModel).githubRepository.ensure();
const reviewData = await octokit.pullRequests.getComments({
owner: remote.owner,
repo: remote.repositoryName,
number: pullRequest.prNumber,
per_page: 100
});
Logger.debug(`Fetch comments of PR #${pullRequest.prNumber} - done`, PullRequestManager.ID);
const rawComments = reviewData.data.map(comment => this.addCommentPermissions(comment, remote));
return parserCommentDiffHunk(rawComments);
}
async getPullRequestCommits(pullRequest: IPullRequestModel): Promise<Github.PullRequestsGetCommitsResponseItem[]> {
try {
Logger.debug(`Fetch commits of PR #${pullRequest.prNumber} - enter`, PullRequestManager.ID);
const { remote, octokit } = await (pullRequest as PullRequestModel).githubRepository.ensure();
const commitData = await octokit.pullRequests.getCommits({
number: pullRequest.prNumber,
owner: remote.owner,
repo: remote.repositoryName
});
Logger.debug(`Fetch commits of PR #${pullRequest.prNumber} - done`, PullRequestManager.ID);
return commitData.data;
} catch (e) {
vscode.window.showErrorMessage(`Fetching commits failed: ${formatError(e)}`);
return [];
}
}
async getCommitChangedFiles(pullRequest: IPullRequestModel, commit: Github.PullRequestsGetCommitsResponseItem): Promise<Github.ReposGetCommitResponseFilesItem[]> {
try {
Logger.debug(`Fetch file changes of commit ${commit.sha} in PR #${pullRequest.prNumber} - enter`, PullRequestManager.ID);
const { octokit, remote } = await (pullRequest as PullRequestModel).githubRepository.ensure();
const fullCommit = await octokit.repos.getCommit({
owner: remote.owner,
repo: remote.repositoryName,
sha: commit.sha
});
Logger.debug(`Fetch file changes of commit ${commit.sha} in PR #${pullRequest.prNumber} - done`, PullRequestManager.ID);
return fullCommit.data.files.filter(file => !!file.patch);
} catch (e) {
vscode.window.showErrorMessage(`Fetching commit file changes failed: ${formatError(e)}`);
return [];
}
}
async getReviewComments(pullRequest: IPullRequestModel, reviewId: number): Promise<Comment[]> {
Logger.debug(`Fetch comments of review #${reviewId} in PR #${pullRequest.prNumber} - enter`, PullRequestManager.ID);
const { octokit, remote } = await (pullRequest as PullRequestModel).githubRepository.ensure();
const reviewData = await octokit.pullRequests.getReviewComments({
owner: remote.owner,
repo: remote.repositoryName,
number: pullRequest.prNumber,
review_id: reviewId
});
Logger.debug(`Fetch comments of review #${reviewId} in PR #${pullRequest.prNumber} - `, PullRequestManager.ID);
const rawComments = reviewData.data.map(comment => this.addCommentPermissions(comment, remote));
return parserCommentDiffHunk(rawComments);
}
async getTimelineEvents(pullRequest: IPullRequestModel): Promise<TimelineEvent[]> {
Logger.debug(`Fetch timeline events of PR #${pullRequest.prNumber} - enter`, PullRequestManager.ID);
const { octokit, remote } = await (pullRequest as PullRequestModel).githubRepository.ensure();
let ret = await octokit.issues.getEventsTimeline({
owner: remote.owner,
repo: remote.repositoryName,
number: pullRequest.prNumber,
per_page: 100
});
Logger.debug(`Fetch timeline events of PR #${pullRequest.prNumber} - done`, PullRequestManager.ID);
return await this.parseTimelineEvents(pullRequest, remote, ret.data);
}
async getIssueComments(pullRequest: IPullRequestModel): Promise<Github.IssuesGetCommentsResponseItem[]> {
Logger.debug(`Fetch issue comments of PR #${pullRequest.prNumber} - enter`, PullRequestManager.ID);
const { octokit, remote } = await (pullRequest as PullRequestModel).githubRepository.ensure();
const promise = await octokit.issues.getComments({
owner: remote.owner,
repo: remote.repositoryName,
number: pullRequest.prNumber,
per_page: 100
});
Logger.debug(`Fetch issue comments of PR #${pullRequest.prNumber} - done`, PullRequestManager.ID);
return promise.data;
}
async createIssueComment(pullRequest: IPullRequestModel, text: string): Promise<Github.IssuesCreateCommentResponse> {
const { octokit, remote } = await (pullRequest as PullRequestModel).githubRepository.ensure();
const promise = await octokit.issues.createComment({
body: text,
number: pullRequest.prNumber,
owner: remote.owner,
repo: remote.repositoryName
});
return this.addCommentPermissions(promise.data as Comment, remote);
}
async createCommentReply(pullRequest: IPullRequestModel, body: string, reply_to: string): Promise<Comment> {
const { octokit, remote } = await (pullRequest as PullRequestModel).githubRepository.ensure();
try {
let ret = await octokit.pullRequests.createCommentReply({
owner: remote.owner,
repo: remote.repositoryName,
number: pullRequest.prNumber,
body: body,
in_reply_to: Number(reply_to)
});
return this.addCommentPermissions(ret.data, remote);
} catch (e) {
this.handleError(e);
}
}
async createComment(pullRequest: IPullRequestModel, body: string, path: string, position: number): Promise<Comment> {
const { octokit, remote } = await (pullRequest as PullRequestModel).githubRepository.ensure();
try {
let ret = await octokit.pullRequests.createComment({
owner: remote.owner,
repo: remote.repositoryName,
number: pullRequest.prNumber,
body: body,
commit_id: pullRequest.head.sha,
path: path,
position: position
});
return this.addCommentPermissions(ret.data, remote);
} catch (e) {
this.handleError(e);
}
}
async getPullRequestDefaults(): Promise<Github.PullRequestsCreateParams> {
if (!this.repository.state.HEAD) {
throw new DetachedHeadError(this.repository);
}
const {origin} = this;
const meta = await origin.getMetadata();
const parent = meta.fork
? meta.parent
: await (this.findRepo(byRemoteName('upstream')) || origin).getMetadata();
const branchName = this.repository.state.HEAD.name;
const {title, body} = titleAndBodyFrom(await this.getHeadCommitMessage());
return {
title, body,
owner: parent.owner.login,
repo: parent.name,
head: `${meta.owner.login}:${branchName}`,
base: parent.default_branch,
};
}
async getMetadata(remote: string): Promise<any> {
const repo = this.findRepo(byRemoteName(remote));
return repo && repo.getMetadata();
}
async getHeadCommitMessage(): Promise<string> {
const {repository} = this;
const {message} = await repository.getCommit(repository.state.HEAD.commit);
return message;
}
get origin(): GitHubRepository {
if (!this._githubRepositories.length) {
throw new NoGitHubReposError(this.repository);
}
const {upstreamRef} = this;
if (upstreamRef) {
// If our current branch has an upstream ref set, find its GitHubRepository.
const upstream = this.findRepo(byRemoteName(upstreamRef.remote));
if (!upstream) {
// No GitHubRepository? We currently won't try pushing elsewhere,
// so fail.
throw new BadUpstreamError(
this.repository.state.HEAD.name,
upstreamRef,
'is not a GitHub repo');
}
// Otherwise, we'll push upstream.
return upstream;
}
// If no upstream is set, let's go digging.
const [first, ...rest] = this._githubRepositories;
return !rest.length // Is there only one GitHub remote?
? first // I GUESS THAT'S WHAT WE'RE GOING WITH, THEN.
: // Otherwise, let's try...
this.findRepo(byRemoteName('origin')) || // by convention
this.findRepo(ownedByMe) || // bc maybe we can push there
first; // out of raw desperation
}
findRepo(where: Predicate<GitHubRepository>): GitHubRepository | undefined {
return this._githubRepositories.filter(where)[0];
}
get upstreamRef(): UpstreamRef | undefined {
const {HEAD} = this.repository.state;
return HEAD && HEAD.upstream;
}
async createPullRequest(params: Github.PullRequestsCreateParams): Promise<IPullRequestModel> {
try {
const repo = this._githubRepositories.find(r => r.remote.owner === params.owner && r.remote.repositoryName === params.repo);
if (!repo) {
throw new Error(`No matching repository ${params.repo} found for ${params.owner}`);
}
await repo.ensure();
const { title, body } = titleAndBodyFrom(await this.getHeadCommitMessage());
if (!params.title) {
params.title = title;
}
if (!params.body) {
params.body = body;
}
// Create PR
let { data } = await repo.octokit.pullRequests.create(params);
const item: PullRequest = {
number: data.number,
body: data.body,
title: data.title,
html_url: data.html_url,
user: data.user,
labels: [],
state: data.state,
merged: false,
assignee: data.assignee,
created_at: data.created_at,
updated_at: data.updated_at,
comments: 0,
commits: 0,
head: data.head,
base: data.base
};
const pullRequestModel = new PullRequestModel(repo, repo.remote, item);
const branchNameSeparatorIndex = params.head.indexOf(':');
const branchName = params.head.slice(branchNameSeparatorIndex + 1);
await PullRequestGitHelper.associateBranchWithPullRequest(this._repository, pullRequestModel, branchName);
return pullRequestModel;
} catch (e) {
Logger.appendLine(`GitHubRepository> Creating pull requests failed: ${e}`);
vscode.window.showWarningMessage(`Creating pull requests for '${params.head}' failed: ${formatError(e)}`);
return null;
}
}
async editIssueComment(pullRequest: IPullRequestModel, commentId: string, text: string): Promise<Comment> {
try {
const { octokit, remote } = await (pullRequest as PullRequestModel).githubRepository.ensure();
const ret = await octokit.issues.editComment({
owner: remote.owner,
repo: remote.repositoryName,
body: text,
comment_id: Number(commentId)
});
return this.addCommentPermissions(ret.data as Comment, remote);
} catch (e) {
throw new Error(formatError(e));
}
}
async editReviewComment(pullRequest: IPullRequestModel, commentId: string, text: string): Promise<Comment> {
try {
const { octokit, remote } = await (pullRequest as PullRequestModel).githubRepository.ensure();
const ret = await octokit.pullRequests.editComment({
owner: remote.owner,
repo: remote.repositoryName,
body: text,
comment_id: Number(commentId)
});
return this.addCommentPermissions(ret.data, remote);
} catch (e) {
throw new Error(formatError(e));
}
}
async deleteIssueComment(pullRequest: IPullRequestModel, commentId: string): Promise<void> {
try {
const { octokit, remote } = await (pullRequest as PullRequestModel).githubRepository.ensure();
await octokit.issues.deleteComment({
owner: remote.owner,
repo: remote.repositoryName,
comment_id: Number(commentId)
});
} catch (e) {
throw new Error(formatError(e));
}
}
async deleteReviewComment(pullRequest: IPullRequestModel, commentId: string): Promise<void> {
try {
const { octokit, remote } = await (pullRequest as PullRequestModel).githubRepository.ensure();
await octokit.pullRequests.deleteComment({
owner: remote.owner,
repo: remote.repositoryName,
comment_id: Number(commentId)
});
} catch (e) {
throw new Error(formatError(e));
}
}
canEditPullRequest(pullRequest: IPullRequestModel): boolean {
const username = pullRequest.author && pullRequest.author.login;
return this._credentialStore.isCurrentUser(username, pullRequest.remote);
}
private addCommentPermissions<T extends Pick<Comment, 'canEdit' | 'canDelete' | 'position' | 'user'>>(
rawComment: T,
remote: Remote
): T {
const isCurrentUser = this._credentialStore.isCurrentUser(rawComment.user.login, remote);
const notOutdated = rawComment.position !== null;
rawComment.canEdit = isCurrentUser && notOutdated;
rawComment.canDelete = isCurrentUser && notOutdated;
return rawComment;
}
private async changePullRequestState(state: 'open' | 'closed', pullRequest: IPullRequestModel): Promise<Github.PullRequestsUpdateResponse> {
const { octokit, remote } = await (pullRequest as PullRequestModel).githubRepository.ensure();
let ret = await octokit.pullRequests.update({
owner: remote.owner,
repo: remote.repositoryName,
number: pullRequest.prNumber,
state: state
});
return ret.data;
}
async editPullRequest(pullRequest: IPullRequestModel, toEdit: IPullRequestEditData): Promise<Github.PullRequestsUpdateResponse> {
try {
const { octokit, remote } = await (pullRequest as PullRequestModel).githubRepository.ensure();
const { data } = await octokit.pullRequests.update({
owner: remote.owner,
repo: remote.repositoryName,
number: pullRequest.prNumber,
body: toEdit.body,
title: toEdit.title
});
return data;
} catch (e) {
throw new Error(formatError(e));
}
}
async closePullRequest(pullRequest: IPullRequestModel): Promise<any> {
return this.changePullRequestState('closed', pullRequest)
.then(x => {
this._telemetry.on('pr.close');
return x;
});
}
async mergePullRequest(pullRequest: IPullRequestModel): Promise<any> {
const { octokit, remote } = await (pullRequest as PullRequestModel).githubRepository.ensure();
return await octokit.pullRequests.merge({
commit_message: '',
commit_title: '',
merge_method: 'merge',
owner: remote.owner,
repo: remote.repositoryName,
number: pullRequest.prNumber,
})
.then(x => {
this._telemetry.on('pr.merge');
return x.data;
});
}
private async createReview(pullRequest: IPullRequestModel, event: ReviewEvent, message?: string): Promise<Github.PullRequestsCreateReviewResponse> {
const { octokit, remote } = await (pullRequest as PullRequestModel).githubRepository.ensure();
let ret = await octokit.pullRequests.createReview({
owner: remote.owner,
repo: remote.repositoryName,
number: pullRequest.prNumber,
event: event,
body: message,
});
return ret.data;
}
async requestChanges(pullRequest: IPullRequestModel, message?: string): Promise<any> {
return this.createReview(pullRequest, ReviewEvent.RequestChanges, message)
.then(x => {
this._telemetry.on('pr.requestChanges');
return x;
});
}
async approvePullRequest(pullRequest: IPullRequestModel, message?: string): Promise<any> {
return this.createReview(pullRequest, ReviewEvent.Approve, message)
.then(x => {
this._telemetry.on('pr.approve');
return x;
});
}
async getPullRequestFileChangesInfo(pullRequest: IPullRequestModel): Promise<IRawFileChange[]> {
Logger.debug(`Fetch file changes, base, head and merge base of PR #${pullRequest.prNumber} - enter`, PullRequestManager.ID);
const { octokit, remote } = await (pullRequest as PullRequestModel).githubRepository.ensure();
if (!pullRequest.base) {
const info = await octokit.pullRequests.get({
owner: remote.owner,
repo: remote.repositoryName,
number: pullRequest.prNumber
});
pullRequest.update(info.data);
}
const { data } = await octokit.repos.compareCommits({
repo: remote.repositoryName,
owner: remote.owner,
base: `${pullRequest.base.repositoryCloneUrl.owner}:${pullRequest.base.ref}`,
head: `${pullRequest.head.repositoryCloneUrl.owner}:${pullRequest.head.ref}`
});
pullRequest.mergeBase = data.merge_base_commit.sha;
Logger.debug(`Fetch file changes and merge base of PR #${pullRequest.prNumber} - done`, PullRequestManager.ID);
return data.files;
}
async getPullRequestRepositoryDefaultBranch(pullRequest: IPullRequestModel): Promise<string> {
const branch = await (pullRequest as PullRequestModel).githubRepository.getDefaultBranch();
return branch;
}
async fullfillPullRequestMissingInfo(pullRequest: IPullRequestModel): Promise<void> {
try {
Logger.debug(`Fullfill pull request missing info - start`, PullRequestManager.ID);
const { octokit, remote } = await (pullRequest as PullRequestModel).githubRepository.ensure();
if (!pullRequest.base) {
const { data } = await octokit.pullRequests.get({
owner: remote.owner,
repo: remote.repositoryName,
number: pullRequest.prNumber
});
pullRequest.update(data);
}
if (!pullRequest.mergeBase) {
const { data } = await octokit.repos.compareCommits({
repo: remote.repositoryName,
owner: remote.owner,
base: `${pullRequest.base.repositoryCloneUrl.owner}:${pullRequest.base.ref}`,
head: `${pullRequest.head.repositoryCloneUrl.owner}:${pullRequest.head.ref}`
});
pullRequest.mergeBase = data.merge_base_commit.sha;
}
} catch (e) {
vscode.window.showErrorMessage(`Fetching Pull Request merge base failed: ${formatError(e)}`);
}
Logger.debug(`Fullfill pull request missing info - done`, PullRequestManager.ID);
}
//#region Git related APIs
async resolvePullRequest(owner: string, repositoryName: string, pullReuqestNumber: number): Promise<IPullRequestModel> {
const githubRepo = this._githubRepositories.find(repo =>
repo.remote.owner.toLowerCase() === owner.toLowerCase() && repo.remote.repositoryName.toLowerCase() === repositoryName.toLowerCase()
);
if (!githubRepo) {
return null;
}
const pr = await githubRepo.getPullRequest(pullReuqestNumber);
return pr;
}
async getMatchingPullRequestMetadataForBranch() {
if (!this.repository || !this.repository.state.HEAD) {
return null;
}
const HEAD = this.repository.state.HEAD;
let matchingPullRequestMetadata = await PullRequestGitHelper.getMatchingPullRequestMetadataForBranch(this.repository, HEAD.name);
return matchingPullRequestMetadata;
}
async getBranchForPullRequestFromExistingRemotes(pullRequest: IPullRequestModel) {
return await PullRequestGitHelper.getBranchForPullRequestFromExistingRemotes(this.repository, this._githubRepositories, pullRequest);
}
async fetchAndCheckout(remote: Remote, branchName: string, pullRequest: IPullRequestModel): Promise<void> {
await PullRequestGitHelper.fetchAndCheckout(this.repository, remote, branchName, pullRequest);
}
async createAndCheckout(pullRequest: IPullRequestModel): Promise<void> {
await PullRequestGitHelper.createAndCheckout(this.repository, pullRequest);
}
async getBranch(remote: Remote, branchName: string): Promise<Branch> {
let githubRepository = this.findRepo(byRemoteName(remote.remoteName));
if (githubRepository) {
let githubBranch = await githubRepository.getBranch(branchName);
if (githubBranch) {
return {
name: githubBranch.name,
type: RefType.RemoteHead
};
}
}
return null;
}
async checkout(branchName: string): Promise<void> {
return this.repository.checkout(branchName);
}
private handleError(e: any) {
if (e.code && e.code === 422) {
let errorObject: RestErrorResult;
try {
errorObject = e.message && JSON.parse(e.message);
} catch {
// If we failed to parse the JSON re-throw the original error
// since it will have a more useful stack
throw e;
}
const firstError = errorObject && errorObject.errors && errorObject.errors[0];
if (firstError && firstError.code === 'missing_field' && firstError.field === 'body') {
throw new Error('Body can\'t be blank');
} else {
throw new Error('There is already a pending review for this pull request on GitHub. Please finish or dismiss this review to be able to leave more comments');
}
} else {
throw e;
}
}
private async addReviewTimelineEventComments(pullRequest: IPullRequestModel, events: TimelineEvent[]): Promise<void> {
const reviewEvents = events.filter(isReviewEvent);
const reviewComments = await this.getPullRequestComments(pullRequest);
// Group comments by file and position
const commentsByFile = groupBy(reviewComments, comment => comment.path);
for (let file in commentsByFile) {
const fileComments = commentsByFile[file];
const commentThreads = groupBy(fileComments, comment => String(comment.position === null ? comment.original_position : comment.position));
// Loop through threads, for each thread, see if there is a matching review, push all comments to it
for (let i in commentThreads) {
const comments = commentThreads[i];
const reviewId = comments[0].pull_request_review_id;
if (reviewId) {
const matchingEvent = reviewEvents.find(review => review.id === reviewId);
if (matchingEvent) {
if (matchingEvent.comments) {
matchingEvent.comments = matchingEvent.comments.concat(comments);
} else {
matchingEvent.comments = comments;
}
}
}
}
}
}
private async fixCommitAttribution(pullRequest: IPullRequestModel, events: TimelineEvent[]): Promise<void> {
const commits = await this.getPullRequestCommits(pullRequest);
const commitEvents = events.filter(isCommitEvent);
for (let commitEvent of commitEvents) {
const matchingCommits = commits.filter(commit => commit.sha === commitEvent.sha);
if (matchingCommits.length === 1) {
const author = matchingCommits[0].author;
// There is not necessarily a GitHub account associated with the commit.
if (author !== null) {
commitEvent.author.avatar_url = author.avatar_url;
commitEvent.author.login = author.login;
commitEvent.author.html_url = author.html_url;
}
}
}
}
private async parseTimelineEvents(pullRequest: IPullRequestModel, remote: Remote, events: any[]): Promise<TimelineEvent[]> {
events.forEach(event => {
let type = getEventType(event.event);
event.event = type;
return event;
});
events.forEach(event => {
if (event.event === EventType.Commented) {
this.addCommentPermissions(event, remote);
}
});
return Promise.all([
this.addReviewTimelineEventComments(pullRequest, events),
this.fixCommitAttribution(pullRequest, events)
]).then(_ => {
return events;
});
}
}
export function getEventType(text: string) {
switch (text) {
case 'committed':
return EventType.Committed;
case 'mentioned':