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