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

SourceControlRepositoryService.test.ts

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