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

GitCafeSourceControlProvider.ts

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