-
Notifications
You must be signed in to change notification settings - Fork 608
/
Copy pathfolderRepositoryManager.ts
2071 lines (1786 loc) · 66.2 KB
/
folderRepositoryManager.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as path from 'path';
import * as vscode from 'vscode';
import type { Branch, Repository, UpstreamRef } from '../api/api';
import { GitApiImpl, GitErrorCodes, RefType } from '../api/api1';
import { GitHubManager } from '../authentication/githubServer';
import Logger from '../common/logger';
import { Protocol, ProtocolType } from '../common/protocol';
import { parseRepositoryRemotes, Remote } from '../common/remote';
import { ISessionState } from '../common/sessionState';
import { ITelemetry } from '../common/telemetry';
import { EventType, TimelineEvent } from '../common/timelineEvent';
import { fromPRUri, Schemes } from '../common/uri';
import { compareIgnoreCase, formatError, Predicate } from '../common/utils';
import { EXTENSION_ID } from '../constants';
import { REPO_KEYS, ReposState } from '../extensionState';
import { UserCompletion, userMarkdown } from '../issues/util';
import { OctokitCommon } from './common';
import { AuthProvider, CredentialStore } from './credentials';
import { GitHubRepository, ItemsData, PullRequestData, ViewerPermission } from './githubRepository';
import { PullRequestState, UserResponse } from './graphql';
import { IAccount, ILabel, IPullRequestsPagingOptions, PRType, RepoAccessAndMergeMethods, User } from './interface';
import { IssueModel } from './issueModel';
import { MilestoneModel } from './milestoneModel';
import { PullRequestGitHelper, PullRequestMetadata } from './pullRequestGitHelper';
import { PullRequestModel } from './pullRequestModel';
import {
convertRESTIssueToRawPullRequest,
convertRESTPullRequestToRawPullRequest,
convertRESTUserToAccount,
getRelatedUsersFromTimelineEvents,
loginComparator,
parseGraphQLUser,
} from './utils';
interface PageInformation {
pullRequestPage: number;
hasMorePages: boolean | null;
}
export interface ItemsResponseResult<T> {
items: T[];
hasMorePages: boolean;
hasUnsearchedRepositories: boolean;
}
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}.`;
}
}
export const SETTINGS_NAMESPACE = 'githubPullRequests';
export const REMOTES_SETTING = 'remotes';
export const ReposManagerStateContext: string = 'ReposManagerStateContext';
export enum ReposManagerState {
Initializing = 'Initializing',
NeedsAuthentication = 'NeedsAuthentication',
RepositoriesLoaded = 'RepositoriesLoaded',
}
export interface PullRequestDefaults {
owner: string;
repo: string;
base: string;
}
export const NO_MILESTONE: string = 'No Milestone';
enum PagedDataType {
PullRequest,
Milestones,
IssuesWithoutMilestone,
IssueSearch,
}
export class FolderRepositoryManager implements vscode.Disposable {
static ID = 'FolderRepositoryManager';
private _subs: vscode.Disposable[];
private _activePullRequest?: PullRequestModel;
private _activeIssue?: IssueModel;
private _githubRepositories: GitHubRepository[];
private _allGitHubRemotes: Remote[] = [];
private _mentionableUsers?: { [key: string]: IAccount[] };
private _fetchMentionableUsersPromise?: Promise<{ [key: string]: IAccount[] }>;
private _assignableUsers?: { [key: string]: IAccount[] };
private _fetchAssignableUsersPromise?: Promise<{ [key: string]: IAccount[] }>;
private _gitBlameCache: { [key: string]: string } = {};
private _githubManager: GitHubManager;
private _repositoryPageInformation: Map<string, PageInformation> = new Map<string, PageInformation>();
private _onDidMergePullRequest = new vscode.EventEmitter<void>();
readonly onDidMergePullRequest = this._onDidMergePullRequest.event;
private _onDidChangeActivePullRequest = new vscode.EventEmitter<void>();
readonly onDidChangeActivePullRequest: vscode.Event<void> = this._onDidChangeActivePullRequest.event;
private _onDidChangeActiveIssue = new vscode.EventEmitter<void>();
readonly onDidChangeActiveIssue: vscode.Event<void> = this._onDidChangeActiveIssue.event;
private _onDidLoadRepositories = new vscode.EventEmitter<ReposManagerState>();
readonly onDidLoadRepositories: vscode.Event<ReposManagerState> = this._onDidLoadRepositories.event;
private _onDidChangeRepositories = new vscode.EventEmitter<void>();
readonly onDidChangeRepositories: vscode.Event<void> = this._onDidChangeRepositories.event;
private _onDidChangeAssignableUsers = new vscode.EventEmitter<IAccount[]>();
readonly onDidChangeAssignableUsers: vscode.Event<IAccount[]> = this._onDidChangeAssignableUsers.event;
constructor(
public context: vscode.ExtensionContext,
private _repository: Repository,
public readonly telemetry: ITelemetry,
private _git: GitApiImpl,
private _credentialStore: CredentialStore,
private readonly _sessionState: ISessionState
) {
this._subs = [];
this._githubRepositories = [];
this._githubManager = new GitHubManager();
this._subs.push(
vscode.workspace.onDidChangeConfiguration(async e => {
if (e.affectsConfiguration(`${SETTINGS_NAMESPACE}.${REMOTES_SETTING}`)) {
await this.updateRepositories();
}
}),
);
this._subs.push(_credentialStore.onDidInitialize(() => this.updateRepositories()));
this.setUpCompletionItemProvider();
this.cleanStoredRepoState();
}
private cleanStoredRepoState() {
const deleteDate: number = new Date().valueOf() - 30 /*days*/ * 86400000 /*milliseconds in a day*/;
const reposState = this.context.globalState.get<ReposState>(REPO_KEYS);
if (reposState?.repos) {
let keysChanged = false;
Object.keys(reposState.repos).forEach(repo => {
const repoState = reposState.repos[repo];
if ((repoState.stateModifiedTime ?? 0) < deleteDate) {
keysChanged = true;
delete reposState.repos[repo];
}
});
if (keysChanged) {
this.context.globalState.update(REPO_KEYS, reposState);
}
}
}
get gitHubRepositories(): GitHubRepository[] {
return this._githubRepositories;
}
private computeAllGitHubRemotes(): Promise<Remote[]> {
const remotes = parseRepositoryRemotes(this.repository);
const potentialRemotes = remotes.filter(remote => remote.host);
return 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: ${e}`);
vscode.window.showErrorMessage(`Resolving GitHub remotes failed: ${formatError(e)}`);
return [];
});
}
public async getActiveGitHubRemotes(allGitHubRemotes: Remote[]): Promise<Remote[]> {
const remotesSetting = vscode.workspace.getConfiguration(SETTINGS_NAMESPACE).get<string[]>(REMOTES_SETTING);
if (!remotesSetting) {
Logger.appendLine(`Unable to read remotes setting`);
return Promise.resolve([]);
}
const missingRemotes = remotesSetting.filter(remote => {
return !allGitHubRemotes.some(repo => repo.remoteName === remote);
});
if (missingRemotes.length === remotesSetting.length) {
Logger.appendLine(`No remotes found. The following remotes are missing: ${missingRemotes.join(', ')}`);
} else {
Logger.debug(`Not all remotes found. The following remotes are missing: ${missingRemotes.join(', ')}`, FolderRepositoryManager.ID);
}
Logger.debug(`Displaying configured remotes: ${remotesSetting.join(', ')}`, FolderRepositoryManager.ID);
return remotesSetting
.map(remote => allGitHubRemotes.find(repo => repo.remoteName === remote))
.filter((repo: Remote | undefined): repo is Remote => !!repo);
}
public setUpCompletionItemProvider() {
let lastPullRequest: PullRequestModel | undefined = undefined;
let lastPullRequestTimelineEvents: TimelineEvent[] = [];
let cachedUsers: UserCompletion[] = [];
vscode.languages.registerCompletionItemProvider(
{ scheme: 'comment' },
{
provideCompletionItems: async (document, position, _token) => {
try {
const query = JSON.parse(document.uri.query);
if (compareIgnoreCase(query.extensionId, EXTENSION_ID) !== 0) {
return;
}
const wordRange = document.getWordRangeAtPosition(
position,
/@([a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38})?/i,
);
if (!wordRange || wordRange.isEmpty) {
return;
}
let prRelatedusers: { login: string; name?: string }[] = [];
const fileRelatedUsersNames: { [key: string]: boolean } = {};
let mentionableUsers: { [key: string]: { login: string; name?: string }[] } = {};
let prNumber: number | undefined;
let remoteName: string | undefined;
const activeTextEditors = vscode.window.visibleTextEditors;
if (activeTextEditors.length) {
const visiblePREditor = activeTextEditors.find(
editor => editor.document.uri.scheme === Schemes.Pr,
);
if (visiblePREditor) {
const params = fromPRUri(visiblePREditor.document.uri);
prNumber = params!.prNumber;
remoteName = params!.remoteName;
} else if (this._activePullRequest) {
prNumber = this._activePullRequest.number;
remoteName = this._activePullRequest.remote.remoteName;
}
if (lastPullRequest && prNumber && prNumber === lastPullRequest.number) {
return cachedUsers;
}
}
const prRelatedUsersPromise = new Promise<void>(async resolve => {
if (prNumber && remoteName) {
Logger.debug('get Timeline Events and parse users', FolderRepositoryManager.ID);
if (lastPullRequest && lastPullRequest.number === prNumber) {
return lastPullRequestTimelineEvents;
}
const githubRepo = this._githubRepositories.find(
repo => repo.remote.remoteName === remoteName,
);
if (githubRepo) {
lastPullRequest = await githubRepo.getPullRequest(prNumber);
lastPullRequestTimelineEvents = await lastPullRequest!.getTimelineEvents();
}
prRelatedusers = getRelatedUsersFromTimelineEvents(lastPullRequestTimelineEvents);
resolve();
}
resolve();
});
const fileRelatedUsersNamesPromise = new Promise<void>(async resolve => {
if (activeTextEditors.length) {
try {
Logger.debug('git blame and parse users', FolderRepositoryManager.ID);
const fsPath = path.resolve(activeTextEditors[0].document.uri.fsPath);
let blames: string | undefined;
if (this._gitBlameCache[fsPath]) {
blames = this._gitBlameCache[fsPath];
} else {
blames = await this.repository.blame(fsPath);
this._gitBlameCache[fsPath] = blames;
}
const blameLines = blames.split('\n');
for (const line of blameLines) {
const matches = /^\w{11} \S*\s*\((.*)\s*\d{4}\-/.exec(line);
if (matches && matches.length === 2) {
const name = matches[1].trim();
fileRelatedUsersNames[name] = true;
}
}
} catch (err) {
Logger.debug(err, FolderRepositoryManager.ID);
}
}
resolve();
});
const getMentionableUsersPromise = new Promise<void>(async resolve => {
Logger.debug('get mentionable users', FolderRepositoryManager.ID);
mentionableUsers = await this.getMentionableUsers();
resolve();
});
await Promise.all([
prRelatedUsersPromise,
fileRelatedUsersNamesPromise,
getMentionableUsersPromise,
]);
cachedUsers = [];
const prRelatedUsersMap: { [key: string]: { login: string; name?: string } } = {};
Logger.debug('prepare user suggestions', FolderRepositoryManager.ID);
prRelatedusers.forEach(user => {
if (!prRelatedUsersMap[user.login]) {
prRelatedUsersMap[user.login] = user;
}
});
const secondMap: { [key: string]: boolean } = {};
for (const mentionableUserGroup in mentionableUsers) {
for (const user of mentionableUsers[mentionableUserGroup]) {
if (!prRelatedUsersMap[user.login] && !secondMap[user.login]) {
secondMap[user.login] = true;
let priority = 2;
if (
fileRelatedUsersNames[user.login] ||
(user.name && fileRelatedUsersNames[user.name])
) {
priority = 1;
}
if (prRelatedUsersMap[user.login]) {
priority = 0;
}
cachedUsers.push({
label: user.login,
insertText: user.login,
filterText:
`${user.login}` +
(user.name && user.name !== user.login
? `_${user.name.toLowerCase().replace(' ', '_')}`
: ''),
sortText: `${priority}_${user.login}`,
detail: user.name,
kind: vscode.CompletionItemKind.User,
login: user.login,
uri: this.repository.rootUri,
});
}
}
}
for (const user in prRelatedUsersMap) {
if (!secondMap[user]) {
// if the mentionable api call fails partially, we should still populate related users from timeline events into the completion list
cachedUsers.push({
label: prRelatedUsersMap[user].login,
insertText: `${prRelatedUsersMap[user].login}`,
filterText:
`${prRelatedUsersMap[user].login}` +
(prRelatedUsersMap[user].name &&
prRelatedUsersMap[user].name !== prRelatedUsersMap[user].login
? `_${prRelatedUsersMap[user].name!.toLowerCase().replace(' ', '_')}`
: ''),
sortText: `0_${prRelatedUsersMap[user].login}`,
detail: prRelatedUsersMap[user].name,
kind: vscode.CompletionItemKind.User,
login: prRelatedUsersMap[user].login,
uri: this.repository.rootUri,
});
}
}
Logger.debug('done', FolderRepositoryManager.ID);
return cachedUsers;
} catch (e) {
return [];
}
},
resolveCompletionItem: async (item: vscode.CompletionItem, _token: vscode.CancellationToken) => {
try {
const repo = await this.getPullRequestDefaults();
const user: User | undefined = await this.resolveUser(repo.owner, repo.repo, (typeof item.label === 'string') ? item.label : item.label.label);
if (user) {
item.documentation = userMarkdown(repo, user);
}
} catch (e) {
// The user might not be resolvable in the repo, since users from outside the repo are included in the list.
}
return item;
},
},
'@',
);
}
get activeIssue(): IssueModel | undefined {
return this._activeIssue;
}
set activeIssue(issue: IssueModel | undefined) {
this._activeIssue = issue;
this._onDidChangeActiveIssue.fire();
}
get activePullRequest(): PullRequestModel | undefined {
return this._activePullRequest;
}
set activePullRequest(pullRequest: PullRequestModel | undefined) {
if (this._activePullRequest) {
this._activePullRequest.isActive = false;
}
if (pullRequest) {
pullRequest.isActive = true;
}
this._activePullRequest = pullRequest;
this._onDidChangeActivePullRequest.fire();
}
get repository(): Repository {
return this._repository;
}
set repository(repository: Repository) {
this._repository = repository;
}
get credentialStore(): CredentialStore {
return this._credentialStore;
}
public async loginAndUpdate() {
if (!this._credentialStore.isAnyAuthenticated()) {
const waitForRepos = new Promise<void>(c => {
const onReposChange = this.onDidChangeRepositories(() => {
onReposChange.dispose();
c();
});
});
await this._credentialStore.login(AuthProvider.github);
await waitForRepos;
}
}
private async getActiveRemotes(): Promise<Remote[]> {
this._allGitHubRemotes = await this.computeAllGitHubRemotes();
const activeRemotes = await this.getActiveGitHubRemotes(this._allGitHubRemotes);
if (activeRemotes.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 activeRemotes;
}
private _updatingRepositories: Promise<void> | undefined;
async updateRepositories(silent: boolean = false): Promise<void> {
if (this._updatingRepositories) {
await this._updatingRepositories;
}
this._updatingRepositories = this.doUpdateRepositories(silent);
return this._updatingRepositories;
}
private async doUpdateRepositories(silent: boolean): Promise<void> {
if (this._git.state === 'uninitialized') {
Logger.appendLine('Cannot updates repositories as git is uninitialized');
return;
}
const activeRemotes = await this.getActiveRemotes();
const isAuthenticated = this._credentialStore.isAuthenticated(AuthProvider.github) || this._credentialStore.isAuthenticated(AuthProvider['github-enterprise']);
vscode.commands.executeCommand('setContext', 'github:authenticated', isAuthenticated);
const repositories: GitHubRepository[] = [];
const resolveRemotePromises: Promise<boolean>[] = [];
const oldRepositories: GitHubRepository[] = [];
this._githubRepositories.forEach(repo => oldRepositories.push(repo));
const authenticatedRemotes = activeRemotes.filter(remote => this._credentialStore.isAuthenticated(remote.authProviderId));
authenticatedRemotes.forEach(remote => {
const repository = this.createGitHubRepository(remote, this._credentialStore);
resolveRemotePromises.push(repository.resolveRemote());
repositories.push(repository);
});
return Promise.all(resolveRemotePromises).then(async (remoteResults: boolean[]) => {
if (remoteResults.some(value => !value)) {
return this._credentialStore.showSamlMessageAndAuth();
}
this._githubRepositories = repositories;
oldRepositories.filter(old => this._githubRepositories.indexOf(old) < 0).forEach(repo => repo.dispose());
const repositoriesChanged =
oldRepositories.length !== this._githubRepositories.length ||
!oldRepositories.every(oldRepo =>
this._githubRepositories.some(newRepo => newRepo.remote.equals(oldRepo.remote)),
);
if (this._githubRepositories.length && repositoriesChanged) {
if (await this.checkIfMissingUpstream()) {
this.updateRepositories(silent);
return;
}
}
if (this.activePullRequest) {
this.getMentionableUsers(repositoriesChanged, true);
}
this.getAssignableUsers(repositoriesChanged);
if (isAuthenticated && activeRemotes.length) {
this._onDidLoadRepositories.fire(ReposManagerState.RepositoriesLoaded);
} else if (!isAuthenticated) {
this._onDidLoadRepositories.fire(ReposManagerState.NeedsAuthentication);
}
if (!silent) {
this._onDidChangeRepositories.fire();
}
return;
});
}
private async checkIfMissingUpstream(): Promise<boolean> {
try {
const origin = await this.getOrigin();
const metadata = await origin.getMetadata();
if (metadata.fork && metadata.parent) {
const parentUrl = new Protocol(metadata.parent.git_url);
const missingParentRemote = !this._githubRepositories.some(
repo =>
repo.remote.owner === parentUrl.owner &&
repo.remote.repositoryName === parentUrl.repositoryName,
);
if (missingParentRemote) {
const upstreamAvailable = !this.repository.state.remotes.some(remote => remote.name === 'upstream');
const remoteName = upstreamAvailable ? 'upstream' : metadata.parent.owner?.login;
if (remoteName) {
// check the remotes to see what protocol is being used
const isSSH = this.gitHubRepositories[0].remote.gitProtocol.type === ProtocolType.SSH;
if (isSSH) {
await this.repository.addRemote(remoteName, metadata.parent.git_url);
} else {
await this.repository.addRemote(remoteName, metadata.parent.clone_url);
}
return true;
}
}
}
} catch (e) {
Logger.appendLine(`Missing upstream check failed: ${e}`);
// ignore
}
return false;
}
getAllAssignableUsers(): IAccount[] | undefined {
if (this._assignableUsers) {
const allAssignableUsers: IAccount[] = [];
Object.keys(this._assignableUsers).forEach(k => {
allAssignableUsers.push(...this._assignableUsers![k]);
});
return allAssignableUsers;
}
return undefined;
}
private getMentionableUsersFromGlobalState(): { [key: string]: IAccount[] } | undefined {
Logger.appendLine('Trying to use globalState for mentionable users.');
const reposState = this.context.globalState.get<ReposState>(REPO_KEYS);
if (reposState) {
const cache: { [key: string]: IAccount[] } = {};
const hasAllRepos = this._githubRepositories.every(repo => {
const key = `${repo.remote.owner}/${repo.remote.repositoryName}`;
if (!reposState.repos[key]) {
return false;
}
cache[repo.remote.repositoryName] = reposState.repos[key].mentionableUsers ?? [];
return true;
});
if (hasAllRepos) {
Logger.appendLine(`Using globalState mentionable users for ${Object.keys(cache).length}.`);
return cache;
}
}
Logger.appendLine(`No globalState for mentionable users.`);
return undefined;
}
private createFetchMentionableUsersPromise(): Promise<{ [key: string]: IAccount[] }> {
const cache: { [key: string]: IAccount[] } = {};
return new Promise<{ [key: string]: IAccount[] }>(resolve => {
const promises = this._githubRepositories.map(async githubRepository => {
const data = await githubRepository.getMentionableUsers();
cache[githubRepository.remote.remoteName] = data;
return;
});
Promise.all(promises).then(() => {
this._mentionableUsers = cache;
this._fetchMentionableUsersPromise = undefined;
const globalReposState = this.context.globalState.get<ReposState>(REPO_KEYS, { repos: {} });
this._githubRepositories.forEach(repo => {
const key = `${repo.remote.owner}/${repo.remote.repositoryName}`;
if (!globalReposState.repos[key]) {
globalReposState.repos[key] = {};
}
globalReposState.repos[key].mentionableUsers = cache[repo.remote.remoteName];
globalReposState.repos[key].stateModifiedTime = new Date().valueOf();
});
this.context.globalState.update(REPO_KEYS, globalReposState);
resolve(cache);
});
});
}
async getMentionableUsers(clearCache?: boolean, useGlobalState?: boolean): Promise<{ [key: string]: IAccount[] }> {
if (clearCache) {
delete this._mentionableUsers;
}
if (this._mentionableUsers) {
return this._mentionableUsers;
}
let globalStateMentionableUsers = this.getMentionableUsersFromGlobalState();
if (useGlobalState && !this._fetchMentionableUsersPromise && globalStateMentionableUsers) {
return globalStateMentionableUsers;
}
if (!this._fetchMentionableUsersPromise) {
this._fetchMentionableUsersPromise = this.createFetchMentionableUsersPromise();
return globalStateMentionableUsers ?? this._fetchMentionableUsersPromise;
}
return this._fetchMentionableUsersPromise;
}
async getAssignableUsers(clearCache?: boolean): Promise<{ [key: string]: IAccount[] }> {
if (clearCache) {
delete this._assignableUsers;
}
if (this._assignableUsers) {
return this._assignableUsers;
}
if (!this._fetchAssignableUsersPromise) {
const cache: { [key: string]: IAccount[] } = {};
const allAssignableUsers: IAccount[] = [];
return (this._fetchAssignableUsersPromise = new Promise(resolve => {
const promises = this._githubRepositories.map(async githubRepository => {
const data = await githubRepository.getAssignableUsers();
cache[githubRepository.remote.remoteName] = data.sort(loginComparator);
allAssignableUsers.push(...data);
return;
});
Promise.all(promises).then(() => {
this._assignableUsers = cache;
this._fetchAssignableUsersPromise = undefined;
resolve(cache);
this._onDidChangeAssignableUsers.fire(allAssignableUsers);
});
}));
}
return this._fetchAssignableUsersPromise;
}
/**
* Returns the remotes that are currently active, which is those that are important by convention (origin, upstream),
* or the remotes configured by the setting githubPullRequests.remotes
*/
getGitHubRemotes(): Remote[] {
const githubRepositories = this._githubRepositories;
if (!githubRepositories || !githubRepositories.length) {
return [];
}
return githubRepositories.map(repository => repository.remote);
}
/**
* Returns all remotes from the repository.
*/
async getAllGitHubRemotes(): Promise<Remote[]> {
return await this.computeAllGitHubRemotes();
}
async getLocalPullRequests(): Promise<PullRequestModel[]> {
const githubRepositories = this._githubRepositories;
if (!githubRepositories || !githubRepositories.length) {
return [];
}
const localBranches = this.repository.state.refs
.filter(r => r.type === RefType.Head && r.name !== undefined)
.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 | undefined = 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) as PullRequestModel[];
});
}
async getLabels(issue?: IssueModel, repoInfo?: { owner: string; repo: string }): Promise<ILabel[]> {
const repo = issue
? issue.githubRepository
: this._githubRepositories.find(
r => r.remote.owner === repoInfo?.owner && r.remote.repositoryName === repoInfo?.repo,
);
if (!repo) {
throw new Error(`No matching repository found for getting labels.`);
}
const { remote, octokit } = await repo.ensure();
let hasNextPage = false;
let page = 1;
let results: ILabel[] = [];
do {
const result = await octokit.issues.listLabelsForRepo({
owner: remote.owner,
repo: remote.repositoryName,
per_page: 100,
page,
});
results = results.concat(
result.data.map(label => {
return {
name: label.name,
color: label.color,
};
}),
);
results = results.sort((a, b) => a.name.localeCompare(b.name));
hasNextPage = !!result.headers.link && result.headers.link.indexOf('rel="next"') > -1;
page += 1;
} while (hasNextPage);
return results;
}
async deleteLocalPullRequest(pullRequest: PullRequestModel, force?: boolean): Promise<void> {
if (!pullRequest.localBranchName) {
return;
}
await this.repository.deleteBranch(pullRequest.localBranchName, force);
let remoteName: string | undefined = undefined;
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);
}
}
/* __GDPR__
"branch.delete" : {}
*/
this.telemetry.sendTelemetryEvent('branch.delete');
}
// Keep track of how many pages we've fetched for each query, so when we reload we pull the same ones.
private totalFetchedPages = new Map<string, number>();
/**
* This method works in three different ways:
* 1) Initialize: fetch the first page of the first remote that has pages
* 2) Fetch Next: fetch the next page from this remote, or if it has no more pages, the first page from the next remote that does have pages
* 3) Restore: fetch all the pages you previously have fetched
*
* When `options.fetchNextPage === false`, we are in case 2.
* Otherwise:
* If `this.totalFetchQueries[queryId] === 0`, we are in case 1.
* Otherwise, we're in case 3.
*/
private async fetchPagedData<T>(
options: IPullRequestsPagingOptions = { fetchNextPage: false },
queryId: string,
pagedDataType: PagedDataType = PagedDataType.PullRequest,
type: PRType = PRType.All,
query?: string,
): Promise<ItemsResponseResult<T>> {
if (!this._githubRepositories || !this._githubRepositories.length) {
return {
items: [],
hasMorePages: false,
hasUnsearchedRepositories: false,
};
}
const getTotalFetchedPages = () => this.totalFetchedPages.get(queryId) || 0;
const setTotalFetchedPages = (numPages: number) => this.totalFetchedPages.set(queryId, numPages);
for (const repository of this._githubRepositories) {
const remoteId = repository.remote.url.toString() + queryId;
if (!this._repositoryPageInformation.get(remoteId)) {
this._repositoryPageInformation.set(remoteId, {
pullRequestPage: 0,
hasMorePages: null,
});
}
}
let pagesFetched = 0;
const itemData: ItemsData = { hasMorePages: false, items: [] };
const addPage = (page: PullRequestData | undefined) => {
pagesFetched++;
if (page) {
itemData.items = itemData.items.concat(page.items);
itemData.hasMorePages = page.hasMorePages;
}
};
const githubRepositories = this._githubRepositories.filter(repo => {
const info = this._repositoryPageInformation.get(repo.remote.url.toString() + queryId);
// If we are in case 1 or 3, don't filter out repos that are out of pages, as we will be querying from the start.
return info && (options.fetchNextPage === false || info.hasMorePages !== false);
});
for (let i = 0; i < githubRepositories.length; i++) {
const githubRepository = githubRepositories[i];
const remoteId = githubRepository.remote.url.toString() + queryId;
const pageInformation = this._repositoryPageInformation.get(remoteId)!;
const fetchPage = async (
pageNumber: number,
): Promise<{ items: any[]; hasMorePages: boolean } | undefined> => {
switch (pagedDataType) {
case PagedDataType.PullRequest: {
if (type === PRType.All) {
return githubRepository.getAllPullRequests(pageNumber);
} else {
return githubRepository.getPullRequestsForCategory(query || '', pageNumber);
}
}
case PagedDataType.Milestones: {
return githubRepository.getIssuesForUserByMilestone(pageInformation.pullRequestPage);
}
case PagedDataType.IssuesWithoutMilestone: {
return githubRepository.getIssuesWithoutMilestone(pageInformation.pullRequestPage);
}
case PagedDataType.IssueSearch: {
return githubRepository.getIssues(pageInformation.pullRequestPage, query);
}
}
};
if (options.fetchNextPage) {
// Case 2. Fetch a single new page, and increment the global number of pages fetched for this query.
pageInformation.pullRequestPage++;
addPage(await fetchPage(pageInformation.pullRequestPage));
setTotalFetchedPages(getTotalFetchedPages() + 1);
} else {
// Case 1&3. Fetch all the pages we have fetched in the past, or in case 1, just a single page.
if (pageInformation.pullRequestPage === 0) {
// Case 1. Pretend we have previously fetched the first page, then hand off to the case 3 machinery to "fetch all pages we have fetched in the past"
pageInformation.pullRequestPage = 1;
}
const pages = await Promise.all(
Array.from({ length: pageInformation.pullRequestPage }).map((_, j) => fetchPage(j + 1)),
);
pages.forEach(page => addPage(page));
}
pageInformation.hasMorePages = itemData.hasMorePages;
// Break early if
// 1) we've received data AND
// 2) either we're fetching just the next page (case 2)
// OR we're fetching all (cases 1&3), and we've fetched as far as we had previously (or further, in case 1).
if (
itemData.items.length &&
(options.fetchNextPage === true ||
(options.fetchNextPage === false && pagesFetched >= getTotalFetchedPages()))
) {
if (getTotalFetchedPages() === 0) {
// We're in case 1, manually set number of pages we looked through until we found first results.
setTotalFetchedPages(pagesFetched);
}
return {
items: itemData.items,
hasMorePages: pageInformation.hasMorePages,
hasUnsearchedRepositories: i < githubRepositories.length - 1,
};
}
}
return {
items: [],
hasMorePages: false,
hasUnsearchedRepositories: false,
};
}
async getPullRequests(
type: PRType,
options: IPullRequestsPagingOptions = { fetchNextPage: false },