Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitCafeSourceControlProvider.ts

525 lines19.6 KB

1import { SourceControlProviderKind } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Option from "effect/Option";
4import * as Result from "effect/Result";
5import * as Schema from "effect/Schema";
6import * as Schedule from "effect/Schedule";
7import {
8 PositiveInt,
9 SourceControlProviderError,
10 TrimmedNonEmptyString,
11 type ChangeRequest,
12} from "@t3tools/contracts";
13import {
14 probeSourceControlProvider,
15 providerAuth,
16 type SourceControlCliDiscoverySpec,
17 type SourceControlManagedCliDiscoverySpec,
18} from "@t3tools/source-control-core/server/discovery";
19import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
20import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
21​
22import * as GitCafeApi from "./GitCafeApi.ts";
23import * as GitCafeCredentials from "./GitCafeCredentials.ts";
24import * as GitCafeHosts from "./gitCafeHosts.ts";
25​
26const AUTH_HOST = "git.cafe";
27const ADMISSION_TIMEOUT = "30 seconds";
28const ADMISSION_POLL_INTERVAL = "500 millis";
29const cliArgs = (host: string) => [
30 "--host",
31 `https://${host}/api`,
32 "--no-input",
33 "--no-update-check",
34];
35​
36const decodeAuth = Schema.decodeUnknownResult(
37 Schema.fromJsonString(
38 Schema.Struct({
39 schemaVersion: Schema.Literal(1),
40 data: Schema.Struct({ host: Schema.String, username: TrimmedNonEmptyString }),
41 }),
42 ),
43);
44const decodeFailure = Schema.decodeUnknownResult(
45 Schema.fromJsonString(
46 Schema.Struct({
47 schemaVersion: Schema.Literal(1),
48 error: Schema.Struct({
49 code: Schema.String,
50 message: Schema.String,
51 status: Schema.NullOr(Schema.Finite),
52 }),
53 }),
54 ),
55);
56const cliFailure = (output: string) =>
57 [output.trim(), ...output.split(/\r?\n/u).toReversed()]
58 .map((line) => decodeFailure(line.trim()))
59 .find(Result.isSuccess)?.success.error;
60​
61const cliDiscovery = {
62 type: "cli",
63 kind: SourceControlProviderKind.make("gitcafe"),
64 label: "GitCafe",
65 executable: "cafe",
66 versionArgs: ["--version"],
67 authArgs: [...cliArgs(AUTH_HOST), "auth", "status", "--json"],
68 parseAuth: (input) => {
69 const signedIn = decodeAuth(input.stdout.trim());
70 if (input.exitCode === 0 && Result.isSuccess(signedIn))
71 return providerAuth({
72 status: "authenticated",
73 host: AUTH_HOST,
74 account: signedIn.success.data.username,
75 });
76 const failure = cliFailure(input.stderr) ?? cliFailure(input.stdout);
77 if (failure)
78 return providerAuth({
79 // Only a refusal says the login is gone; a forbidden or offline answer says nothing.
80 status:
81 failure.code === "AUTHENTICATION_REQUIRED" || failure.status === 401
82 ? "unauthenticated"
83 : "unknown",
84 host: AUTH_HOST,
85 detail: failure.message,
86 });
87 return providerAuth({
88 status: "unknown",
89 host: AUTH_HOST,
90 detail: `GitCafe authentication status could not be read. Run \`cafe auth login --host https://${AUTH_HOST}/api\`.`,
91 });
92 },
93 installHint: `Install the GitCafe CLI with \`bun install -g @gitcafe/cli\`, then run \`cafe auth login --host https://${AUTH_HOST}/api\`, save a token in Settings, or set CAFE_TOKEN on the server.`,
94} satisfies SourceControlCliDiscoverySpec;
95​
96export const parseAuth = cliDiscovery.parseAuth;
97​
98export const makeDiscovery = Effect.gen(function* () {
99 const { process } = yield* SourceControlHost.SourceControlHost;
100 const credentials = yield* GitCafeCredentials.GitCafeCredentials;
101 return {
102 type: "managed-cli",
103 kind: cliDiscovery.kind,
104 label: cliDiscovery.label,
105 installHint: cliDiscovery.installHint,
106 probe: (cwd: string) =>
107 credentials.cliEnv(AUTH_HOST).pipe(
108 Effect.flatMap((env) =>
109 probeSourceControlProvider({
110 cwd,
111 spec: cliDiscovery,
112 process: { run: (input) => process.run({ ...input, env: { ...input.env, ...env } }) },
113 }),
114 ),
115 ),
116 refineUnknownRemote: () => Effect.succeed(null),
117 } satisfies SourceControlManagedCliDiscoverySpec;
118});
119​
120const Repository = Schema.Struct({
121 name: TrimmedNonEmptyString,
122 defaultBranch: Schema.NullOr(TrimmedNonEmptyString),
123});
124const Pull = Schema.Struct({
125 number: PositiveInt,
126 title: TrimmedNonEmptyString,
127 state: Schema.Literals(["open", "closed", "merged"]),
128 draft: Schema.Boolean,
129 sourceBranch: TrimmedNonEmptyString,
130 targetBranch: TrimmedNonEmptyString,
131 headOid: Schema.optional(Schema.NullOr(Schema.String)),
132 updatedAt: Schema.OptionFromNullOr(Schema.DateTimeUtcFromString),
133});
134const PullDetail = Schema.Struct({
135 ...Pull.fields,
136 sourceRepo: Schema.NullOr(
137 Schema.Struct({ owner: TrimmedNonEmptyString, name: TrimmedNonEmptyString }),
138 ),
139 closedAt: Schema.NullOr(Schema.String),
140 mergedAt: Schema.NullOr(Schema.String),
141});
142const Pulls = Schema.Struct({ items: Schema.Array(Pull), next: Schema.NullOr(Schema.String) });
143const RepositoryAdmission = Schema.Struct({
144 repoId: TrimmedNonEmptyString,
145 state: Schema.String,
146 owner: TrimmedNonEmptyString,
147 name: TrimmedNonEmptyString,
148});
149const CreatedRepository = Schema.Struct({
150 data: Schema.Struct({ resource: RepositoryAdmission }),
151});
152const decodeCreatedRepository = Schema.decodeEffect(Schema.fromJsonString(CreatedRepository));
153const encodeBranches = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
154​
155interface Target {
156 readonly host: GitCafeHosts.GitCafeHost;
157 readonly repository: string;
159​
160const cloneUrls = (target: Target) => ({
161 nameWithOwner: target.repository,
162 url: `https://${target.host}/${target.repository}`,
163 sshUrl: `ssh@${target.host}:${target.repository}.git`,
164});
165​
166const isSshRemote = (remoteUrl: string | undefined) =>
167 remoteUrl !== undefined && (/^ssh:\/\//iu.test(remoteUrl) || /^[^/:]+@[^/:]+:/u.test(remoteUrl));
168​
169const pullUrlPattern = /^https:\/\/([^/]+)\/([^/]+\/[^/]+)\/pulls\/(\d+)\/?(?:[?#].*)?$/u;
170​
171export const make = Effect.gen(function* () {
172 const api = yield* GitCafeApi.GitCafeApi;
173 const host = yield* SourceControlHost.SourceControlHost;
174 const credentials = yield* GitCafeCredentials.GitCafeCredentials;
175​
176 const error = (operation: string, cwd: string, detail: string, cause?: unknown) =>
177 new SourceControlProviderError({
178 provider: SourceControlProviderKind.make("gitcafe"),
179 operation,
180 cwd,
181 detail,
182 ...(cause === undefined ? {} : { cause }),
183 });
184 const read = <S extends Schema.Codec<unknown, unknown, never, never>>(
185 operation: string,
186 cwd: string,
187 request: Omit<GitCafeApi.GitCafeApiRequest, "operation">,
188 schema: S,
189 ) =>
190 api.request({ ...request, operation }).pipe(
191 Effect.mapError((cause) => error(operation, cwd, cause.detail, cause)),
192 Effect.flatMap((raw) =>
193 Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
194 Effect.mapError((cause) =>
195 error(operation, cwd, "GitCafe returned an unreadable response.", cause),
196 ),
197 ),
198 ),
199 );
200 const cafe = (operation: string, cwd: string, target: Target, args: ReadonlyArray<string>) =>
201 credentials
202 .cliEnv(target.host)
203 .pipe(
204 Effect.flatMap((env) =>
205 host.process.run({
206 operation: `GitCafeSourceControlProvider.${operation}`,
207 command: "cafe",
208 cwd,
209 args: [...cliArgs(target.host), ...args],
210 env: { CAFE_OUTPUT: "json", ...env },
211 timeoutMs: 30_000,
212 }),
213 ),
214 )
215 .pipe(
216 Effect.mapError((cause) =>
217 error(
218 operation,
219 cwd,
220 (cause._tag === "VcsProcessExitError" && cliFailure(cause.detail)?.message) ||
221 "GitCafe CLI command failed.",
222 cause,
223 ),
224 ),
225 );
226​
227 const resolveTarget = Effect.fn("GitCafeSourceControlProvider.resolveTarget")(function* (
228 operation: string,
229 input: {
230 readonly cwd: string;
231 readonly context?: SourceControlProvider.SourceControlProviderContext;
232 readonly repository?: string;
233 },
234 ) {
235 const named =
236 input.repository === undefined ? null : GitCafeHosts.parseGitCafeRemote(input.repository);
237 if (named) return named;
238 const readRemote = host.git
239 .resolvePrimaryRemoteName(input.cwd)
240 .pipe(
241 Effect.flatMap((remote) => host.git.readConfigValue(input.cwd, `remote.${remote}.url`)),
242 );
243 const remoteUrl =
244 input.context?.remoteUrl ??
245 (input.repository === undefined
246 ? yield* readRemote.pipe(
247 Effect.mapError((cause) =>
248 error(operation, input.cwd, "Could not read the GitCafe remote.", cause),
249 ),
250 )
251 : yield* readRemote.pipe(Effect.orElseSucceed(() => null)));
252 const remote = remoteUrl ? GitCafeHosts.parseGitCafeRemote(remoteUrl) : null;
253 if (input.repository === undefined) {
254 if (remote) return remote;
255 return yield* error(operation, input.cwd, "No GitCafe repository remote was found.");
256 }
257 const repository = GitCafeHosts.gitCafeRepositoryPath(input.repository);
258 if (repository !== null)
259 return { host: remote?.host ?? AUTH_HOST, repository } satisfies Target;
260 return yield* error(
261 operation,
262 input.cwd,
263 "A GitCafe repository is named owner/name or by its git.cafe URL.",
264 );
265 });
266​
267 const getPull = Effect.fn("GitCafeSourceControlProvider.getPull")(function* (input: {
268 readonly cwd: string;
269 readonly context?: SourceControlProvider.SourceControlProviderContext;
270 readonly reference: string;
271 }) {
272 const match = pullUrlPattern.exec(input.reference.trim());
273 const urlHost = match?.[1] ? GitCafeHosts.gitCafeHost(match[1]) : null;
274 const target: Target =
275 urlHost && match?.[2]
276 ? { host: urlHost, repository: match[2] }
277 : yield* resolveTarget("getChangeRequest", input);
278 const number = match
279 ? urlHost
280 ? match[3]
281 : undefined
282 : /^#?([1-9]\d*)$/u.exec(input.reference.trim())?.[1];
283 if (number === undefined)
284 return yield* error(
285 "getChangeRequest",
286 input.cwd,
287 "A GitCafe pull request is a number or a git.cafe pull request URL.",
288 );
289 const pull = yield* read(
290 "getChangeRequest",
291 input.cwd,
292 { host: target.host, path: `/repos/${target.repository}/pulls/${number}` },
293 PullDetail,
294 );
295 const owner = target.repository.split("/")[0] ?? null;
296 return {
297 provider: SourceControlProviderKind.make("gitcafe"),
298 number: pull.number,
299 title: pull.title,
300 url: `https://${target.host}/${target.repository}/pulls/${pull.number}`,
301 baseRefName: pull.targetBranch,
302 headRefName: pull.sourceBranch,
303 ...(pull.headOid ? { headSha: pull.headOid } : {}),
304 state: pull.state,
305 ...(pull.draft ? { isDraft: true } : {}),
306 closedAt: pull.closedAt,
307 mergedAt: pull.mergedAt,
308 updatedAt: pull.updatedAt,
309 isCrossRepository: pull.sourceRepo !== null,
310 headRepositoryNameWithOwner: pull.sourceRepo
311 ? `${pull.sourceRepo.owner}/${pull.sourceRepo.name}`
312 : target.repository,
313 headRepositoryOwnerLogin: pull.sourceRepo?.owner ?? owner,
314 } satisfies ChangeRequest;
315 });
316​
317 return SourceControlProvider.SourceControlProvider.of({
318 kind: SourceControlProviderKind.make("gitcafe"),
319 repositoryNameFromRemoteUrl: (url) => GitCafeHosts.parseGitCafeRemote(url)?.repository ?? null,
320 getChangeRequest: getPull,
321 listChangeRequests: Effect.fn("GitCafeSourceControlProvider.listChangeRequests")(
322 function* (input) {
323 const target = yield* resolveTarget("listChangeRequests", input);
324 const source = SourceControlProvider.sourceControlRefFromInput(input);
325 const branch = SourceControlProvider.sourceBranch(input);
326 const limit = input.limit ?? 20;
327 const items: Array<ChangeRequest> = [];
328 let after: string | null = null;
329 do {
330 const query = new URLSearchParams({
331 sourceBranches: encodeBranches([branch]),
332 limit: String(Math.min(limit, 100)),
333 sort: "newest",
334 });
335 if (input.state !== "all") query.set("state", input.state);
336 if (after !== null) query.set("after", after);
337 const page: typeof Pulls.Type = yield* read(
338 "listChangeRequests",
339 input.cwd,
340 { host: target.host, path: `/repos/${target.repository}/pulls?${query}` },
341 Pulls,
342 );
343 for (const pull of page.items) {
344 if (pull.sourceBranch !== branch || items.length >= limit) continue;
345 // List rows omit fork identity, so only the branch's own rows are read in full.
346 const detail = yield* getPull({
347 cwd: input.cwd,
348 reference: `https://${target.host}/${target.repository}/pulls/${pull.number}`,
349 });
350 if (
351 (!source?.repository || detail.headRepositoryNameWithOwner === source.repository) &&
352 (!source?.owner || detail.headRepositoryOwnerLogin === source.owner)
353 )
354 items.push(detail);
355 }
356 after = page.items.length === 0 || page.next === after ? null : page.next;
357 } while (after !== null && items.length < limit);
358 return items;
359 },
360 ),
361 createChangeRequest: Effect.fn("GitCafeSourceControlProvider.createChangeRequest")(
362 function* (input) {
363 const target = yield* resolveTarget("createChangeRequest", {
364 ...input,
365 ...(input.target?.repository ? { repository: input.target.repository } : {}),
366 });
367 const source = SourceControlProvider.sourceControlRefFromInput(input);
368 const sourceRepository =
369 source?.repository ??
370 (source?.owner
371 ? `${source.owner}/${target.repository.split("/")[1]}`
372 : target.repository);
373 const branch = SourceControlProvider.sourceBranch(input);
374 yield* cafe("createChangeRequest", input.cwd, target, [
375 "pr",
376 "create",
377 "--json",
378 "--repo",
379 target.repository,
380 "--head",
381 sourceRepository === target.repository ? branch : `${sourceRepository}:${branch}`,
382 "--base",
383 input.target?.refName ?? input.baseRefName,
384 "--title",
385 input.title,
386 "--body-file",
387 input.bodyFile,
388 ]);
389 },
390 ),
391 getRepositoryCloneUrls: Effect.fn("GitCafeSourceControlProvider.getRepositoryCloneUrls")(
392 function* (input) {
393 const target = yield* resolveTarget("getRepositoryCloneUrls", input);
394 yield* read(
395 "getRepositoryCloneUrls",
396 input.cwd,
397 { host: target.host, path: `/repos/${target.repository}` },
398 Repository,
399 );
400 return cloneUrls(target);
401 },
402 ),
403 createRepository: Effect.fn("GitCafeSourceControlProvider.createRepository")(function* (input) {
404 const target = yield* resolveTarget("createRepository", input);
405 const [owner = "", name = ""] = target.repository.split("/");
406 const output = yield* cafe("createRepository", input.cwd, target, [
407 "repo",
408 "create",
409 name,
410 "--org",
411 owner,
412 "--visibility",
413 input.visibility,
414 "--json",
415 ]);
416 const created = yield* decodeCreatedRepository(output.stdout).pipe(
417 Effect.mapError((cause) =>
418 error("createRepository", input.cwd, "GitCafe returned an unreadable response.", cause),
419 ),
420 );
421 // GitCafe admits a repository asynchronously: `cafe repo create` answers while admission is
422 // still running, so wait for it to settle the way `cafe repo create --clone` does.
423 const settled = (state: string) => state === "complete" || state === "blocked";
424 const pending = created.data.resource;
425 const resource = settled(pending.state)
426 ? pending
427 : yield* read(
428 "createRepository",
429 input.cwd,
430 {
431 host: target.host,
432 path: `/orgs/${pending.owner}/admissions/${pending.repoId}`,
433 },
434 RepositoryAdmission,
435 ).pipe(
436 Effect.repeat({
437 until: (admission) => settled(admission.state),
438 schedule: Schedule.spaced(ADMISSION_POLL_INTERVAL),
439 }),
440 Effect.timeoutOption(ADMISSION_TIMEOUT),
441 Effect.map(Option.getOrElse(() => pending)),
442 );
443 if (resource.state !== "complete")
444 return yield* error(
445 "createRepository",
446 input.cwd,
447 `GitCafe repository ${target.repository} is ${resource.state}. Check it on GitCafe before retrying.`,
448 );
449 return cloneUrls({ host: target.host, repository: `${resource.owner}/${resource.name}` });
450 }),
451 getDefaultBranch: Effect.fn("GitCafeSourceControlProvider.getDefaultBranch")(function* (input) {
452 const target = yield* resolveTarget("getDefaultBranch", input);
453 const repository = yield* read(
454 "getDefaultBranch",
455 input.cwd,
456 { host: target.host, path: `/repos/${target.repository}` },
457 Repository,
458 );
459 return repository.defaultBranch;
460 }),
461 // `cafe` has no forced checkout, so the branch is fetched and switched to with git.
462 checkoutChangeRequest: Effect.fn("GitCafeSourceControlProvider.checkoutChangeRequest")(
463 function* (input) {
464 const pull = yield* getPull(input);
465 const pullHost = new URL(pull.url).host;
466 const sourceRepository = pull.headRepositoryNameWithOwner;
467 if (!sourceRepository)
468 return yield* error(
469 "checkoutChangeRequest",
470 input.cwd,
471 "GitCafe did not name the pull request's source repository.",
472 );
473 const contextRemote = input.context
474 ? GitCafeHosts.parseGitCafeRemote(input.context.remoteUrl)
475 : null;
476 const git = host.git;
477 yield* Effect.gen(function* () {
478 const remoteName =
479 input.context &&
480 contextRemote?.repository === sourceRepository &&
481 contextRemote.host === pullHost
482 ? input.context.remoteName
483 : yield* git.ensureRemote({
484 cwd: input.cwd,
485 preferredName: "gitcafe",
486 url: isSshRemote(input.context?.remoteUrl)
487 ? `ssh@${pullHost}:${sourceRepository}.git`
488 : `https://${pullHost}/${sourceRepository}.git`,
489 });
490 const localBranch = pull.isCrossRepository
491 ? `pr-${pull.number}/${pull.headRefName}`
492 : pull.headRefName;
493 const branches = yield* git.listLocalBranchNames(input.cwd);
494 const remoteBranch = { cwd: input.cwd, remoteName, remoteBranch: pull.headRefName };
495 if (input.force !== true && !branches.includes(localBranch))
496 yield* git.fetchRemoteBranch({ ...remoteBranch, localBranch });
497 else yield* git.fetchRemoteTrackingBranch(remoteBranch);
498 if (input.force === true)
499 yield* git.execute({
500 operation: "GitCafeSourceControlProvider.checkoutChangeRequest",
501 cwd: input.cwd,
502 args: [
503 "checkout",
504 "-B",
505 localBranch,
506 `refs/remotes/${remoteName}/${pull.headRefName}`,
507 "--",
508 ],
509 });
510 yield* git.setBranchUpstream({ ...remoteBranch, branch: localBranch });
511 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
512 }).pipe(
513 Effect.mapError((cause) =>
514 error(
515 "checkoutChangeRequest",
516 input.cwd,
517 "Could not check out the GitCafe pull request.",
518 cause,
519 ),
520 ),
521 );
522 },
523 ),
524 });
525});