-
Notifications
You must be signed in to change notification settings - Fork 720
Expand file tree
/
Copy pathgithubRepository.ts
More file actions
1990 lines (1791 loc) · 64.7 KB
/
githubRepository.ts
File metadata and controls
1990 lines (1791 loc) · 64.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as buffer from 'buffer';
import { ApolloQueryResult, DocumentNode, FetchResult, MutationOptions, NetworkStatus, OperationVariables, QueryOptions } from 'apollo-boost';
import LRUCache from 'lru-cache';
import * as vscode from 'vscode';
import { mergeQuerySchemaWithShared, OctokitCommon } from './common';
import { CredentialStore, GitHub } from './credentials';
import {
AssignableUsersResponse,
CreatePullRequestResponse,
FileContentResponse,
ForkDetailsResponse,
GetBranchResponse,
GetChecksResponse,
isCheckRun,
IssueResponse,
IssuesSearchResponse,
ListBranchesResponse,
MaxIssueResponse,
MentionableUsersResponse,
MergeQueueForBranchResponse,
MilestoneIssuesResponse,
OrganizationTeamsCountResponse,
OrganizationTeamsResponse,
OrgProjectsResponse,
PullRequestNumberData,
PullRequestNumbersResponse,
PullRequestParticipantsResponse,
PullRequestResponse,
PullRequestsResponse,
PullRequestTemplatesResponse,
RepoProjectsResponse,
RevertPullRequestResponse,
SuggestedActorsResponse,
UserResponse,
ViewerPermissionResponse,
} from './graphql';
import {
CheckState,
IAccount,
IMilestone,
IProject,
Issue,
ITeam,
MergeMethod,
PullRequest,
PullRequestChecks,
PullRequestCheckStatus,
PullRequestReviewRequirement,
RepoAccessAndMergeMethods,
User,
} from './interface';
import { IssueChangeEvent, IssueModel } from './issueModel';
import { LoggingOctokit } from './loggingOctokit';
import { PullRequestModel } from './pullRequestModel';
import defaultSchema from './queries.gql';
import * as extraSchema from './queriesExtra.gql';
import * as limitedSchema from './queriesLimited.gql';
import * as sharedSchema from './queriesShared.gql';
import {
convertRESTPullRequestToRawPullRequest,
getAvatarWithEnterpriseFallback,
getOverrideBranch,
isInCodespaces,
parseAccount,
parseGraphQLIssue,
parseGraphQLPullRequest,
parseGraphQLUser,
parseGraphQLViewerPermission,
parseMergeMethod,
parseMilestone,
restPaginate,
} from './utils';
import { AuthenticationError, AuthProvider, GitHubServerType, isSamlError } from '../common/authentication';
import { Disposable, disposeAll } from '../common/lifecycle';
import Logger from '../common/logger';
import { GitHubRemote, parseRemote } from '../common/remote';
import { BRANCH_LIST_TIMEOUT, PR_SETTINGS_NAMESPACE } from '../common/settingKeys';
import { ITelemetry } from '../common/telemetry';
import { PullRequestCommentController } from '../view/pullRequestCommentController';
import { PRCommentControllerRegistry } from '../view/pullRequestCommentControllerRegistry';
export const PULL_REQUEST_PAGE_SIZE = 20;
const GRAPHQL_COMPONENT_ID = 'GraphQL';
export interface ItemsData<T> {
items: T[];
hasMorePages: boolean;
totalCount?: number;
}
export interface IssueData extends ItemsData<Issue> {
items: Issue[];
hasMorePages: boolean;
}
export interface PullRequestData extends ItemsData<PullRequestModel> {
items: PullRequestModel[];
}
export interface MilestoneData extends ItemsData<{ milestone: IMilestone; issues: IssueModel[] }> {
items: { milestone: IMilestone; issues: IssueModel[] }[];
hasMorePages: boolean;
}
export enum ViewerPermission {
Unknown = 'unknown',
Admin = 'ADMIN',
Maintain = 'MAINTAIN',
Read = 'READ',
Triage = 'TRIAGE',
Write = 'WRITE',
}
export enum TeamReviewerRefreshKind {
None,
Try,
Force
}
export interface ForkDetails {
isFork: boolean;
parent: {
owner: {
login: string;
};
name: string;
};
}
export type IMetadata = OctokitCommon.ReposGetResponseData;
export enum GraphQLErrorType {
Unprocessable = 'UNPROCESSABLE',
}
export interface GraphQLError {
extensions?: {
code: string;
};
type?: GraphQLErrorType;
message?: string;
}
export enum CopilotWorkingStatus {
NotCopilotIssue = 'NotCopilotIssue',
InProgress = 'InProgress',
Error = 'Error',
Done = 'Done',
}
export interface PullRequestChangeEvent {
model: IssueModel;
event: IssueChangeEvent;
}
export class GitHubRepository extends Disposable {
static ID = 'GitHubRepository';
protected _initialized: boolean = false;
protected _hub: GitHub | undefined;
protected _metadata: Promise<IMetadata> | undefined;
public commentsController?: vscode.CommentController;
public commentsHandler?: PRCommentControllerRegistry;
private _pullRequestModelsByNumber: LRUCache<number, { model: PullRequestModel, disposables: vscode.Disposable[] }> = new LRUCache({
maxAge: 1000 * 60 * 60 * 4 /* 4 hours */, stale: true, updateAgeOnGet: true,
dispose: (_key, value) => {
disposeAll(value.disposables);
value.model.dispose();
}
});
private _issueModelsByNumber: LRUCache<number, { model: IssueModel, disposables: vscode.Disposable[] }> = new LRUCache({
maxAge: 1000 * 60 * 60 * 4 /* 4 hours */, stale: true, updateAgeOnGet: true,
dispose: (_key, value) => {
disposeAll(value.disposables);
value.model.dispose();
}
});
// eslint-disable-next-line rulesdir/no-any-except-union-method-signature
private _queriesSchema: any;
private _areQueriesLimited: boolean = false;
get areQueriesLimited(): boolean { return this._areQueriesLimited; }
private _onDidAddPullRequest: vscode.EventEmitter<PullRequestModel> = this._register(new vscode.EventEmitter());
public readonly onDidAddPullRequest: vscode.Event<PullRequestModel> = this._onDidAddPullRequest.event;
private _onDidChangePullRequests: vscode.EventEmitter<PullRequestChangeEvent[]> = this._register(new vscode.EventEmitter());
public readonly onDidChangePullRequests: vscode.Event<PullRequestChangeEvent[]> = this._onDidChangePullRequests.event;
public get hub(): GitHub {
if (!this._hub) {
if (!this._initialized) {
throw new Error('Call ensure() before accessing this property.');
} else {
throw new AuthenticationError();
}
}
return this._hub;
}
public equals(repo: GitHubRepository): boolean {
return this.remote.equals(repo.remote);
}
getExistingPullRequestModel(prNumber: number): PullRequestModel | undefined {
return this._pullRequestModelsByNumber.get(prNumber)?.model;
}
getExistingIssueModel(issueNumber: number): IssueModel | undefined {
return this._issueModelsByNumber.get(issueNumber)?.model;
}
get pullRequestModels(): PullRequestModel[] {
return Array.from(this._pullRequestModelsByNumber.values().map(value => value.model));
}
get issueModels(): IssueModel[] {
return Array.from(this._issueModelsByNumber.values().map(value => value.model));
}
public async ensureCommentsController(): Promise<void> {
try {
await this.ensure();
if (this.commentsController) {
return;
}
this.commentsController = vscode.comments.createCommentController(
`${PullRequestCommentController.PREFIX}-${this.remote.gitProtocol.normalizeUri()?.authority}-${this.remote.remoteName}-${this.remote.owner}-${this.remote.repositoryName}`,
`Pull Request (${this.remote.owner}/${this.remote.repositoryName})`,
);
this.commentsHandler = new PRCommentControllerRegistry(this.commentsController, this.telemetry);
this._register(this.commentsHandler);
this._register(this.commentsController);
} catch (e) {
console.log(e);
}
}
override dispose() {
super.dispose();
this.commentsController = undefined;
this.commentsHandler = undefined;
}
public get octokit(): LoggingOctokit {
return this.hub && this.hub.octokit;
}
private get id(): string {
return `${GitHubRepository.ID}+${this._id}`;
}
constructor(
private readonly _id: number,
public remote: GitHubRemote,
public readonly rootUri: vscode.Uri,
private readonly _credentialStore: CredentialStore,
public readonly telemetry: ITelemetry,
silent: boolean = false
) {
super();
this._queriesSchema = mergeQuerySchemaWithShared(sharedSchema.default, defaultSchema);
// kick off the comments controller early so that the Comments view is visible and doesn't pop up later in an way that's jarring
if (!silent) {
this.ensureCommentsController();
}
}
get authMatchesServer(): boolean {
if ((this.remote.githubServerType === GitHubServerType.GitHubDotCom) && this._credentialStore.isAuthenticated(AuthProvider.github)) {
return true;
} else if ((this.remote.githubServerType === GitHubServerType.Enterprise) && this._credentialStore.isAuthenticated(AuthProvider.githubEnterprise)) {
return true;
} else {
// Not good. We have a mismatch between auth type and server type.
return false;
}
}
private async codespacesTokenError<T>(action: QueryOptions | MutationOptions<T>) {
if (isInCodespaces() && (await this._metadata)?.fork) {
// :( https://github.com/microsoft/vscode-pull-request-github/issues/5325#issuecomment-1798243852
/* __GDPR__
"pr.codespacesTokenError" : {
"action": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth" }
}
*/
this.telemetry.sendTelemetryErrorEvent('pr.codespacesTokenError', {
action: action.context
});
throw new Error(vscode.l10n.t('This action cannot be completed in a GitHub Codespace on a fork.'));
}
}
query = async <T>(query: QueryOptions, ignoreSamlErrors: boolean = false, legacyFallback?: { query: DocumentNode, variables?: OperationVariables }): Promise<ApolloQueryResult<T>> => {
const gql = this.authMatchesServer && this.hub && this.hub.graphql;
if (!gql) {
const logValue = (query.query.definitions[0] as { name: { value: string } | undefined }).name?.value;
Logger.debug(`Not available for query: ${logValue ?? 'unknown'}`, GRAPHQL_COMPONENT_ID);
const empty: ApolloQueryResult<T> = {
data: null as T,
loading: false,
networkStatus: NetworkStatus.error,
stale: false,
} satisfies ApolloQueryResult<T>;
return empty;
}
let rsp;
try {
rsp = await gql.query<T>(query);
} catch (e) {
const logInfo = (query.query.definitions[0] as { name: { value: string } | undefined }).name?.value;
const gqlErrors = e.graphQLErrors ? e.graphQLErrors as GraphQLError[] : undefined;
Logger.error(`Error querying GraphQL API (${logInfo}): ${e.message}${gqlErrors ? `. ${gqlErrors.map(error => error.extensions?.code).join(',')}` : ''}`, this.id);
if (legacyFallback) {
query.query = legacyFallback.query;
query.variables = legacyFallback.variables;
return this.query(query, ignoreSamlErrors);
}
if (gqlErrors && gqlErrors.length && (gqlErrors.some(error => error.extensions?.code === 'undefinedField')) && !this._areQueriesLimited) {
// We're running against a GitHub server that doesn't support the query we're trying to run.
// Switch to the limited schema and try again.
this._areQueriesLimited = true;
this._queriesSchema = mergeQuerySchemaWithShared(sharedSchema.default, limitedSchema.default);
query.query = this.schema[(query.query.definitions[0] as { name: { value: string } }).name.value];
rsp = await gql.query<T>(query);
} else if (ignoreSamlErrors && isSamlError(e)) {
// Some queries just result in SAML errors.
} else if ((e.message as string | undefined)?.includes('401 Unauthorized')) {
await this._credentialStore.recreate(vscode.l10n.t('Your authentication session has lost authorization. You need to sign in again to regain authorization.'));
rsp = await gql.query<T>(query);
} else {
if (e.graphQLErrors && e.graphQLErrors.length && e.graphQLErrors[0].message === 'Resource not accessible by integration') {
await this.codespacesTokenError(query);
}
throw e;
}
}
return rsp;
};
mutate = async <T>(mutation: MutationOptions<T>, legacyFallback?: { mutation: DocumentNode, deleteProps: string[] }): Promise<FetchResult<T>> => {
const gql = this.authMatchesServer && this.hub && this.hub.graphql;
if (!gql) {
Logger.debug(`Not available for query: ${mutation.context as string}`, GRAPHQL_COMPONENT_ID);
const empty: FetchResult<T> = {
data: null
};
return empty;
}
let rsp: FetchResult<T>;
try {
rsp = await gql.mutate<T>(mutation);
} catch (e) {
if (legacyFallback) {
mutation.mutation = legacyFallback.mutation;
if (mutation.variables?.input) {
for (const prop of legacyFallback.deleteProps) {
delete mutation.variables.input[prop];
}
}
return this.mutate(mutation);
} else if (e.graphQLErrors && e.graphQLErrors.length && e.graphQLErrors[0].message === 'Resource not accessible by integration') {
await this.codespacesTokenError(mutation);
}
throw e;
}
return rsp;
};
get schema() {
return this._queriesSchema;
}
private async getMetadataForRepo(owner: string, repo: string): Promise<IMetadata> {
if (this._metadata && this.remote.owner === owner && this.remote.repositoryName === repo) {
Logger.debug(`Using cached metadata for repo ${owner}/${repo}`, this.id);
return this._metadata;
}
Logger.debug(`Fetch metadata for repo - enter`, this.id);
const { octokit } = await this.ensure();
const result = await octokit.call(octokit.api.repos.get, {
owner,
repo
});
Logger.debug(`Fetch metadata for repo ${owner}/${repo} - done`, this.id);
const metadata = { ...result.data, currentUser: await this._hub?.currentUser };
return metadata;
}
async getMetadata(): Promise<IMetadata> {
if (this._metadata) {
const metadata = await this._metadata;
Logger.debug(`Using cached metadata ${metadata.owner?.login}/${metadata.name}`, this.id);
return metadata;
}
Logger.debug(`Fetch metadata - enter`, this.id);
const { remote } = await this.ensure();
this._metadata = this.getMetadataForRepo(remote.owner, remote.repositoryName);
Logger.debug(`Fetch metadata ${remote.owner}/${remote.repositoryName} - done`, this.id);
return this._metadata;
}
/**
* Resolves remotes with redirects.
* @returns
*/
async resolveRemote(): Promise<boolean> {
try {
const { clone_url } = await this.getMetadata();
this.remote = GitHubRemote.remoteAsGitHub(parseRemote(this.remote.remoteName, clone_url, this.remote.gitProtocol)!, this.remote.githubServerType);
} catch (e) {
Logger.warn(`Unable to resolve remote: ${e}`);
if (isSamlError(e)) {
return false;
}
}
return true;
}
async ensure(additionalScopes: boolean = false): Promise<GitHubRepository> {
this._initialized = true;
const oldHub = this._hub;
if (!this._credentialStore.isAuthenticated(this.remote.authProviderId)) {
// We need auth now. (ex., a PR is already checked out)
// We can no longer wait until later for login to be done
await this._credentialStore.create(undefined, additionalScopes);
if (!this._credentialStore.isAuthenticated(this.remote.authProviderId)) {
this._hub = await this._credentialStore.showSignInNotification(this.remote.authProviderId);
}
} else {
if (additionalScopes) {
this._hub = await this._credentialStore.getHubEnsureAdditionalScopes(this.remote.authProviderId);
} else {
this._hub = this._credentialStore.getHub(this.remote.authProviderId);
}
}
if (oldHub !== this._hub) {
if (this._areQueriesLimited || this._credentialStore.areScopesOld(this.remote.authProviderId) || (this.remote.authProviderId === AuthProvider.githubEnterprise)) {
this._areQueriesLimited = true;
this._queriesSchema = mergeQuerySchemaWithShared(sharedSchema.default, limitedSchema.default);
} else {
if (this._credentialStore.areScopesExtra(this.remote.authProviderId)) {
this._queriesSchema = mergeQuerySchemaWithShared(sharedSchema.default, extraSchema.default);
} else {
this._queriesSchema = mergeQuerySchemaWithShared(sharedSchema.default, defaultSchema);
}
}
}
return this;
}
async ensureAdditionalScopes(): Promise<GitHubRepository> {
return this.ensure(true);
}
async getDefaultBranch(): Promise<string> {
const overrideSetting = getOverrideBranch();
if (overrideSetting) {
return overrideSetting;
}
try {
const data = await this.getMetadata();
return data.default_branch;
} catch (e) {
Logger.warn(`Fetching default branch failed: ${e}`, this.id);
}
return 'master';
}
async getPullRequestTemplates(): Promise<string[] | undefined> {
try {
Logger.debug('Fetch pull request templates - enter', this.id);
const { query, remote, schema } = await this.ensure();
const result = await query<PullRequestTemplatesResponse>({
query: schema.PullRequestTemplates,
variables: {
owner: remote.owner,
name: remote.repositoryName,
}
});
Logger.debug('Fetch pull request templates - done', this.id);
return result.data.repository.pullRequestTemplates.map(template => template.body);
} catch (e) {
// The template was not found.
}
}
private _repoAccessAndMergeMethods: RepoAccessAndMergeMethods | undefined;
async getRepoAccessAndMergeMethods(refetch: boolean = false): Promise<RepoAccessAndMergeMethods> {
try {
if (!this._repoAccessAndMergeMethods || refetch) {
Logger.debug(`Fetch repo permissions and available merge methods - enter`, this.id);
const data = await this.getMetadata();
Logger.debug(`Fetch repo permissions and available merge methods - done`, this.id);
const hasWritePermission = data.permissions?.push ?? false;
this._repoAccessAndMergeMethods = {
// Users with push access to repo have rights to merge/close PRs,
// edit title/description, assign reviewers/labels etc.
hasWritePermission,
mergeMethodsAvailability: {
merge: data.allow_merge_commit ?? false,
squash: data.allow_squash_merge ?? false,
rebase: data.allow_rebase_merge ?? false,
},
viewerCanAutoMerge: (data.allow_auto_merge && hasWritePermission) ?? false
};
}
return this._repoAccessAndMergeMethods;
} catch (e) {
Logger.warn(`GitHubRepository> Fetching repo permissions and available merge methods failed: ${e}`);
}
return {
hasWritePermission: true,
mergeMethodsAvailability: {
merge: true,
squash: true,
rebase: true,
},
viewerCanAutoMerge: false
};
}
private _branchHasMergeQueue: Map<string, MergeMethod> = new Map();
async mergeQueueMethodForBranch(branch: string): Promise<MergeMethod | undefined> {
if (this._branchHasMergeQueue.has(branch)) {
return this._branchHasMergeQueue.get(branch)!;
}
try {
Logger.debug('Fetch branch has merge queue - enter', this.id);
const { query, remote, schema } = await this.ensure();
if (!schema.MergeQueueForBranch) {
return undefined;
}
const result = await query<MergeQueueForBranchResponse>({
query: schema.MergeQueueForBranch,
variables: {
owner: remote.owner,
name: remote.repositoryName,
branch
}
});
Logger.debug('Fetch branch has merge queue - done', this.id);
const mergeMethod = parseMergeMethod(result.data.repository.mergeQueue?.configuration?.mergeMethod);
if (mergeMethod) {
this._branchHasMergeQueue.set(branch, mergeMethod);
}
return mergeMethod;
} catch (e) {
Logger.error(`Fetching branch has merge queue failed: ${e}`, this.id);
}
}
async commit(branch: string, message: string, files: Map<string, Uint8Array>): Promise<boolean> {
Logger.debug(`Committing files to branch ${branch} - enter`, this.id);
let success = false;
try {
const { octokit, remote } = await this.ensure();
const lastCommitSha = (await octokit.call(octokit.api.repos.getBranch, { owner: remote.owner, repo: remote.repositoryName, branch })).data.commit.sha;
const lastTreeSha = (await octokit.call(octokit.api.repos.getCommit, { owner: remote.owner, repo: remote.repositoryName, ref: lastCommitSha })).data.commit.tree.sha;
const treeItems: { path: string, mode: '100644', content: string }[] = [];
for (const [path, content] of files) {
treeItems.push({ path: path.substring(1), mode: '100644', content: content.toString() });
}
const newTreeSha = (await octokit.call(octokit.api.git.createTree, { owner: remote.owner, repo: remote.repositoryName, base_tree: lastTreeSha, tree: treeItems })).data.sha;
const newCommitSha = (await octokit.call(octokit.api.git.createCommit, { owner: remote.owner, repo: remote.repositoryName, message, tree: newTreeSha, parents: [lastCommitSha] })).data.sha;
await octokit.call(octokit.api.git.updateRef, { owner: remote.owner, repo: remote.repositoryName, ref: `heads/${branch}`, sha: newCommitSha });
success = true;
} catch (e) {
// not sure what kinds of errors to expect here
Logger.error(`Committing files to branch ${branch} failed: ${e}`, this.id);
}
Logger.debug(`Committing files to branch ${branch} - done`, this.id);
return success;
}
async getCommitParent(ref: string): Promise<string | undefined> {
Logger.debug(`Fetch commit for ref ${ref} - enter`, this.id);
try {
const { octokit, remote } = await this.ensure();
const commit = (await octokit.call(octokit.api.repos.getCommit, { owner: remote.owner, repo: remote.repositoryName, ref })).data;
return commit.parents[0].sha;
} catch (e) {
Logger.error(`Fetching commit for ref ${ref} failed: ${e}`, this.id);
}
Logger.debug(`Fetch commit for ref ${ref} - done`, this.id);
}
async getAllPullRequests(page?: number): Promise<PullRequestData | undefined> {
let remote: GitHubRemote | undefined;
try {
Logger.debug(`Fetch all pull requests - enter`, this.id);
const ensured = await this.ensure();
remote = ensured.remote;
const octokit = ensured.octokit;
const result = await octokit.call(octokit.api.pulls.list, {
owner: remote.owner,
repo: remote.repositoryName,
per_page: PULL_REQUEST_PAGE_SIZE,
page: page || 1,
});
const hasMorePages = !!result.headers.link && result.headers.link.indexOf('rel="next"') > -1;
if (!result.data) {
// We really don't expect this to happen, but it seems to (see #574).
// Log a warning and return an empty set.
Logger.warn(
`No result data for ${remote.owner}/${remote.repositoryName} Status: ${result.status}`,
);
return {
items: [],
hasMorePages: false,
totalCount: 0
};
}
const pullRequests = result.data
.map(pullRequest => {
if (!pullRequest.head.repo) {
Logger.appendLine('The remote branch for this PR was already deleted.', this.id);
return null;
}
return this.createOrUpdatePullRequestModel(
convertRESTPullRequestToRawPullRequest(pullRequest, this),
);
})
.filter(item => item !== null) as PullRequestModel[];
Logger.debug(`Fetch all pull requests - done`, this.id);
return {
items: pullRequests,
hasMorePages
};
} catch (e) {
Logger.error(`Fetching all pull requests failed: ${e}`, this.id);
if (e.status === 404) {
// not found
vscode.window.showWarningMessage(
`Fetching all pull requests for remote '${remote?.remoteName}' failed, please check if the repository ${remote?.owner}/${remote?.repositoryName} is valid.`,
);
} else {
throw e;
}
}
return undefined;
}
async getPullRequestNumbers(): Promise<PullRequestNumberData[] | undefined> {
let remote: GitHubRemote | undefined;
try {
Logger.debug(`Fetch pull request numbers - enter`, this.id);
const ensured = await this.ensure();
remote = ensured.remote;
const { query, schema } = ensured;
const { data } = await query<PullRequestNumbersResponse>({
query: schema.PullRequestNumbers,
variables: {
owner: remote.owner,
name: remote.repositoryName,
first: 100,
},
});
Logger.debug(`Fetch pull request numbers - done`, this.id);
if (data?.repository?.pullRequests) {
return data.repository.pullRequests.nodes;
}
} catch (e) {
Logger.error(`Fetching pull request numbers failed: ${e}`, this.id);
if (e.status === 404) {
// not found
vscode.window.showWarningMessage(
`Fetching pull request numbers for remote '${remote?.remoteName}' failed, please check if the repository ${remote?.owner}/${remote?.repositoryName} is valid.`,
);
} else {
throw e;
}
}
return undefined;
}
async getPullRequestForBranch(branch: string, headOwner: string): Promise<PullRequestModel | undefined> {
let remote: GitHubRemote | undefined;
try {
Logger.debug(`Fetch pull requests for branch - enter`, this.id);
const ensured = await this.ensure();
remote = ensured.remote;
const { query, schema } = ensured;
const { data } = await query<PullRequestsResponse>({
query: schema.PullRequestForHead,
variables: {
owner: remote.owner,
name: remote.repositoryName,
headRefName: branch,
},
});
Logger.debug(`Fetch pull requests for branch - done`, this.id);
if (data?.repository && data.repository.pullRequests.nodes.length > 0) {
const prs = (await Promise.all(data.repository.pullRequests.nodes.map(node => parseGraphQLPullRequest(node, this)))).filter(pr => pr.head?.repo.owner === headOwner);
if (prs.length === 0) {
return undefined;
}
const mostRecentOrOpenPr = prs.find(pr => pr.state.toLowerCase() === 'open') ?? prs[0];
return this.createOrUpdatePullRequestModel(mostRecentOrOpenPr);
}
} catch (e) {
Logger.error(`Fetching pull request for branch failed: ${e}`, this.id);
if (e.status === 404) {
// not found
vscode.window.showWarningMessage(
`Fetching pull request for branch for remote '${remote?.remoteName}' failed, please check if the repository ${remote?.owner}/${remote?.repositoryName} is valid.`,
);
}
}
return undefined;
}
async canGetProjectsNow(): Promise<boolean> {
let { schema } = await this.ensure();
if (schema.GetRepoProjects && schema.GetOrgProjects) {
return true;
}
return false;
}
async getOrgProjects(): Promise<IProject[]> {
Logger.debug(`Fetch org projects - enter`, this.id);
let { query, remote, schema } = await this.ensure();
const projects: IProject[] = [];
try {
const { data } = await query<OrgProjectsResponse>({
query: schema.GetOrgProjects,
variables: {
owner: remote.owner,
after: null,
}
});
if (data && data.organization.projectsV2 && data.organization.projectsV2.nodes) {
data.organization.projectsV2.nodes.forEach(raw => {
projects.push(raw);
});
}
} catch (e) {
Logger.error(`Unable to fetch org projects: ${e}`, this.id);
return projects;
}
Logger.debug(`Fetch org projects - done`, this.id);
return projects;
}
async getProjects(): Promise<IProject[] | undefined> {
try {
Logger.debug(`Fetch projects - enter`, this.id);
let { query, remote, schema } = await this.ensure();
if (!schema.GetRepoProjects) {
const additional = await this.ensureAdditionalScopes();
query = additional.query;
remote = additional.remote;
schema = additional.schema;
}
const { data } = await query<RepoProjectsResponse>({
query: schema.GetRepoProjects,
variables: {
owner: remote.owner,
name: remote.repositoryName,
},
});
Logger.debug(`Fetch projects - done`, this.id);
const projects: IProject[] = [];
if (data && data.repository?.projectsV2 && data.repository.projectsV2.nodes) {
data.repository.projectsV2.nodes.forEach(raw => {
projects.push(raw);
});
}
return projects;
} catch (e) {
Logger.error(`Unable to fetch projects: ${e}`, this.id);
return;
}
}
async getMilestones(includeClosed: boolean = false): Promise<IMilestone[] | undefined> {
try {
Logger.debug(`Fetch milestones - enter`, this.id);
const { query, remote, schema } = await this.ensure();
const states = ['OPEN'];
if (includeClosed) {
states.push('CLOSED');
}
const { data } = await query<MilestoneIssuesResponse>({
query: schema.GetMilestones,
variables: {
owner: remote.owner,
name: remote.repositoryName,
states: states,
},
});
Logger.debug(`Fetch milestones - done`, this.id);
const milestones: IMilestone[] = [];
if (data && data.repository?.milestones && data.repository.milestones.nodes) {
data.repository.milestones.nodes.forEach(raw => {
const milestone = parseMilestone(raw);
if (milestone) {
milestones.push(milestone);
}
});
}
return milestones;
} catch (e) {
Logger.error(`Unable to fetch milestones: ${e}`, this.id);
return;
}
}
async getLines(sha: string, file: string, lineStart: number, lineEnd: number): Promise<string | undefined> {
Logger.debug(`Fetch milestones - enter`, this.id);
const { query, remote, schema } = await this.ensure();
const { data } = await query<FileContentResponse>({
query: schema.GetFileContent,
variables: {
owner: remote.owner,
name: remote.repositoryName,
expression: `${sha}:${file}`
}
});
if (!data.repository?.object.text) {
return undefined;
}
return data.repository.object.text.split('\n').slice(lineStart - 1, lineEnd).join('\n');
}
async getIssues(page?: number, queryString?: string): Promise<IssueData | undefined> {
try {
Logger.debug(`Fetch issues with query - enter`, this.id);
const { query, schema } = await this.ensure();
const { data } = await query<IssuesSearchResponse>({
query: schema.Issues,
variables: {
query: `${queryString} type:issue`,
},
});
Logger.debug(`Fetch issues with query - done`, this.id);
const issues: Issue[] = [];
if (data && data.search.edges) {
await Promise.all(data.search.edges.map(async raw => {
if (raw.node.id) {
issues.push(await parseGraphQLIssue(raw.node, this));
}
}));
}
return {
items: issues,
hasMorePages: data.search.pageInfo.hasNextPage,
totalCount: data.search.issueCount
};
} catch (e) {
Logger.error(`Unable to fetch issues with query: ${e}`, this.id);
return;
}
}
private async _getMaxItem(isIssue: boolean): Promise<number | undefined> {
try {
Logger.debug(`Fetch max ${isIssue ? 'issue' : 'pull request'} - enter`, this.id);
const { query, remote, schema } = await this.ensure();
const { data } = await query<MaxIssueResponse>({
query: isIssue ? schema.MaxIssue : schema.MaxPullRequest,
variables: {
owner: remote.owner,
name: remote.repositoryName,
},
});
Logger.debug(`Fetch max ${isIssue ? 'issue' : 'pull request'} - done`, this.id);
if (data?.repository && data.repository.issues.edges.length === 1) {
return data.repository.issues.edges[0].node.number;
}
return;
} catch (e) {
Logger.error(`Unable to fetch ${isIssue ? 'issues' : 'pull requests'} with query: ${e}`, this.id);
return;
}
}
async getMaxIssue(): Promise<number | undefined> {
return this._getMaxItem(true);
}
async getMaxPullRequest(): Promise<number | undefined> {
return this._getMaxItem(false);
}
async getViewerPermission(): Promise<ViewerPermission> {
try {
Logger.debug(`Fetch viewer permission - enter`, this.id);
const { query, remote, schema } = await this.ensure();
const { data } = await query<ViewerPermissionResponse>({
query: schema.GetViewerPermission,
variables: {
owner: remote.owner,
name: remote.repositoryName,
},
});
Logger.debug(`Fetch viewer permission - done`, this.id);
return parseGraphQLViewerPermission(data);
} catch (e) {
Logger.error(`Unable to fetch viewer permission: ${e}`, this.id);
return ViewerPermission.Unknown;
}
}
public async getWorkflowRunsFromAction(fromDate: string): Promise<OctokitCommon.ListWorkflowRunsForRepo[]> {
const { octokit, remote } = await this.ensure();
const createdDate = new Date(fromDate);
const created = `>=${createdDate.getFullYear()}-${String(createdDate.getMonth() + 1).padStart(2, '0')}-${String(createdDate.getDate()).padStart(2, '0')}`;
const allRuns = await restPaginate<typeof octokit.api.actions.listWorkflowRunsForRepo, OctokitCommon.ListWorkflowRunsForRepo>(octokit.api.actions.listWorkflowRunsForRepo, {
owner: remote.owner,
repo: remote.repositoryName,
event: 'dynamic',
created
});
return allRuns;
}
public async getWorkflowJobs(workflowRunId: number): Promise<OctokitCommon.WorkflowJob[]> {
const { octokit, remote } = await this.ensure();
const jobs = await octokit.call(octokit.api.actions.listJobsForWorkflowRun, {
owner: remote.owner,
repo: remote.repositoryName,
run_id: workflowRunId
});
return jobs.data.jobs;
}
async getCheckRunLogs(checkRunDatabaseId: number): Promise<string> {
Logger.debug(`Fetch check run logs - enter`, this.id);
const { octokit, remote } = await this.ensure();
// Try GitHub Actions logs first (works for Actions workflow runs)
try {
const result = await octokit.call(octokit.api.actions.downloadJobLogsForWorkflowRun, {
owner: remote.owner,
repo: remote.repositoryName,
job_id: checkRunDatabaseId,
});
Logger.debug(`Fetch check run logs via Actions API - done`, this.id);
return result.data as string;
} catch {
// Not a GitHub Actions job - fall through to Checks API
}
// Fall back to Checks API output (works for any GitHub App, e.g. Azure Pipelines)
try {
const result = await octokit.call(octokit.api.checks.get, {
owner: remote.owner,
repo: remote.repositoryName,
check_run_id: checkRunDatabaseId,
});
const output = result.data.output;
const parts: string[] = [];
if (output.title) {
parts.push(output.title);
parts.push('');