Open History to see the last commit
1/**
2 * Pins `./GitCafeSourceControlProvider.ts`, which pass 2 creates:
3 *
4 * - `discovery: SourceControlCliDiscoverySpec` — kind `"gitcafe"`, executable `"cafe"`,
5 * `authArgs` ending in `["auth", "status", "--json"]` against `https://git.cafe/api`, and a
6 * `parseAuth` that reads cafe's `{ schemaVersion: 1, data: { host, username } }` answer and its
7 * `{ schemaVersion: 1, error: { code, status, message } }` failure envelope.
8 * - `make: Effect<SourceControlProvider["Service"], never, GitCafeApi | SourceControlHost>` with
9 * kind `"gitcafe"`, resolving the repository and host from the checkout's remote.
10 *
11 * Uses `./GitCafeApi.ts` and `./GitCafeCredentials.ts` as pinned in the sibling tests.
12 */
13import { assert, describe, it } from "@effect/vitest";
14import { GitCommandError } from "@t3tools/contracts";
15import * as Effect from "effect/Effect";
16import * as Fiber from "effect/Fiber";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Schema from "effect/Schema";
20import * as TestClock from "effect/testing/TestClock";
21import * as HttpClient from "effect/http/HttpClient";
22import * as HttpClientResponse from "effect/http/HttpClientResponse";
23import { ChildProcessSpawner } from "effect/process";
24import * as HostProcess from "@t3tools/shared/HostProcess";
25import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
26
27import * as GitCafeApi from "./GitCafeApi.ts";
28import * as GitCafeCredentials from "./GitCafeCredentials.ts";
29import * as GitCafeSourceControlProvider from "./GitCafeSourceControlProvider.ts";
30
31const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
32
33const authAnswer = (input: { stdout?: unknown; stderr?: unknown; exitCode?: number }) => ({
34 stdout: input.stdout === undefined ? "" : encodeJson(input.stdout),
35 stderr: input.stderr === undefined ? "" : encodeJson(input.stderr),
36 exitCode: ChildProcessSpawner.ExitCode(input.exitCode ?? 0),
37});
38const failure = (code: string, status: number | null) => ({
39 schemaVersion: 1,
40 error: { code, status, message: `Failure ${code}` },
41});
42
43describe("GitCafeSourceControlProvider", () => {
44 it("probes the cafe CLI against production", () => {
45 const { discovery } = GitCafeSourceControlProvider;
46 assert.strictEqual(discovery.kind, "gitcafe");
47 assert.strictEqual(discovery.executable, "cafe");
48 assert.deepStrictEqual(discovery.authArgs.slice(0, 2), ["--host", "https://git.cafe/api"]);
49 assert.deepStrictEqual(discovery.authArgs.slice(-3), ["auth", "status", "--json"]);
50 });
51
52 it("reads a signed-in account and keeps transient failures apart from sign-out", () => {
53 const { parseAuth } = GitCafeSourceControlProvider.discovery;
54 const signedIn = parseAuth(
55 authAnswer({ stdout: { schemaVersion: 1, data: { host: "git.cafe", username: "alice" } } }),
56 );
57 assert.strictEqual(signedIn.status, "authenticated");
58 assert.deepStrictEqual(signedIn.account, Option.some("alice"));
59 assert.strictEqual(
60 parseAuth(authAnswer({ stderr: failure("AUTHENTICATION_REQUIRED", 401), exitCode: 1 }))
61 .status,
62 "unauthenticated",
63 );
64 for (const [code, status] of [
65 ["FORBIDDEN", 403],
66 ["NETWORK_ERROR", null],
67 ] as const) {
68 assert.strictEqual(
69 parseAuth(authAnswer({ stderr: failure(code, status), exitCode: 1 })).status,
70 "unknown",
71 );
72 }
73 });
74
75 it.effect.each([
76 ["https://staging.git.cafe/team/project.git", "staging.git.cafe"],
77 ["ssh@git.cafe:team/project.git", "git.cafe"],
78 ] as const)("resolves the repository from the remote %s", ([remoteUrl, host]) => {
79 const urls: Array<string> = [];
80 const client = HttpClient.make((request) => {
81 urls.push(request.url);
82 return Effect.succeed(
83 HttpClientResponse.fromWeb(
84 request,
85 new Response(encodeJson({ name: "project", defaultBranch: "trunk" })),
86 ),
87 );
88 });
89 const context = {
90 provider: { kind: "gitcafe" as const, name: "GitCafe", baseUrl: `https://${host}` },
91 remoteName: "origin",
92 remoteUrl,
93 };
94 return Effect.gen(function* () {
95 const provider = yield* GitCafeSourceControlProvider.make;
96 assert.strictEqual(provider.kind, "gitcafe");
97 assert.strictEqual(yield* provider.getDefaultBranch({ cwd: "/repo", context }), "trunk");
98 assert.deepStrictEqual(
99 yield* provider.getRepositoryCloneUrls({ cwd: "/repo", context, repository: remoteUrl }),
100 {
101 nameWithOwner: "team/project",
102 url: `https://${host}/team/project`,
103 sshUrl: `ssh@${host}:team/project.git`,
104 },
105 );
106 assert.deepStrictEqual(urls, [
107 `https://${host}/api/repos/team/project`,
108 `https://${host}/api/repos/team/project`,
109 ]);
110 }).pipe(
111 Effect.provide(
112 GitCafeApi.layer.pipe(
113 Layer.provide(GitCafeCredentials.layer),
114 Layer.provideMerge(TestSourceControlHost.layer()),
115 Layer.provide(
116 Layer.succeed(HostProcess.Environment, { CAFE_TOKEN: "env-token", CAFE_HOST: host }),
117 ),
118 Layer.provide(Layer.succeed(HostProcess.WorkingDirectory, "/server")),
119 Layer.provide(Layer.succeed(HttpClient.HttpClient, client)),
120 ),
121 ),
122 );
123 });
124
125 it.effect(
126 "reads a bare owner/name on git.cafe without a remote, and no other host's pulls",
127 () => {
128 const urls: Array<string> = [];
129 const client = HttpClient.make((request) => {
130 urls.push(request.url);
131 return Effect.succeed(
132 HttpClientResponse.fromWeb(
133 request,
134 new Response(encodeJson({ name: "project", defaultBranch: "trunk" })),
135 ),
136 );
137 });
138 return Effect.gen(function* () {
139 const provider = yield* GitCafeSourceControlProvider.make;
140 // The checkout has no remote at all, as when a repository is about to be created.
141 assert.deepStrictEqual(
142 yield* provider.getRepositoryCloneUrls({ cwd: "/repo", repository: "team/project" }),
143 {
144 nameWithOwner: "team/project",
145 url: "https://git.cafe/team/project",
146 sshUrl: "ssh@git.cafe:team/project.git",
147 },
148 );
149 const foreign = yield* provider
150 .getChangeRequest({
151 cwd: "/repo",
152 reference: "https://example.com/team/project/pulls/42",
153 })
154 .pipe(Effect.flip);
155 assert.strictEqual(foreign._tag, "SourceControlProviderError");
156 assert.deepStrictEqual(urls, ["https://git.cafe/api/repos/team/project"]);
157 }).pipe(
158 Effect.provide(
159 GitCafeApi.layer.pipe(
160 Layer.provide(GitCafeCredentials.layer),
161 Layer.provideMerge(
162 TestSourceControlHost.layer({
163 git: {
164 resolvePrimaryRemoteName: () =>
165 Effect.fail(
166 new GitCommandError({
167 operation: "resolvePrimaryRemoteName",
168 command: "git remote",
169 cwd: "/repo",
170 detail: "No git remote is configured.",
171 }),
172 ),
173 },
174 }),
175 ),
176 Layer.provide(Layer.succeed(HostProcess.Environment, { CAFE_TOKEN: "env-token" })),
177 Layer.provide(Layer.succeed(HostProcess.WorkingDirectory, "/server")),
178 Layer.provide(Layer.succeed(HttpClient.HttpClient, client)),
179 ),
180 ),
181 );
182 },
183 );
184
185 it.effect.each([
186 ["no context", undefined, "https://git.cafe/fork/project.git"],
187 ["an HTTPS remote", "https://git.cafe/team/project.git", "https://git.cafe/fork/project.git"],
188 ["an SSH remote", "ssh@git.cafe:team/project.git", "ssh@git.cafe:fork/project.git"],
189 ["an ssh:// remote", "ssh://ssh@git.cafe/team/project.git", "ssh@git.cafe:fork/project.git"],
190 [
191 "an HTTPS remote with a user",
192 "https://alice@git.cafe/team/project.git",
193 "https://git.cafe/fork/project.git",
194 ],
195 ] as const)("checks a fork out over the transport of %s", ([, remoteUrl, expected]) => {
196 const remotes: Array<string> = [];
197 const client = HttpClient.make((request) =>
198 Effect.succeed(
199 HttpClientResponse.fromWeb(
200 request,
201 new Response(
202 encodeJson({
203 number: 7,
204 title: "Change",
205 state: "open",
206 draft: false,
207 sourceBranch: "feature",
208 targetBranch: "main",
209 headOid: null,
210 updatedAt: null,
211 sourceRepo: { owner: "fork", name: "project" },
212 closedAt: null,
213 mergedAt: null,
214 }),
215 ),
216 ),
217 ),
218 );
219 const context =
220 remoteUrl === undefined
221 ? undefined
222 : {
223 provider: { kind: "gitcafe" as const, name: "GitCafe", baseUrl: "https://git.cafe" },
224 remoteName: "origin",
225 remoteUrl,
226 };
227 return Effect.gen(function* () {
228 const provider = yield* GitCafeSourceControlProvider.make;
229 yield* provider.checkoutChangeRequest({
230 cwd: "/repo",
231 reference: "https://git.cafe/team/project/pulls/7",
232 ...(context === undefined ? {} : { context }),
233 });
234 assert.deepStrictEqual(remotes, [expected]);
235 }).pipe(
236 Effect.provide(
237 GitCafeApi.layer.pipe(
238 Layer.provide(GitCafeCredentials.layer),
239 Layer.provideMerge(
240 TestSourceControlHost.layer({
241 git: {
242 ensureRemote: (input) => {
243 remotes.push(input.url);
244 return Effect.succeed("gitcafe");
245 },
246 listLocalBranchNames: () => Effect.succeed([]),
247 fetchRemoteBranch: () => Effect.void,
248 setBranchUpstream: () => Effect.void,
249 switchRef: () => Effect.succeed({ refName: null }),
250 },
251 }),
252 ),
253 Layer.provide(Layer.succeed(HostProcess.Environment, { CAFE_TOKEN: "env-token" })),
254 Layer.provide(Layer.succeed(HostProcess.WorkingDirectory, "/server")),
255 Layer.provide(Layer.succeed(HttpClient.HttpClient, client)),
256 ),
257 ),
258 );
259 });
260
261 it.effect("waits for a created repository's admission before handing out its URLs", () => {
262 const urls: Array<string> = [];
263 const states = ["running", "complete"];
264 const client = HttpClient.make((request) => {
265 urls.push(request.url);
266 return Effect.succeed(
267 HttpClientResponse.fromWeb(
268 request,
269 new Response(
270 encodeJson({
271 repoId: "repo_1",
272 state: states.shift(),
273 owner: "team",
274 name: "project",
275 }),
276 ),
277 ),
278 );
279 });
280 return Effect.gen(function* () {
281 const provider = yield* GitCafeSourceControlProvider.make;
282 const created = yield* provider
283 .createRepository({ cwd: "/repo", repository: "team/project", visibility: "private" })
284 .pipe(Effect.forkChild);
285 yield* TestClock.adjust("1 second");
286 assert.deepStrictEqual(yield* Fiber.join(created), {
287 nameWithOwner: "team/project",
288 url: "https://git.cafe/team/project",
289 sshUrl: "ssh@git.cafe:team/project.git",
290 });
291 assert.deepStrictEqual(urls, [
292 "https://git.cafe/api/orgs/team/admissions/repo_1",
293 "https://git.cafe/api/orgs/team/admissions/repo_1",
294 ]);
295 }).pipe(
296 Effect.provide(
297 GitCafeApi.layer.pipe(
298 Layer.provide(GitCafeCredentials.layer),
299 Layer.provideMerge(
300 TestSourceControlHost.layer({
301 process: {
302 run: () =>
303 Effect.succeed(
304 TestSourceControlHost.processOutput(
305 encodeJson({
306 schemaVersion: 1,
307 data: {
308 resource: {
309 repoId: "repo_1",
310 state: "running",
311 owner: "team",
312 name: "project",
313 },
314 },
315 }),
316 ),
317 ),
318 },
319 git: {
320 resolvePrimaryRemoteName: () =>
321 Effect.fail(
322 new GitCommandError({
323 operation: "resolvePrimaryRemoteName",
324 command: "git remote",
325 cwd: "/repo",
326 detail: "No git remote is configured.",
327 }),
328 ),
329 },
330 }),
331 ),
332 Layer.provide(Layer.succeed(HostProcess.Environment, { CAFE_TOKEN: "env-token" })),
333 Layer.provide(Layer.succeed(HostProcess.WorkingDirectory, "/server")),
334 Layer.provide(Layer.succeed(HttpClient.HttpClient, client)),
335 ),
336 ),
337 );
338 });
339});