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

SourceControlRepositoryService.test.ts

467 lines15.6 KB

1import * as NodePath from "@effect/platform-node/NodePath";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, it } from "@effect/vitest";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as PlatformError from "effect/PlatformError";
8import { ChildProcessSpawner } from "effect/unstable/process";
9​
10import { GitCommandError, SourceControlProviderError } from "@t3tools/contracts";
11​
12import * as ServerConfig from "../config.ts";
13import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
14import type * as SourceControlProvider from "./SourceControlProvider.ts";
15import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
16import * as SourceControlRepositoryService from "./SourceControlRepositoryService.ts";
17​
18const CLONE_URLS = {
19 nameWithOwner: "octocat/t3code",
20 url: "https://github.com/octocat/t3code",
21 sshUrl: "git@github.com:octocat/t3code.git",
22};
23​
24function makeProvider(
25 overrides: Partial<SourceControlProvider.SourceControlProvider["Service"]> = {},
26): SourceControlProvider.SourceControlProvider["Service"] {
27 const unsupported = (operation: string) =>
28 Effect.die(`unexpected provider operation ${operation}`) as Effect.Effect<
29 never,
30 SourceControlProviderError
31 >;
32​
33 return {
34 kind: "github",
35 listChangeRequests: () => unsupported("listChangeRequests"),
36 getChangeRequest: () => unsupported("getChangeRequest"),
37 createChangeRequest: () => unsupported("createChangeRequest"),
38 getRepositoryCloneUrls: () => Effect.succeed(CLONE_URLS),
39 createRepository: () => Effect.succeed(CLONE_URLS),
40 getDefaultBranch: () => Effect.succeed(null),
41 checkoutChangeRequest: () => unsupported("checkoutChangeRequest"),
42 ...overrides,
43 };
45​
46function processOutput(): GitVcsDriver.ExecuteGitResult {
47 return {
48 exitCode: ChildProcessSpawner.ExitCode(0),
49 stdout: "",
50 stderr: "",
51 stdoutTruncated: false,
52 stderrTruncated: false,
53 };
55​
56function makeLayer(input: {
57 readonly provider?: SourceControlProvider.SourceControlProvider["Service"];
58 readonly git?: Partial<GitVcsDriver.GitVcsDriver["Service"]>;
59 readonly fileSystem?: FileSystem.FileSystem;
60}) {
61 const serviceLayer = SourceControlRepositoryService.layer.pipe(
62 Layer.provide(
63 Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({
64 get: () => Effect.succeed(input.provider ?? makeProvider()),
65 }),
66 ),
67 Layer.provide(
68 Layer.mock(GitVcsDriver.GitVcsDriver)({
69 execute: () => Effect.succeed(processOutput()),
70 ensureRemote: () => Effect.succeed("origin"),
71 pushCurrentBranch: () =>
72 Effect.succeed({
73 status: "pushed" as const,
74 branch: "feature/remote-v1",
75 upstreamBranch: "origin/feature/remote-v1",
76 setUpstream: true,
77 }),
78 ...input.git,
79 }),
80 ),
81 Layer.provide(
82 ServerConfig.layerTest(
83 process.cwd(),
84 input.fileSystem ? "/tmp/t3-source-control-repos" : { prefix: "t3-source-control-repos-" },
85 ),
86 ),
87 );
88​
89 return input.fileSystem
90 ? serviceLayer.pipe(
91 Layer.provide(Layer.succeed(FileSystem.FileSystem, input.fileSystem)),
92 Layer.provideMerge(NodePath.layer),
93 )
94 : serviceLayer.pipe(Layer.provideMerge(NodeServices.layer));
96​
97it.effect("looks up repositories through the requested provider without search", () => {
98 const calls: Array<{ cwd: string; repository: string }> = [];
99 const provider = makeProvider({
100 getRepositoryCloneUrls: (input) =>
101 Effect.sync(() => {
102 calls.push({ cwd: input.cwd, repository: input.repository });
103 return CLONE_URLS;
104 }),
105 });
106​
107 return Effect.gen(function* () {
108 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
109 const result = yield* service.lookupRepository({
110 provider: "github",
111 repository: "octocat/t3code",
112 cwd: "/workspace",
113 });
114​
115 assert.deepStrictEqual(result, { provider: "github", ...CLONE_URLS });
116 assert.deepStrictEqual(calls, [{ cwd: "/workspace", repository: "octocat/t3code" }]);
117 }).pipe(Effect.provide(makeLayer({ provider })));
118});
119​
120it.effect("preserves provider failures without deriving the repository message from them", () => {
121 const providerCause = new SourceControlProviderError({
122 provider: "github",
123 operation: "getRepositoryCloneUrls",
124 cwd: "/workspace",
125 repository: "octocat/t3code",
126 detail: "credential token abc123 was rejected",
127 });
128 const provider = makeProvider({
129 getRepositoryCloneUrls: () => Effect.fail(providerCause),
130 });
131​
132 return Effect.gen(function* () {
133 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
134 const error = yield* Effect.flip(
135 service.lookupRepository({
136 provider: "github",
137 repository: "octocat/t3code",
138 cwd: "/workspace",
139 }),
140 );
141​
142 assert.strictEqual(error.provider, "github");
143 assert.strictEqual(error.operation, "lookupRepository");
144 assert.strictEqual(error.detail, "The source control operation could not be completed.");
145 assert.strictEqual(
146 error.message,
147 "Source control repository operation lookupRepository failed for github: The source control operation could not be completed.",
148 );
149 assert.strictEqual(error.cause, providerCause);
150 }).pipe(Effect.provide(makeLayer({ provider })));
151});
152​
153it.effect("clones a looked-up repository into the requested destination", () =>
154 Effect.gen(function* () {
155 const fs = yield* FileSystem.FileSystem;
156 const parent = yield* fs.makeTempDirectoryScoped({
157 prefix: "t3-source-control-clone-parent-",
158 });
159 const destinationPath = `${parent}/t3code`;
160 const cloneCalls: Array<{ cwd: string; args: ReadonlyArray<string> }> = [];
161​
162 yield* Effect.gen(function* () {
163 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
164 const result = yield* service.cloneRepository({
165 provider: "github",
166 repository: "octocat/t3code",
167 destinationPath,
168 protocol: "https",
169 });
170​
171 assert.deepStrictEqual(result, {
172 cwd: destinationPath,
173 remoteUrl: CLONE_URLS.url,
174 repository: { provider: "github", ...CLONE_URLS },
175 });
176 assert.deepStrictEqual(cloneCalls, [
177 {
178 cwd: parent,
179 args: ["clone", CLONE_URLS.url, "t3code"],
180 },
181 ]);
182 }).pipe(
183 Effect.provide(
184 makeLayer({
185 git: {
186 execute: (input) =>
187 Effect.sync(() => {
188 cloneCalls.push({ cwd: input.cwd, args: input.args });
189 return processOutput();
190 }),
191 },
192 }),
193 ),
194 );
195 }).pipe(Effect.provide(NodeServices.layer)),
196);
197​
198it.effect("returns actionable, transport-safe clone failures", () => {
199 const cases = [
200 {
201 stderr: "Host key verification failed.\nfatal: Could not read from remote repository.\n",
202 expected:
203 "SSH could not verify the source control host. Add its host key to known_hosts and try again.",
204 },
205 {
206 stderr: "git@example.com: Permission denied (publickey).\n",
207 expected:
208 "SSH authentication failed. Add an SSH key to your source control account and try again.",
209 },
210 {
211 stderr:
212 "fatal: could not read Username for 'https://example.com': terminal prompts disabled\n",
213 expected:
214 "HTTPS authentication failed. Configure Git credentials for the source control host and try again.",
215 },
216 {
217 stderr:
218 "ssh: Could not resolve hostname example.com: nodename nor servname provided\nfatal: Could not read from remote repository.\n",
219 expected:
220 "The source control host could not be resolved. Check your network or VPN connection and try again.",
221 },
222 {
223 stderr: "fatal: an unrecognized clone failure\n",
224 expected:
225 "Git could not clone the repository. Verify that the remote works in a terminal and try again.",
226 },
227 ] as const;
228​
229 return Effect.forEach(cases, ({ stderr, expected }) =>
230 Effect.gen(function* () {
231 const fs = yield* FileSystem.FileSystem;
232 const parent = yield* fs.makeTempDirectoryScoped({
233 prefix: "t3-source-control-clone-failure-",
234 });
235 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
236 const error = yield* Effect.flip(
237 service.cloneRepository({
238 remoteUrl: CLONE_URLS.sshUrl,
239 destinationPath: `${parent}/t3code`,
240 }),
241 );
242​
243 assert.strictEqual(error.operation, "cloneRepository");
244 assert.strictEqual(error.provider, "github");
245 assert.strictEqual(error.detail, expected);
246 assert.instanceOf(error.cause, GitCommandError);
247 assert.strictEqual(error.cause.detail, expected);
248 assert.strictEqual(error.cause.stderrLength, stderr.length);
249 }).pipe(
250 Effect.provide(
251 makeLayer({
252 git: {
253 execute: () =>
254 Effect.succeed({
255 ...processOutput(),
256 exitCode: ChildProcessSpawner.ExitCode(128),
257 stderr,
258 }),
259 },
260 }),
261 ),
262 ),
263 ).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
264});
265​
266it.effect("preserves destination probe failures instead of treating them as missing paths", () => {
267 const fileSystemCause = PlatformError.systemError({
268 _tag: "PermissionDenied",
269 module: "FileSystem",
270 method: "exists",
271 pathOrDescriptor: "/restricted/t3code",
272 });
273​
274 return Effect.gen(function* () {
275 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
276 const error = yield* Effect.flip(
277 service.cloneRepository({
278 remoteUrl: CLONE_URLS.sshUrl,
279 destinationPath: "/restricted/t3code",
280 }),
281 );
282​
283 assert.strictEqual(error.provider, "unknown");
284 assert.strictEqual(error.operation, "cloneRepository");
285 assert.strictEqual(error.cause, fileSystemCause);
286 }).pipe(
287 Effect.provide(
288 makeLayer({
289 fileSystem: FileSystem.makeNoop({
290 exists: () => Effect.fail(fileSystemCause),
291 makeDirectory: () => Effect.void,
292 }),
293 }),
294 ),
295 );
296});
297​
298it.effect("publishes by creating the repository, adding a remote, and pushing upstream", () => {
299 const createCalls: Array<{ cwd: string; repository: string; visibility: string }> = [];
300 const remoteCalls: Array<{ cwd: string; preferredName: string; url: string }> = [];
301 const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
302 const provider = makeProvider({
303 createRepository: (input) =>
304 Effect.sync(() => {
305 createCalls.push({
306 cwd: input.cwd,
307 repository: input.repository,
308 visibility: input.visibility,
309 });
310 return CLONE_URLS;
311 }),
312 });
313​
314 return Effect.gen(function* () {
315 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
316 const result = yield* service.publishRepository({
317 cwd: "/workspace",
318 provider: "github",
319 repository: "octocat/t3code",
320 visibility: "private",
321 remoteName: "origin",
322 protocol: "ssh",
323 });
324​
325 assert.deepStrictEqual(result, {
326 repository: { provider: "github", ...CLONE_URLS },
327 remoteName: "origin",
328 remoteUrl: CLONE_URLS.sshUrl,
329 branch: "feature/remote-v1",
330 upstreamBranch: "origin/feature/remote-v1",
331 status: "pushed",
332 });
333 assert.deepStrictEqual(createCalls, [
334 { cwd: "/workspace", repository: "octocat/t3code", visibility: "private" },
335 ]);
336 assert.deepStrictEqual(remoteCalls, [
337 { cwd: "/workspace", preferredName: "origin", url: CLONE_URLS.sshUrl },
338 ]);
339 assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin" }]);
340 }).pipe(
341 Effect.provide(
342 makeLayer({
343 provider,
344 git: {
345 ensureRemote: (input) =>
346 Effect.sync(() => {
347 remoteCalls.push(input);
348 return "origin";
349 }),
350 pushCurrentBranch: (cwd, _fallbackBranch, options) =>
351 Effect.sync(() => {
352 pushCalls.push({ cwd, remoteName: options?.remoteName });
353 return {
354 status: "pushed" as const,
355 branch: "feature/remote-v1",
356 upstreamBranch: "origin/feature/remote-v1",
357 setUpstream: true,
358 };
359 }),
360 },
361 }),
362 ),
363 );
364});
365​
366it.effect("publishes to the remote name returned by ensureRemote", () => {
367 const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
368​
369 return Effect.gen(function* () {
370 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
371 const result = yield* service.publishRepository({
372 cwd: "/workspace",
373 provider: "github",
374 repository: "octocat/t3code",
375 visibility: "private",
376 remoteName: "origin",
377 protocol: "ssh",
378 });
379​
380 assert.equal(result.remoteName, "origin-1");
381 assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin-1" }]);
382 }).pipe(
383 Effect.provide(
384 makeLayer({
385 git: {
386 ensureRemote: () => Effect.succeed("origin-1"),
387 pushCurrentBranch: (cwd, _fallbackBranch, options) =>
388 Effect.sync(() => {
389 pushCalls.push({ cwd, remoteName: options?.remoteName });
390 return {
391 status: "pushed" as const,
392 branch: "feature/remote-v1",
393 upstreamBranch: `${options?.remoteName ?? "missing"}/feature/remote-v1`,
394 setUpstream: true,
395 };
396 }),
397 },
398 }),
399 ),
400 );
401});
402​
403it.effect("publish succeeds with status remote_added when the local repo has no commits", () => {
404 let pushCalls = 0;
405 return Effect.gen(function* () {
406 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
407 const result = yield* service.publishRepository({
408 cwd: "/workspace",
409 provider: "github",
410 repository: "octocat/t3code",
411 visibility: "private",
412 remoteName: "origin",
413 protocol: "ssh",
414 });
415​
416 assert.deepStrictEqual(result, {
417 repository: { provider: "github", ...CLONE_URLS },
418 remoteName: "origin",
419 remoteUrl: CLONE_URLS.sshUrl,
420 branch: "main",
421 status: "remote_added",
422 });
423 assert.strictEqual(pushCalls, 0);
424 }).pipe(
425 Effect.provide(
426 makeLayer({
427 git: {
428 execute: (input) =>
429 input.args[0] === "rev-parse"
430 ? Effect.fail(
431 new GitCommandError({
432 operation: input.operation,
433 command: "git rev-parse --verify HEAD",
434 cwd: input.cwd,
435 detail: "fatal: Needed a single revision",
436 }),
437 )
438 : Effect.succeed(processOutput()),
439 statusDetails: () =>
440 Effect.succeed({
441 isRepo: true,
442 hasOriginRemote: true,
443 isDefaultBranch: true,
444 branch: "main",
445 upstreamRef: null,
446 hasWorkingTreeChanges: false,
447 workingTree: { files: [], insertions: 0, deletions: 0 },
448 hasUpstream: false,
449 aheadCount: 0,
450 behindCount: 0,
451 aheadOfDefaultCount: 0,
452 }),
453 pushCurrentBranch: () =>
454 Effect.sync(() => {
455 pushCalls += 1;
456 return {
457 status: "pushed" as const,
458 branch: "main",
459 upstreamBranch: "origin/main",
460 setUpstream: true,
461 };
462 }),
463 },
464 }),
465 ),
466 );
467});