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

SourceControlRepositoryService.test.ts

550 lines19.7 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 resolveLink: () => undefined,
66 get: () => Effect.succeed(input.provider ?? makeProvider()),
67 }),
68 ),
69 Layer.provide(
70 Layer.mock(GitVcsDriver.GitVcsDriver)({
71 execute: () => Effect.succeed(processOutput()),
72 ensureRemote: () => Effect.succeed("origin"),
73 pushCurrentBranch: () =>
74 Effect.succeed({
75 status: "pushed" as const,
76 branch: "feature/remote-v1",
77 upstreamBranch: "origin/feature/remote-v1",
78 setUpstream: true,
79 }),
80 ...input.git,
81 }),
82 ),
83 Layer.provide(
84 ServerConfig.layerTest(
85 process.cwd(),
86 input.fileSystem ? "/tmp/t3-source-control-repos" : { prefix: "t3-source-control-repos-" },
87 ),
88 ),
89 );
90​
91 return input.fileSystem
92 ? serviceLayer.pipe(
93 Layer.provide(Layer.succeed(FileSystem.FileSystem, input.fileSystem)),
94 Layer.provideMerge(NodePath.layer),
95 )
96 : serviceLayer.pipe(Layer.provideMerge(NodeServices.layer));
98​
99it.effect("looks up repositories through the requested provider without search", () => {
100 const calls: Array<{ cwd: string; repository: string }> = [];
101 const provider = makeProvider({
102 getRepositoryCloneUrls: (input) =>
103 Effect.sync(() => {
104 calls.push({ cwd: input.cwd, repository: input.repository });
105 return CLONE_URLS;
106 }),
107 });
108​
109 return Effect.gen(function* () {
110 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
111 const result = yield* service.lookupRepository({
112 provider: "github",
113 repository: "octocat/t3code",
114 cwd: "/workspace",
115 });
116​
117 assert.deepStrictEqual(result, { provider: "github", ...CLONE_URLS });
118 assert.deepStrictEqual(calls, [{ cwd: "/workspace", repository: "octocat/t3code" }]);
119 }).pipe(Effect.provide(makeLayer({ provider })));
120});
121​
122it.effect("preserves provider failures without deriving the repository message from them", () => {
123 const providerCause = new SourceControlProviderError({
124 provider: "github",
125 operation: "getRepositoryCloneUrls",
126 cwd: "/workspace",
127 repository: "octocat/t3code",
128 detail: "credential token abc123 was rejected",
129 });
130 const provider = makeProvider({
131 getRepositoryCloneUrls: () => Effect.fail(providerCause),
132 });
133​
134 return Effect.gen(function* () {
135 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
136 const error = yield* Effect.flip(
137 service.lookupRepository({
138 provider: "github",
139 repository: "octocat/t3code",
140 cwd: "/workspace",
141 }),
142 );
143​
144 assert.strictEqual(error.provider, "github");
145 assert.strictEqual(error.operation, "lookupRepository");
146 assert.strictEqual(error.detail, "The source control operation could not be completed.");
147 assert.strictEqual(
148 error.message,
149 "Source control repository operation lookupRepository failed for github: The source control operation could not be completed.",
150 );
151 assert.strictEqual(error.cause, providerCause);
152 }).pipe(Effect.provide(makeLayer({ provider })));
153});
154​
155it.effect("clones a looked-up repository into the requested destination", () =>
156 Effect.gen(function* () {
157 const fs = yield* FileSystem.FileSystem;
158 const path = yield* Path.Path;
159 const parent = yield* fs.makeTempDirectoryScoped({
160 prefix: "t3-source-control-clone-parent-",
161 });
162 const destinationPath = path.join(parent, "t3code");
163 const cloneCalls: Array<{ cwd: string; args: ReadonlyArray<string> }> = [];
164​
165 yield* Effect.gen(function* () {
166 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
167 const result = yield* service.cloneRepository({
168 provider: "github",
169 repository: "octocat/t3code",
170 destinationPath,
171 protocol: "https",
172 });
173​
174 assert.deepStrictEqual(result, {
175 cwd: destinationPath,
176 remoteUrl: CLONE_URLS.url,
177 repository: { provider: "github", ...CLONE_URLS },
178 });
179 assert.deepStrictEqual(cloneCalls, [
180 {
181 cwd: parent,
182 args: ["clone", "--progress", CLONE_URLS.url, "t3code"],
183 },
184 ]);
185 }).pipe(
186 Effect.provide(
187 makeLayer({
188 git: {
189 execute: (input) =>
190 Effect.sync(() => {
191 cloneCalls.push({ cwd: input.cwd, args: input.args });
192 return processOutput();
193 }),
194 },
195 }),
196 ),
197 );
198 }).pipe(Effect.provide(NodeServices.layer)),
199);
200​
201it.effect("reports clone progress from git's stderr and keeps its error text on failure", () =>
202 Effect.gen(function* () {
203 const fs = yield* FileSystem.FileSystem;
204 const path = yield* Path.Path;
205 const parent = yield* fs.makeTempDirectoryScoped({
206 prefix: "t3-source-control-clone-progress-",
207 });
208 const destinationPath = path.join(parent, "t3code");
209 const progress: Array<{ stage: string; percent: number | null; detail: string | null }> = [];
210​
211 const stderrLines = [
212 "Cloning into 't3code'...",
213 "remote: Enumerating objects: 10, done.",
214 "Receiving objects: 40% (4/10), 1.00 MiB | 2.00 MiB/s",
215 "Receiving objects: 100% (10/10), 2.50 MiB | 2.00 MiB/s, done.",
216 "fatal: early EOF",
217 "fatal: unable to access 'https://user:s3c@ret@github.com/octocat/t3code.git/': could not resolve host",
218 ];
219 const error = yield* Effect.gen(function* () {
220 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
221 return yield* Effect.flip(
222 service.cloneRepository(
223 { remoteUrl: CLONE_URLS.sshUrl, destinationPath },
224 { onProgress: (line) => Effect.sync(() => void progress.push(line)) },
225 ),
226 );
227 }).pipe(
228 Effect.provide(
229 makeLayer({
230 git: {
231 execute: (input) =>
232 Effect.gen(function* () {
233 for (const line of stderrLines) {
234 yield* input.progress?.onStderrLine?.(line) ?? Effect.void;
235 }
236 return yield* new GitCommandError({
237 operation: input.operation,
238 command: "git",
239 cwd: input.cwd,
240 detail: "Git command exited with a non-zero status.",
241 exitCode: 128,
242 });
243 }),
244 },
245 }),
246 ),
247 );
248​
249 assert.deepStrictEqual(progress, [
250 { stage: "counting", percent: null, detail: null },
251 { stage: "receiving", percent: 40, detail: "1.00 MiB | 2.00 MiB/s" },
252 { stage: "receiving", percent: 100, detail: "2.50 MiB | 2.00 MiB/s" },
253 ]);
254 // Git echoes the remote in some failures; the credentials must not follow.
255 assert.strictEqual(
256 error.detail,
257 "fatal: early EOF fatal: unable to access 'https://github.com/octocat/t3code.git/': could not resolve host",
258 );
259 }).pipe(Effect.provide(NodeServices.layer)),
260);
261​
262it.effect("strips embedded credentials from the remote URL it reports", () =>
263 Effect.gen(function* () {
264 const fs = yield* FileSystem.FileSystem;
265 const path = yield* Path.Path;
266 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-redact-" });
267 const destinationPath = path.join(parent, "t3code");
268 const cloneArgs: Array<ReadonlyArray<string>> = [];
269 const result = yield* Effect.gen(function* () {
270 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
271 return yield* service.prepareClone({
272 remoteUrl: "https://user:s3cret@github.com/octocat/t3code.git",
273 destinationPath,
274 });
275 }).pipe(
276 Effect.provide(
277 makeLayer({
278 git: {
279 execute: (input) =>
280 Effect.sync(() => {
281 cloneArgs.push(input.args);
282 return processOutput();
283 }),
284 },
285 }),
286 ),
287 );
288 assert.equal(result.remoteUrl, "https://github.com/octocat/t3code.git");
289 // Git itself still receives the credentials.
290 assert.equal(result.cloneUrl, "https://user:s3cret@github.com/octocat/t3code.git");
291 }).pipe(Effect.provide(NodeServices.layer)),
292);
293​
294it.effect("discards only a directory git wrote to", () =>
295 Effect.gen(function* () {
296 const fs = yield* FileSystem.FileSystem;
297 const path = yield* Path.Path;
298 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-discard-" });
299 const partial = path.join(parent, "partial");
300 yield* fs.makeDirectory(path.join(partial, ".git"), { recursive: true });
301 yield* fs.writeFileString(path.join(partial, "README.md"), "half");
302 const foreign = path.join(parent, "foreign");
303 yield* fs.makeDirectory(foreign);
304 yield* fs.writeFileString(path.join(foreign, "notes.txt"), "mine");
305​
306 // A file where the directory should be must not be removed either.
307 const replaced = path.join(parent, "replaced");
308 yield* fs.writeFileString(replaced, "not a directory");
309​
310 yield* Effect.gen(function* () {
311 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
312 yield* service.discardClone(partial);
313 const error = yield* Effect.flip(service.discardClone(foreign));
314 assert.include(error.detail, "not from the clone");
315 const replacedError = yield* Effect.flip(service.discardClone(replaced));
316 assert.include(replacedError.detail, "could not be inspected");
317 // A destination that never got created is nothing to discard.
318 yield* service.discardClone(path.join(parent, "missing"));
319 }).pipe(Effect.provide(makeLayer({})));
320​
321 // The partial clone is emptied but its directory (the workspace root) stays.
322 assert.deepStrictEqual(yield* fs.readDirectory(partial), []);
323 assert.deepStrictEqual(yield* fs.readDirectory(foreign), ["notes.txt"]);
324 assert.strictEqual(yield* fs.readFileString(replaced), "not a directory");
325 }).pipe(Effect.provide(NodeServices.layer)),
326);
327​
328it.effect("redacts query tokens and userinfo containing '@' from reported URLs", () =>
329 Effect.gen(function* () {
330 const fs = yield* FileSystem.FileSystem;
331 const path = yield* Path.Path;
332 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-redact2-" });
333 yield* Effect.gen(function* () {
334 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
335 const query = yield* service.prepareClone({
336 remoteUrl: "https://github.com/octocat/t3code.git?access_token=s3cret",
337 destinationPath: path.join(parent, "a"),
338 });
339 assert.equal(query.remoteUrl, "https://github.com/octocat/t3code.git");
340 const nested = yield* service.prepareClone({
341 remoteUrl: "https://user:pa@rt@github.com/octocat/t3code.git",
342 destinationPath: path.join(parent, "b"),
343 });
344 assert.equal(nested.remoteUrl, "https://github.com/octocat/t3code.git");
345 }).pipe(Effect.provide(makeLayer({})));
346 }).pipe(Effect.provide(NodeServices.layer)),
347);
348​
349it.effect("preserves destination probe failures instead of treating them as missing paths", () => {
350 const fileSystemCause = PlatformError.systemError({
351 _tag: "PermissionDenied",
352 module: "FileSystem",
353 method: "exists",
354 pathOrDescriptor: "/restricted/t3code",
355 });
356​
357 return Effect.gen(function* () {
358 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
359 const error = yield* Effect.flip(
360 service.cloneRepository({
361 remoteUrl: CLONE_URLS.sshUrl,
362 destinationPath: "/restricted/t3code",
363 }),
364 );
365​
366 assert.strictEqual(error.provider, "unknown");
367 assert.strictEqual(error.operation, "cloneRepository");
368 assert.strictEqual(error.cause, fileSystemCause);
369 }).pipe(
370 Effect.provide(
371 makeLayer({
372 fileSystem: FileSystem.makeNoop({
373 exists: () => Effect.fail(fileSystemCause),
374 makeDirectory: () => Effect.void,
375 }),
376 }),
377 ),
378 );
379});
380​
381it.effect("publishes by creating the repository, adding a remote, and pushing upstream", () => {
382 const createCalls: Array<{ cwd: string; repository: string; visibility: string }> = [];
383 const remoteCalls: Array<{ cwd: string; preferredName: string; url: string }> = [];
384 const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
385 const provider = makeProvider({
386 createRepository: (input) =>
387 Effect.sync(() => {
388 createCalls.push({
389 cwd: input.cwd,
390 repository: input.repository,
391 visibility: input.visibility,
392 });
393 return CLONE_URLS;
394 }),
395 });
396​
397 return Effect.gen(function* () {
398 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
399 const result = yield* service.publishRepository({
400 cwd: "/workspace",
401 provider: "github",
402 repository: "octocat/t3code",
403 visibility: "private",
404 remoteName: "origin",
405 protocol: "ssh",
406 });
407​
408 assert.deepStrictEqual(result, {
409 repository: { provider: "github", ...CLONE_URLS },
410 remoteName: "origin",
411 remoteUrl: CLONE_URLS.sshUrl,
412 branch: "feature/remote-v1",
413 upstreamBranch: "origin/feature/remote-v1",
414 status: "pushed",
415 });
416 assert.deepStrictEqual(createCalls, [
417 { cwd: "/workspace", repository: "octocat/t3code", visibility: "private" },
418 ]);
419 assert.deepStrictEqual(remoteCalls, [
420 { cwd: "/workspace", preferredName: "origin", url: CLONE_URLS.sshUrl },
421 ]);
422 assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin" }]);
423 }).pipe(
424 Effect.provide(
425 makeLayer({
426 provider,
427 git: {
428 ensureRemote: (input) =>
429 Effect.sync(() => {
430 remoteCalls.push(input);
431 return "origin";
432 }),
433 pushCurrentBranch: (cwd, _fallbackBranch, options) =>
434 Effect.sync(() => {
435 pushCalls.push({ cwd, remoteName: options?.remoteName });
436 return {
437 status: "pushed" as const,
438 branch: "feature/remote-v1",
439 upstreamBranch: "origin/feature/remote-v1",
440 setUpstream: true,
441 };
442 }),
443 },
444 }),
445 ),
446 );
447});
448​
449it.effect("publishes to the remote name returned by ensureRemote", () => {
450 const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
451​
452 return Effect.gen(function* () {
453 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
454 const result = yield* service.publishRepository({
455 cwd: "/workspace",
456 provider: "github",
457 repository: "octocat/t3code",
458 visibility: "private",
459 remoteName: "origin",
460 protocol: "ssh",
461 });
462​
463 assert.equal(result.remoteName, "origin-1");
464 assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin-1" }]);
465 }).pipe(
466 Effect.provide(
467 makeLayer({
468 git: {
469 ensureRemote: () => Effect.succeed("origin-1"),
470 pushCurrentBranch: (cwd, _fallbackBranch, options) =>
471 Effect.sync(() => {
472 pushCalls.push({ cwd, remoteName: options?.remoteName });
473 return {
474 status: "pushed" as const,
475 branch: "feature/remote-v1",
476 upstreamBranch: `${options?.remoteName ?? "missing"}/feature/remote-v1`,
477 setUpstream: true,
478 };
479 }),
480 },
481 }),
482 ),
483 );
484});
485​
486it.effect("publish succeeds with status remote_added when the local repo has no commits", () => {
487 let pushCalls = 0;
488 return Effect.gen(function* () {
489 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
490 const result = yield* service.publishRepository({
491 cwd: "/workspace",
492 provider: "github",
493 repository: "octocat/t3code",
494 visibility: "private",
495 remoteName: "origin",
496 protocol: "ssh",
497 });
498​
499 assert.deepStrictEqual(result, {
500 repository: { provider: "github", ...CLONE_URLS },
501 remoteName: "origin",
502 remoteUrl: CLONE_URLS.sshUrl,
503 branch: "main",
504 status: "remote_added",
505 });
506 assert.strictEqual(pushCalls, 0);
507 }).pipe(
508 Effect.provide(
509 makeLayer({
510 git: {
511 execute: (input) =>
512 input.args[0] === "rev-parse"
513 ? Effect.fail(
514 new GitCommandError({
515 operation: input.operation,
516 command: "git rev-parse --verify HEAD",
517 cwd: input.cwd,
518 detail: "fatal: Needed a single revision",
519 }),
520 )
521 : Effect.succeed(processOutput()),
522 statusDetails: () =>
523 Effect.succeed({
524 isRepo: true,
525 hasOriginRemote: true,
526 isDefaultBranch: true,
527 branch: "main",
528 upstreamRef: null,
529 hasWorkingTreeChanges: false,
530 workingTree: { files: [], insertions: 0, deletions: 0 },
531 hasUpstream: false,
532 aheadCount: 0,
533 behindCount: 0,
534 aheadOfDefaultCount: 0,
535 }),
536 pushCurrentBranch: () =>
537 Effect.sync(() => {
538 pushCalls += 1;
539 return {
540 status: "pushed" as const,
541 branch: "main",
542 upstreamBranch: "origin/main",
543 setUpstream: true,
544 };
545 }),
546 },
547 }),
548 ),
549 );
550});