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

GitCafeSourceControlProvider.ts

519 lines19.4 KB

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