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

GitCafeSourceControlProvider.ts

503 lines19.2 KB

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