Repository navigation
Expand file tree
/
Copy pathGitHubSourceControlProvider.ts
More file actions
1106 lines (1051 loc) · 42.4 KB
/
Copy pathGitHubSourceControlProvider.ts
File metadata and controls
1106 lines (1051 loc) · 42.4 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
import { SourceControlProviderKind } from "@t3tools/contracts";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import {
GraphQL,
GraphQLClient,
GraphQLClientError,
GraphQLGroup,
GraphQLResolver,
} from "effect/graphql";
import * as Option from "effect/Option";
import * as RequestResolver from "effect/RequestResolver";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import {
SourceControlProviderError,
TrimmedNonEmptyString,
type ChangeRequest,
type SourceControlProviderDiscoveryItem,
type SourceControlRepositoryCloneUrls,
} from "@t3tools/contracts";
import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
import { GH_PROCESS_CONCURRENCY } from "./GitHubCredentials.ts";
import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
import * as GitHubRest from "./GitHubRest.ts";
import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
import * as GitHubChangeRequestTemplate from "./gitHubChangeRequestTemplate.ts";
import * as GitHubGraphQlClient from "./gitHubGraphQlClient.ts";
import {
normalizeGitHubPullRequestRecord,
type NormalizedGitHubPullRequestRecord,
} from "./gitHubPullRequests.ts";
import {
gitHubApiHostForRemote,
parseFetchRemotes,
parseGitHubRepositorySelector,
parsePullRequestReference,
resolveGitHubRepository,
type GitHubRepositoryLocator,
} from "./gitHubRepositoryResolution.ts";
import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
import {
effectiveGitHubAccount,
findAuthenticatedGitHubAccount,
parseGitHubAuthStatus,
type GitHubAuthStatusAccount,
} from "./gitHubAuthStatus.ts";
import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
import {
combinedAuthOutput,
firstSafeAuthLine,
probeSourceControlProvider,
providerAuth,
type SourceControlAuthProbeInput,
type SourceControlCliDiscoverySpec,
type SourceControlManagedCliDiscoverySpec,
} from "@t3tools/source-control-core/server/discovery";
import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition";
import * as GitHubClient from "../shared/definition.ts";
import {
PullRequestByNumber,
PullRequestNode,
PullRequestsByHead,
} from "./sourceControlProvider.graphql.ts";
// Decode rows separately to isolate malformed PRs within shared documents.
const LenientPullRequestsByHead = GraphQL.query(PullRequestsByHead.name, {
// `GraphQLResolver.aliased` needs a template per lookup.
document: PullRequestsByHead.template!,
variables: PullRequestsByHead.variables,
result: Schema.Struct({
repository: Schema.NullOr(
Schema.Struct({
pullRequests: Schema.Struct({ nodes: Schema.NullOr(Schema.Array(Schema.Unknown)) }),
}),
),
}),
});
const decodePullRequestNode = Schema.decodeUnknownOption(PullRequestNode);
const decodeLinkSubject = Schema.decodeUnknownEffect(
Schema.fromJsonString(
Schema.Struct({ title: Schema.String, body: Schema.optional(Schema.NullOr(Schema.String)) }),
),
);
function toChangeRequest(record: NormalizedGitHubPullRequestRecord): ChangeRequest {
return { provider: SourceControlProviderKind.make("github"), ...record };
}
function authAccounts(accounts: ReadonlyArray<GitHubAuthStatusAccount>) {
return accounts.map((entry) => ({
host: entry.host,
account: entry.account,
active: entry.active,
authenticated: entry.authenticated,
...(entry.error === null ? {} : { error: entry.error }),
...(entry.environmentVariable === null
? {}
: { environmentVariable: entry.environmentVariable }),
}));
}
export function parseGitHubAuth(
input: SourceControlAuthProbeInput,
settings: GitHubClient.GitHubSettings = readSourceControlHostSettings(GitHubClient.settings, {}),
) {
const output = combinedAuthOutput(input);
const authStatus = parseGitHubAuthStatus(input.stdout);
const hosts = [...new Set(authStatus.accounts.map((entry) => entry.host))];
const fallback = findAuthenticatedGitHubAccount(authStatus.accounts);
const orderedHosts = fallback
? [fallback.host, ...hosts.filter((host) => host !== fallback.host)]
: hosts;
const chosen = orderedHosts
.map((host) => effectiveGitHubAccount(host, authStatus.accounts, settings))
.find((entry) => entry !== undefined);
const accounts = authStatus.parsed ? { accounts: authAccounts(authStatus.accounts) } : {};
if (chosen) {
return {
...providerAuth({
status: "authenticated",
account: chosen.account,
host: chosen.host,
detail:
chosen.environmentVariable === null
? undefined
: `Using ${chosen.environmentVariable} from the server environment; it overrides the account chosen in Settings.`,
}),
...accounts,
};
}
if (fallback) {
return {
...providerAuth({
status: "unauthenticated",
host: fallback.host,
detail: "Every GitHub host gh is signed in to is turned off in Settings → Source Control.",
}),
...accounts,
};
}
const failedAccount = authStatus.accounts.find((entry) => entry.active) ?? authStatus.accounts[0];
if (authStatus.parsed) {
return {
...providerAuth({
status: "unauthenticated",
host: failedAccount?.host,
detail:
failedAccount?.error ??
"Run `gh auth login` to authenticate GitHub CLI with an active account.",
}),
...accounts,
};
}
// gh before 2.81.0 rejects --json with a nonzero exit that resembles a signed-out CLI.
if (input.exitCode !== 0 && output.includes("unknown flag: --json")) {
return providerAuth({
status: "unknown",
detail:
"GitHub CLI is too old to report sign-in status. Update `gh` to 2.81.0 or newer (for example `brew upgrade gh`) and rescan.",
});
}
if (input.exitCode !== 0) {
return providerAuth({
status: "unauthenticated",
detail: firstSafeAuthLine(output) ?? "Run `gh auth login` to authenticate GitHub CLI.",
});
}
return providerAuth({
status: "unknown",
detail: firstSafeAuthLine(output) ?? "GitHub CLI auth status could not be parsed.",
});
}
export const discovery = {
type: "cli",
kind: SourceControlProviderKind.make("github"),
label: "GitHub",
executable: "gh",
versionArgs: ["--version"],
authArgs: ["auth", "status", "--json", "hosts"],
parseAuth: parseGitHubAuth,
installHint:
"Install the GitHub command-line tool (`gh`) via https://cli.github.com/ or your package manager (for example `brew install gh`).",
} satisfies SourceControlCliDiscoverySpec;
const decodeViewer = Schema.decodeUnknownOption(
Schema.fromJsonString(Schema.Struct({ login: Schema.String })),
);
function environmentTokenVariable(environment: NodeJS.ProcessEnv): string | null {
return ["GH_TOKEN", "GITHUB_TOKEN"].find((name) => environment[name]?.trim()) ?? null;
}
// `gh auth status` may not know environment tokens; check the API.
export const makeDiscovery = Effect.gen(function* () {
const api = yield* GitHubRest.GitHubRest;
const sourceControlHost = yield* SourceControlHost.SourceControlHost;
const process = sourceControlHost.process;
const environment = yield* HostProcess.Environment;
const appSignIn = yield* GitHubAppSignIn.GitHubAppSignIn;
const offerAppSignIn = <A extends SourceControlProviderDiscoveryItem>(item: A): A =>
appSignIn.enabled ? { ...item, appSignIn: true } : item;
return {
type: "managed-cli",
kind: discovery.kind,
label: discovery.label,
installHint: discovery.installHint,
probe: Effect.fn("GitHubSourceControlProvider.discovery")(function* (cwd: string) {
const settings = readSourceControlHostSettings(
GitHubClient.settings,
yield* sourceControlHost.settings.get.pipe(
Effect.map((current) => current.sourceControlHosts[GitHubClient.definition.kind]),
Effect.orElseSucceed(() => undefined),
),
);
const cli = yield* probeSourceControlProvider({
cwd,
process: {
run: (input) => process.run({ ...input, concurrency: GH_PROCESS_CONCURRENCY }),
},
spec: { ...discovery, parseAuth: (input) => parseGitHubAuth(input, settings) },
});
const savedToken = (settings.tokens["github.com"] ?? "").trim() !== "";
const signedIn =
appSignIn.enabled && !savedToken && (settings.signIns["github.com"] ?? "").trim() !== "";
const variable = environmentTokenVariable(environment);
const appName = GitHubClient.APP_SIGN_IN.appName;
const tokenSource = savedToken
? "the token saved in Settings"
: signedIn
? `the ${appName} sign-in`
: variable;
if (tokenSource === null || settings.hosts["github.com"]?.enabled === false) {
return offerAppSignIn(cli);
}
const viewer = yield* api
.rest({ host: "github.com", operation: "discovery", path: "user" })
.pipe(Effect.result);
const login = Result.isSuccess(viewer)
? Option.getOrUndefined(decodeViewer(viewer.success.body))?.login
: undefined;
const accounts = cli.auth.accounts === undefined ? {} : { accounts: cli.auth.accounts };
return offerAppSignIn({
...cli,
status: "available" as const,
auth: {
...(login !== undefined
? providerAuth({
status: "authenticated",
account: login,
host: "github.com",
detail: savedToken
? "Using the token saved in Settings; it overrides GH_TOKEN and the gh login."
: signedIn
? `Signed in with ${appName}.`
: `Using ${variable} from the server environment; it overrides the account chosen in Settings.`,
})
: Result.isFailure(viewer) && viewer.failure._tag !== "GitHubApiAuthenticationError"
? providerAuth({
status: "unknown",
host: "github.com",
detail: `Could not check ${savedToken || signedIn ? tokenSource : `the token in ${tokenSource}`}: ${viewer.failure.message}`,
})
: providerAuth({
status: "unauthenticated",
host: "github.com",
detail: savedToken
? "GitHub refused the token saved in Settings. Replace or remove it in Settings → Source Control."
: signedIn
? `GitHub refused the ${appName} sign-in. Sign in again in Settings → Source Control.`
: `GitHub refused the token in ${tokenSource}. Replace it, or unset it to use \`gh auth login\`.`,
})),
...accounts,
},
} satisfies SourceControlProviderDiscoveryItem);
}),
// Claim disabled hosts so errors identify the setting.
refineUnknownRemote: ({ context }) => {
const url = URL.parse(context.provider.baseUrl);
if (!url?.host) return Effect.succeed(null);
// A timeout or keyring failure propagates: the registry does not keep that answer.
return api.credential(url.host).pipe(
Effect.as(true),
Effect.catchTags({
GitHubCliMissingError: () => Effect.succeed(false),
GitHubHostDisabledError: () => Effect.succeed(true),
GitHubNotSignedInError: () => Effect.succeed(false),
}),
Effect.map((known) =>
known
? ({
kind: SourceControlProviderKind.make("github"),
name: "GitHub Self-Hosted",
baseUrl: context.provider.baseUrl,
} as const)
: null,
),
);
},
} satisfies SourceControlManagedCliDiscoverySpec;
});
class GitHubFailure extends Data.TaggedError("GitHubFailure")<{
readonly detail: string;
readonly cause: unknown;
}> {}
const failure = (detail: string, cause?: unknown) => new GitHubFailure({ detail, cause });
const PULL_REQUEST_NOT_FOUND = "Pull request not found. Check the PR number or URL and try again.";
const REPOSITORY_NOT_FOUND = "Repository not found. Check the owner and name and try again.";
function fromGitHubApiError(
error: GitHubRequestPolicy.GitHubApiError,
notFound = PULL_REQUEST_NOT_FOUND,
): GitHubFailure {
switch (error._tag) {
case "GitHubCliMissingError":
return failure(
"No GitHub credential on the server. Set GH_TOKEN, or install the GitHub CLI and run `gh auth login`.",
error,
);
case "GitHubNotSignedInError":
case "GitHubHostDisabledError":
return failure(error.message, error);
case "GitHubApiAuthenticationError":
return failure(
"GitHub is not authenticated. Run `gh auth login` (or set GH_TOKEN) and retry.",
error,
);
case "GitHubApiRateLimitError":
case "SourceControlRateLimitPausedError":
return failure(
"GitHub API rate limit exceeded. Requests resume when the limit resets.",
error,
);
case "GitHubApiNotFoundError":
return failure(notFound, error);
case "GitHubCliFailedError":
case "GitHubAppSessionError":
case "GitHubApiResponseError":
case "GitHubApiRequestError":
return failure(error.message.trim() || "GitHub request failed.", error);
}
}
const notFound = (cause: string) => failure(PULL_REQUEST_NOT_FOUND, new Error(cause));
const RawRepositorySchema = Schema.Struct({
full_name: TrimmedNonEmptyString,
html_url: TrimmedNonEmptyString,
ssh_url: TrimmedNonEmptyString,
default_branch: Schema.optional(Schema.NullOr(Schema.String)),
});
const decodeRawRepository = decodeJsonResult(RawRepositorySchema);
function repositoryCloneUrls(
raw: Schema.Schema.Type<typeof RawRepositorySchema>,
): SourceControlRepositoryCloneUrls {
return { nameWithOwner: raw.full_name, url: raw.html_url, sshUrl: raw.ssh_url };
}
const decodeViewerLogin = decodeJsonResult(Schema.Struct({ login: TrimmedNonEmptyString }));
type PullRequestListState = "open" | "closed" | "merged" | "all";
const GRAPHQL_STATES: Record<
PullRequestListState,
NonNullable<PullRequestsByHead.Variables["states"]>
> = {
open: ["OPEN"],
closed: ["CLOSED"],
merged: ["MERGED"],
all: ["OPEN", "CLOSED", "MERGED"],
};
/** 50 lookups keeps responses near 0.5s at the same one-point cost as 100. */
const HEAD_LOOKUPS_PER_DOCUMENT = 50;
/** Git reads stagger background lookups by ~300ms; gather batches before spending quota. */
const HEAD_LOOKUP_BATCH_WINDOW = "50 millis";
const BACKGROUND_HEAD_LOOKUP_BATCH_WINDOW = "500 millis";
/** For heads matching 100 PRs each, 50 lookups approached GitHub's ~10s limit; 25 took ~7s. */
const BACKGROUND_HEAD_LOOKUPS_PER_DOCUMENT = 25;
const HEAD_LOOKUP_MAX_RESPONSE_BYTES = 16_000_000;
const OWNER_HEAD_SCAN_LIMIT = 100;
function trimmed(value: string): string | null {
const text = value.trim();
return text.length > 0 ? text : null;
}
/** Null isolates unusable PRs from the rest of a listing. */
function toPullRequestRecord(node: PullRequestNode): NormalizedGitHubPullRequestRecord | null {
const title = trimmed(node.title);
const url = trimmed(node.url);
const baseRefName = trimmed(node.baseRefName);
const headRefName = trimmed(node.headRefName);
const updatedAt = DateTime.make(node.updatedAt);
if (node.number < 1 || !title || !url || !baseRefName || !headRefName) return null;
if (Option.isNone(updatedAt)) return null;
return normalizeGitHubPullRequestRecord({
...node,
title,
url,
baseRefName,
headRefName,
updatedAt: Option.some(DateTime.toUtc(updatedAt.value)),
});
}
export function pullRequestCheckoutBranchName(input: {
readonly headRefName: string;
readonly headOwner: string | null;
readonly isCrossRepository: boolean;
readonly defaultBranch: string | null;
}): string {
return input.isCrossRepository &&
input.headOwner !== null &&
input.defaultBranch !== null &&
input.headRefName === input.defaultBranch
? `${input.headOwner}/${input.headRefName}`
: input.headRefName;
}
const contextHost = (context: SourceControlProvider.SourceControlProviderContext | undefined) =>
context === undefined ? undefined : new URL(context.provider.baseUrl).host;
export const make = Effect.gen(function* () {
const api = yield* GitHubRest.GitHubRest;
const sourceControlHost = yield* SourceControlHost.SourceControlHost;
const process = sourceControlHost.process;
const environment = yield* HostProcess.Environment;
const git = sourceControlHost.git;
const fileSystem = yield* FileSystem.FileSystem;
const gitRead = (cwd: string, args: ReadonlyArray<string>) =>
process.run({
operation: "GitHubSourceControlProvider.resolveRepository",
command: "git",
args,
cwd,
allowNonZeroExit: true,
timeoutMs: 5_000,
});
const resolveRepository = Effect.fn("GitHubSourceControlProvider.resolveRepository")(
function* (input: {
readonly cwd: string;
readonly host?: string | undefined;
readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
}) {
const envRepository = environment.GH_REPO?.trim();
const hostHint = input.host ?? contextHost(input.context);
const defaultHost = (hostHint ?? environment.GH_HOST ?? "github.com").toLowerCase();
if (envRepository) {
const locator = parseGitHubRepositorySelector(envRepository, defaultHost);
if (locator !== null) return locator;
}
const [remotes, resolved] = yield* Effect.all([
gitRead(input.cwd, ["remote", "-v"]),
gitRead(input.cwd, ["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"]),
]).pipe(Effect.orElseSucceed(() => [null, null] as const));
const { host, locator } = resolveGitHubRepository({
remotes: remotes?.exitCode === 0 ? remotes.stdout : "",
resolved: resolved?.exitCode === 0 ? resolved.stdout : "",
hostHint,
defaultHost,
});
if (locator !== null) return locator;
if (input.context) {
const remote = normalizeGitRemoteUrl(input.context.remoteUrl);
const fallback = parseGitHubRepositorySelector(
`${host}/${remote.slice(remote.indexOf("/") + 1)}`,
host,
);
if (fallback !== null) return fallback;
}
return yield* failure(
`No GitHub repository on ${host} was found among this checkout's git remotes.`,
);
},
);
const client = yield* GraphQLClient.make(
GraphQLGroup.make(LenientPullRequestsByHead, PullRequestByNumber).middleware(
GitHubGraphQlClient.GitHubGraphQlAuth,
),
).pipe(Effect.provide(GitHubGraphQlClient.layer));
const graphqlRead = <A, E, R>(
target: GitHubGraphQlClient.GitHubGraphQlTarget["Service"],
decodeDetail: string,
effect: Effect.Effect<A, E, R>,
) =>
effect.pipe(
GitHubGraphQlClient.call(target),
Effect.mapError((error) =>
GraphQLClientError.isGraphQLClientError(error)
? failure(decodeDetail, error)
: fromGitHubApiError(error as GitHubRequestPolicy.GitHubApiError),
),
);
const rest = (input: GitHubRest.GitHubRestInput, notFoundDetail?: string) =>
api.rest(input).pipe(Effect.mapError((error) => fromGitHubApiError(error, notFoundDetail)));
// Batch by host/credential; isolate missing repositories and interactive/background reserves.
const headResolver = GraphQLResolver.aliased(client.PullRequestsByHead, {
batchKey: GitHubGraphQlClient.batchKey,
}).pipe(RequestResolver.batchN(HEAD_LOOKUPS_PER_DOCUMENT));
const interactiveHeadResolver = headResolver.pipe(
RequestResolver.setDelay(HEAD_LOOKUP_BATCH_WINDOW),
);
const backgroundHeadResolver = headResolver.pipe(
RequestResolver.batchN(BACKGROUND_HEAD_LOOKUPS_PER_DOCUMENT),
RequestResolver.setDelay(BACKGROUND_HEAD_LOOKUP_BATCH_WINDOW),
);
const listByHead = Effect.fn("GitHubSourceControlProvider.listByHead")(function* (input: {
readonly cwd: string;
readonly headSelector: string;
readonly state: PullRequestListState;
readonly limit: number;
readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
readonly host?: string | undefined;
readonly allowReserve: boolean;
}) {
const locator = yield* resolveRepository(input);
const limit = Math.min(Math.max(Math.trunc(input.limit), 1), 100);
const ownerMatch = /^([^:/\s]+):(.+)$/u.exec(input.headSelector.trim());
const headRefName = ownerMatch?.[2] ?? input.headSelector.trim();
const result = yield* graphqlRead(
{
host: locator.host,
operation: "listPullRequestsByHead",
allowReserve: input.allowReserve,
// 50 default-branch lookups can each match 100 fork PRs and exceed the usual cap.
maxResponseBytes: HEAD_LOOKUP_MAX_RESPONSE_BYTES,
},
"GitHub returned an invalid change request list.",
GraphQLResolver.request(
{
owner: locator.owner,
name: locator.name,
head: headRefName,
states: GRAPHQL_STATES[input.state],
first: ownerMatch ? OWNER_HEAD_SCAN_LIMIT : limit,
},
input.allowReserve ? interactiveHeadResolver : backgroundHeadResolver,
),
);
if (result.repository === null) return yield* notFound("The repository could not be read.");
const rows = (result.repository.pullRequests.nodes ?? []).flatMap((entry) => {
const node = Option.getOrNull(decodePullRequestNode(entry));
const record = node === null ? null : toPullRequestRecord(node);
return record === null ? [] : [record];
});
if (!ownerMatch) return rows;
const headOwner = ownerMatch[1]!.toLowerCase();
return rows
.filter((row) => row.headRepositoryOwnerLogin?.toLowerCase() === headOwner)
.slice(0, limit);
});
const readPullRequest = Effect.fn("GitHubSourceControlProvider.readPullRequest")(
function* (input: {
readonly cwd: string;
readonly reference: string;
readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
readonly host?: string | undefined;
}) {
const parsed = parsePullRequestReference(input.reference);
if (parsed.kind === "branch") {
// `gh pr view <branch>` prefers an open pull request, then the newest of any state.
const lookup = (state: PullRequestListState) =>
listByHead({
cwd: input.cwd,
headSelector: parsed.headSelector,
state,
limit: 1,
host: input.host,
context: input.context,
allowReserve: true,
});
const [open] = yield* lookup("open");
const found = open ?? (yield* lookup("all"))[0];
if (found === undefined) return yield* notFound("No pull request has this head branch.");
return found;
}
const locator = parsed.kind === "url" ? parsed.locator : yield* resolveRepository(input);
const decodeDetail = "GitHub returned an invalid pull request.";
const result = yield* graphqlRead(
{ host: locator.host, operation: "getPullRequest", allowReserve: true },
decodeDetail,
client.PullRequestByNumber({
owner: locator.owner,
name: locator.name,
number: parsed.number,
}),
);
const node = result.repository?.pullRequest;
if (node == null) return yield* notFound("The pull request does not exist.");
const record = toPullRequestRecord(node);
if (record === null)
return yield* failure(decodeDetail, new Error("Malformed pull request."));
return record;
},
);
const readRepository = Effect.fn("GitHubSourceControlProvider.readRepository")(function* (
locator: GitHubRepositoryLocator,
) {
const response = yield* rest(
{
host: locator.host,
operation: "getRepository",
path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}`,
allowReserve: true,
},
REPOSITORY_NOT_FOUND,
);
const decoded = decodeRawRepository(response.body);
if (Result.isFailure(decoded)) {
return yield* failure("GitHub returned an invalid repository.", decoded.failure);
}
return decoded.success;
});
const readViewerLogin = Effect.fn("GitHubSourceControlProvider.readViewerLogin")(function* (
host: string,
) {
const response = yield* rest({
host,
operation: "getViewer",
path: "user",
allowReserve: true,
});
const decoded = decodeViewerLogin(response.body);
if (Result.isFailure(decoded)) {
return yield* failure("GitHub request failed.", decoded.failure);
}
return decoded.success.login;
});
// Keep paths, argv and stderr in cause; expose only a fixed checkout error to clients.
const gitFailure = (cause: unknown) =>
failure("The pull request could not be checked out with git.", cause);
const runGit = (cwd: string, operation: string, args: ReadonlyArray<string>) =>
git.execute({
operation: `GitHubSourceControlProvider.checkoutPullRequest.${operation}`,
cwd,
args,
});
const checkoutPullRequest = Effect.fn("GitHubSourceControlProvider.checkoutPullRequest")(
function* (input: {
readonly cwd: string;
readonly reference: string;
readonly force?: boolean;
readonly context?: SourceControlProvider.SourceControlProviderContext;
}) {
const reference = parsePullRequestReference(input.reference);
const pullRequest = yield* readPullRequest(input);
const base = reference.kind === "url" ? reference.locator : yield* resolveRepository(input);
const baseNameWithOwner = `${base.owner}/${base.name}`.toLowerCase();
const headNameWithOwner = pullRequest.headRepositoryNameWithOwner ?? null;
const isCrossRepository =
pullRequest.isCrossRepository ??
(headNameWithOwner !== null && headNameWithOwner.toLowerCase() !== baseNameWithOwner);
const headOwner =
pullRequest.headRepositoryOwnerLogin ?? headNameWithOwner?.split("/")[0] ?? null;
const remotes = yield* gitRead(input.cwd, ["remote", "-v"]).pipe(
Effect.map((result) => (result.exitCode === 0 ? result.stdout : "")),
Effect.mapError(gitFailure),
);
const remoteFor = (nameWithOwner: string) =>
parseFetchRemotes(remotes).find(
(remote) =>
(gitHubApiHostForRemote(remote.url) ??
normalizeGitRemoteUrl(remote.url).split("/")[0]) === base.host &&
normalizeGitRemoteUrl(remote.url).split("/").slice(1).join("/") ===
nameWithOwner.toLowerCase(),
)?.name ?? null;
const baseRemote = Effect.suspend(() => {
const known = remoteFor(baseNameWithOwner);
return known === null ? git.resolvePrimaryRemoteName(input.cwd) : Effect.succeed(known);
});
// Avoid resetting the default branch; prefix colliding forks and fail if it is unknown.
const defaultBranch = isCrossRepository
? yield* readRepository(base).pipe(
Effect.map((repository) => repository.default_branch ?? null),
)
: null;
const localBranch = pullRequestCheckoutBranchName({
headRefName: pullRequest.headRefName,
headOwner,
isCrossRepository,
defaultBranch,
});
const headRemote = Effect.gen(function* () {
if (!isCrossRepository) return yield* baseRemote;
if (headNameWithOwner === null) return yield* failure("The fork is gone.");
const known = remoteFor(headNameWithOwner);
if (known !== null) return known;
const [owner, name] = headNameWithOwner.split("/");
const fork = yield* readRepository({ host: base.host, owner: owner!, name: name! });
const originUrl = yield* git.readConfigValue(input.cwd, "remote.origin.url");
return yield* git.ensureRemote({
cwd: input.cwd,
preferredName: headOwner ?? "fork",
url: originUrl !== null && isSshRemoteUrl(originUrl) ? fork.ssh_url : fork.html_url,
});
});
const exists = (yield* git
.listLocalBranchNames(input.cwd)
.pipe(Effect.mapError(gitFailure))).includes(localBranch);
const target = yield* Effect.gen(function* () {
const remoteName = yield* headRemote;
yield* git.fetchRemoteTrackingBranch({
cwd: input.cwd,
remoteName,
remoteBranch: pullRequest.headRefName,
});
return {
ref: `refs/remotes/${remoteName}/${pullRequest.headRefName}`,
upstream: { remoteName, remoteBranch: pullRequest.headRefName },
};
}).pipe(
Effect.catch(() =>
Effect.gen(function* () {
yield* runGit(input.cwd, "fetchPullRef", [
"fetch",
"--quiet",
"--no-tags",
"--",
yield* baseRemote,
`refs/pull/${pullRequest.number}/head`,
]);
const { commitSha } = yield* git.resolveCommit({
cwd: input.cwd,
revision: "FETCH_HEAD",
});
return { ref: commitSha, upstream: null };
}),
),
Effect.mapError(gitFailure),
);
yield* Effect.gen(function* () {
if (!exists) {
yield* git.createBranch({ cwd: input.cwd, branch: localBranch, startPoint: target.ref });
}
yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
if (exists) {
yield* runGit(
input.cwd,
"sync",
input.force === true
? ["reset", "--hard", "--quiet", target.ref]
: ["merge", "--ff-only", "--quiet", target.ref],
);
}
// Set tracking after sync succeeds so a failed checkout preserves the existing upstream.
if (target.upstream !== null) {
yield* git.setBranchUpstream({ cwd: input.cwd, branch: localBranch, ...target.upstream });
}
}).pipe(Effect.mapError(gitFailure));
},
);
const providerError =
(
operation: string,
cwd: string,
context?: { readonly reference?: string; readonly repository?: string },
) =>
(error: GitHubFailure) =>
new SourceControlProviderError({
provider: SourceControlProviderKind.make("github"),
operation,
cwd,
...(context?.reference === undefined
? {}
: {
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
context.reference,
),
}),
...(context?.repository === undefined
? {}
: {
repository: SourceControlProvider.transportSafeSourceControlErrorValue(
context.repository,
),
}),
detail: error.detail,
cause: error.cause,
});
const readLinkSubject = Effect.fn("GitHubSourceControlProvider.readLinkSubject")(function* (
input: { readonly cwd: string; readonly url: URL },
endpoint: string,
) {
const result = yield* api
.rest({
host: input.url.host,
operation: "resolveLink",
path: endpoint,
maxResponseBytes: 1_000_000,
})
.pipe(
Effect.timeout("3 seconds"),
Effect.mapError(
(cause) =>
new SourceControlProviderError({
provider: SourceControlProviderKind.make("github"),
operation: "resolveLink",
cwd: input.cwd,
detail: "The linked subject could not be read.",
cause,
}),
),
);
const subject = yield* decodeLinkSubject(result.body).pipe(
Effect.mapError(
(cause) =>
new SourceControlProviderError({
provider: SourceControlProviderKind.make("github"),
operation: "resolveLink.decode",
cwd: input.cwd,
detail: "The linked subject could not be read.",
cause,
}),
),
);
return { title: subject.title, body: subject.body ?? null };
});
/**
* Fork: the identity names the `upstream` remote, but `#123` means a pull request in the
* repository gh opens them in, which `gh repo set-default` can point at `origin`. The web URL
* names that repository when it differs, so clients resolve bare numbers there.
*/
const refineRepositoryIdentity: NonNullable<
SourceControlProvider.SourceControlProvider["Service"]["refineRepositoryIdentity"]
> = Effect.fn("GitHubSourceControlProvider.refineRepositoryIdentity")(function* ({ identity }) {
if (identity.provider !== "github" || !identity.rootPath) return identity;
const base = yield* resolveRepository({ cwd: identity.rootPath }).pipe(Effect.option);
if (Option.isNone(base)) return identity;
const { host, owner, name } = base.value;
const key = `${host}/${owner}/${name}`.toLowerCase();
if (key === identity.canonicalKey) return identity;
// The resolved path is lower-cased; the origin keeps the remote's capitalisation.
const repository =
key === identity.origin?.canonicalKey
? (identity.origin.displayName ?? `${owner}/${name}`)
: `${owner}/${name}`;
return { ...identity, webUrl: `https://${host}/${repository}` };
});
return SourceControlProvider.SourceControlProvider.of({
kind: SourceControlProviderKind.make("github"),
refineRepositoryIdentity,
// `gh pr list --head` accepts only bare ref names; qualified selectors waste
// a GraphQL call and return nothing. Bare names also match other forks, so
// read a full page and check the owner to select the right head.
headBranchProbe: ({ headSelectors }) => ({
headSelectors: headSelectors.filter((selector) => !selector.includes(":")),
limit: 100,
}),
readChangeRequestTemplate: Effect.fn("GitHubSourceControlProvider.readChangeRequestTemplate")(
function ({ cwd, treeish }) {
return GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute);
},
),
// `createChangeRequest` targets what `resolveRepository` picks: GH_REPO when it parses, else
// the remote `gh repo set-default` marked (`gh-resolved`). An HTTPS remote keeps a
// non-default port in the context's host, and the mark is then ignored.
createsChangeRequestsIn: Effect.fn("GitHubSourceControlProvider.createsChangeRequestsIn")(
function* ({ cwd, context, repository }) {
const host = URL.canParse(context.provider.baseUrl)
? new URL(context.provider.baseUrl).host
: null;
const target = repository?.toLowerCase();
const fromEnvironment = parseGitHubRepositorySelector(
environment.GH_REPO ?? "",
host ?? "",
);
if (fromEnvironment !== null) {
const { host: targetHost, owner, name } = fromEnvironment;
return (
host !== null &&
URL.canParse(`https://${targetHost}`) &&
new URL(`https://${targetHost}`).host === host &&
`${owner}/${name}`.toLowerCase() === target
);
}
const mark = yield* git
.readConfigValue(cwd, `remote.${context.remoteName}.gh-resolved`)
.pipe(Effect.orElseSucceed(() => null));
const { locator } = resolveGitHubRepository({
remotes: `${context.remoteName}\t${context.remoteUrl} (fetch)`,
resolved: mark === null ? "" : `remote.${context.remoteName}.gh-resolved ${mark}`,
hostHint: host ?? undefined,
defaultHost: host ?? "github.com",
});
return locator === null || `${locator.owner}/${locator.name}`.toLowerCase() === target;
},
),
// `gh pr create` run in the checkout, as an agent in a T3 worktree often does, takes its base
// from this key.
recordBranchBase: Effect.fn("GitHubSourceControlProvider.recordBranchBase")(function ({
cwd,
branch,
baseBranch,
}) {
return git
.writeConfigValue({ cwd, key: `branch.${branch}.gh-merge-base`, value: baseBranch })
.pipe(
Effect.catch((cause) =>
Effect.logWarning("Could not record the branch base for gh", { cause }),
),
);
}),
resolveLink: (input) => {
// Automatic enrichment must not send ambient CLI credentials to a host from message text.
if (input.url.host !== "github.com") return undefined;
const match = /^\/([\w.-]+)\/([\w.-]+)\/(?:pull|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
input.url.pathname,
);
if (!match) return undefined;
return readLinkSubject(input, `repos/${match[1]}/${match[2]}/issues/${match[3]}`);
},
listChangeRequests: Effect.fn("GitHubSourceControlProvider.listChangeRequests")(
function (input) {
return (
input.state === "open" ? Effect.succeed(true) : SourceControlRateLimit.Interactive
).pipe(
Effect.flatMap((allowReserve) =>
listByHead({
cwd: input.cwd,
headSelector: input.headSelector,
state: input.state,
limit: input.limit ?? (input.state === "open" ? 1 : 20),
host: contextHost(input.context),
context: input.context,
allowReserve,
}),
),
Effect.map((records) => records.map(toChangeRequest)),
Effect.mapError(
providerError("listChangeRequests", input.cwd, { reference: input.headSelector }),
),
);
},
),
getChangeRequest: Effect.fn("GitHubSourceControlProvider.getChangeRequest")(function (input) {
return readPullRequest({ ...input, host: contextHost(input.context) }).pipe(
Effect.map(toChangeRequest),
Effect.mapError(
providerError("getChangeRequest", input.cwd, { reference: input.reference }),
),
);
}),
createChangeRequest: Effect.fn("GitHubSourceControlProvider.createChangeRequest")(
function* (input) {
const locator = yield* resolveRepository(input);
const body = yield* fileSystem
.readFileString(input.bodyFile)
.pipe(
Effect.mapError((cause) =>
failure("The pull request description could not be read.", cause),
),
);
yield* rest({
host: locator.host,
operation: "createPullRequest",
method: "POST",
allowReserve: true,