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

GitCafeSourceControlProvider.ts

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