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

SourceControlRepositoryService.test.ts

519 lines19.0 KB

1import { SourceControlProviderKind } from "@t3tools/contracts";
2import * as NodePath from "@effect/platform-node/NodePath";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { assert, it } from "@effect/vitest";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Path from "effect/Path";
8import * as Layer from "effect/Layer";
9import * as PlatformError from "effect/PlatformError";
10import { ChildProcessSpawner } from "effect/process";
11​
12import { GitCommandError, SourceControlProviderError } from "@t3tools/contracts";
13​
14import * as ServerConfig from "../config.ts";
15import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
16import type * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
17import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
18import * as SourceControlRepositoryService from "./SourceControlRepositoryService.ts";
19​
20const CLONE_URLS = {
21 nameWithOwner: "octocat/t3code",
22 url: "https://github.com/octocat/t3code",
23 sshUrl: "git@github.com:octocat/t3code.git",
24};
25​
26function makeProvider(
27 overrides: Partial<SourceControlProvider.SourceControlProvider["Service"]> = {},
28): SourceControlProvider.SourceControlProvider["Service"] {
29 const unsupported = (operation: string) =>
30 Effect.die(`unexpected provider operation ${operation}`) as Effect.Effect<
31 never,
32 SourceControlProviderError
33 >;
34​
35 return {
36 kind: SourceControlProviderKind.make("github"),
37 listChangeRequests: () => unsupported("listChangeRequests"),
38 getChangeRequest: () => unsupported("getChangeRequest"),
39 createChangeRequest: () => unsupported("createChangeRequest"),
40 getRepositoryCloneUrls: () => Effect.succeed(CLONE_URLS),
41 createRepository: () => Effect.succeed(CLONE_URLS),
42 getDefaultBranch: () => Effect.succeed(null),
43 checkoutChangeRequest: () => unsupported("checkoutChangeRequest"),
44 ...overrides,
45 };
47​
48function processOutput(): GitVcsDriver.ExecuteGitResult {
49 return {
50 exitCode: ChildProcessSpawner.ExitCode(0),
51 stdout: "",
52 stderr: "",
53 stdoutTruncated: false,
54 stderrTruncated: false,
55 };
57​
58function layer(input: {
59 readonly provider?: SourceControlProvider.SourceControlProvider["Service"];
60 readonly git?: Partial<GitVcsDriver.GitVcsDriver["Service"]>;
61 readonly fileSystem?: FileSystem.FileSystem;
62}) {
63 const layerService = SourceControlRepositoryService.layer.pipe(
64 Layer.provide(
65 Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({
66 resolveLink: () => undefined,
67 get: () => Effect.succeed(input.provider ?? makeProvider()),
68 }),
69 ),
70 Layer.provide(
71 Layer.mock(GitVcsDriver.GitVcsDriver)({
72 execute: () => Effect.succeed(processOutput()),
73 ensureRemote: () => Effect.succeed("origin"),
74 pushCurrentBranch: () =>
75 Effect.succeed({
76 status: "pushed" as const,
77 branch: "feature/remote-v1",
78 upstreamBranch: "origin/feature/remote-v1",
79 setUpstream: true,
80 }),
81 ...input.git,
82 }),
83 ),
84 Layer.provide(
85 ServerConfig.layerTest(
86 process.cwd(),
87 input.fileSystem ? "/tmp/t3-source-control-repos" : { prefix: "t3-source-control-repos-" },
88 ),
89 ),
90 );
91​
92 return input.fileSystem
93 ? layerService.pipe(
94 Layer.provide(Layer.succeed(FileSystem.FileSystem, input.fileSystem)),
95 Layer.provideMerge(NodePath.layer),
96 )
97 : layerService.pipe(Layer.provideMerge(NodeServices.layer));
99​
100it.effect("clones a looked-up repository after creating missing parent directories", () =>
101 Effect.gen(function* () {
102 const fs = yield* FileSystem.FileSystem;
103 const path = yield* Path.Path;
104 const temporaryDirectory = yield* fs.makeTempDirectoryScoped({
105 prefix: "t3-source-control-clone-parent-",
106 });
107 const parent = path.join(temporaryDirectory, "missing", "nested");
108 const destinationPath = path.join(parent, "t3code");
109 const cloneCalls: Array<{ cwd: string; args: ReadonlyArray<string> }> = [];
110​
111 yield* Effect.gen(function* () {
112 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
113 const result = yield* service.cloneRepository({
114 provider: SourceControlProviderKind.make("github"),
115 repository: "octocat/t3code",
116 destinationPath,
117 protocol: "https",
118 });
119​
120 assert.deepStrictEqual(result, {
121 cwd: destinationPath,
122 remoteUrl: CLONE_URLS.url,
123 repository: { provider: SourceControlProviderKind.make("github"), ...CLONE_URLS },
124 });
125 assert.deepStrictEqual(cloneCalls, [
126 {
127 cwd: parent,
128 args: ["clone", "--progress", "--", CLONE_URLS.url, "t3code"],
129 },
130 ]);
131 }).pipe(
132 Effect.provide(
133 layer({
134 git: {
135 execute: (input) =>
136 Effect.gen(function* () {
137 assert.isTrue(yield* fs.exists(parent).pipe(Effect.orDie));
138 cloneCalls.push({ cwd: input.cwd, args: input.args });
139 return processOutput();
140 }),
141 },
142 }),
143 ),
144 );
145 }).pipe(Effect.provide(NodeServices.layer)),
146);
147​
148it.effect.each(["--bare", "source.git"])(
149 "clones a local repository named %s as a working tree",
150 (repositoryName) =>
151 Effect.gen(function* () {
152 const fs = yield* FileSystem.FileSystem;
153 const path = yield* Path.Path;
154 const git = yield* GitVcsDriver.GitVcsDriver;
155 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-clone-options-" });
156 yield* git.execute({
157 operation: "test.init",
158 cwd: parent,
159 args: ["init", "--bare", path.join(parent, repositoryName)],
160 });
161 const destinationPath = path.join(parent, "checkout");
162 yield* Effect.gen(function* () {
163 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
164 const result = yield* service.cloneRepository({
165 remoteUrl: repositoryName,
166 destinationPath,
167 });
168 assert.strictEqual(result.cwd, destinationPath);
169 assert.isTrue(yield* fs.exists(path.join(destinationPath, ".git")));
170 }).pipe(Effect.provide(layer({ git: { execute: git.execute } })));
171 }).pipe(
172 Effect.provide(
173 GitVcsDriver.layer.pipe(
174 Layer.provide(
175 ServerConfig.layerTest(process.cwd(), {
176 prefix: "t3-clone-options-config-",
177 }),
178 ),
179 Layer.provideMerge(NodeServices.layer),
180 ),
181 ),
182 ),
183);
184​
185it.effect("reports clone progress from git's stderr and keeps its error text on failure", () =>
186 Effect.gen(function* () {
187 const fs = yield* FileSystem.FileSystem;
188 const path = yield* Path.Path;
189 const parent = yield* fs.makeTempDirectoryScoped({
190 prefix: "t3-source-control-clone-progress-",
191 });
192 const destinationPath = path.join(parent, "t3code");
193 const progress: Array<{ stage: string; percent: number | null; detail: string | null }> = [];
194​
195 const stderrLines = [
196 "Cloning into 't3code'...",
197 "remote: Enumerating objects: 10, done.",
198 "Receiving objects: 40% (4/10), 1.00 MiB | 2.00 MiB/s",
199 "Receiving objects: 100% (10/10), 2.50 MiB | 2.00 MiB/s, done.",
200 "fatal: early EOF",
201 "fatal: unable to access 'https://user:s3c@ret@github.com/octocat/t3code.git/': could not resolve host",
202 ];
203 const error = yield* Effect.gen(function* () {
204 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
205 return yield* Effect.flip(
206 service.cloneRepository(
207 { remoteUrl: CLONE_URLS.sshUrl, destinationPath },
208 { onProgress: (line) => Effect.sync(() => void progress.push(line)) },
209 ),
210 );
211 }).pipe(
212 Effect.provide(
213 layer({
214 git: {
215 execute: (input) =>
216 Effect.gen(function* () {
217 for (const line of stderrLines) {
218 yield* input.progress?.onStderrLine?.(line) ?? Effect.void;
219 }
220 return yield* new GitCommandError({
221 operation: input.operation,
222 command: "git",
223 cwd: input.cwd,
224 detail: "Git command exited with a non-zero status.",
225 exitCode: 128,
226 });
227 }),
228 },
229 }),
230 ),
231 );
232​
233 assert.deepStrictEqual(progress, [
234 { stage: "counting", percent: null, detail: null },
235 { stage: "receiving", percent: 40, detail: "1.00 MiB | 2.00 MiB/s" },
236 { stage: "receiving", percent: 100, detail: "2.50 MiB | 2.00 MiB/s" },
237 ]);
238 assert.strictEqual(
239 error.detail,
240 "fatal: early EOF fatal: unable to access 'https://github.com/octocat/t3code.git/': could not resolve host",
241 );
242 }).pipe(Effect.provide(NodeServices.layer)),
243);
244​
245it.effect("strips embedded credentials from the remote URL it reports", () =>
246 Effect.gen(function* () {
247 const fs = yield* FileSystem.FileSystem;
248 const path = yield* Path.Path;
249 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-redact-" });
250 const destinationPath = path.join(parent, "t3code");
251 const cloneArgs: Array<ReadonlyArray<string>> = [];
252 const result = yield* Effect.gen(function* () {
253 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
254 return yield* service.prepareClone({
255 remoteUrl: "https://user:s3cret@github.com/octocat/t3code.git",
256 destinationPath,
257 });
258 }).pipe(
259 Effect.provide(
260 layer({
261 git: {
262 execute: (input) =>
263 Effect.sync(() => {
264 cloneArgs.push(input.args);
265 return processOutput();
266 }),
267 },
268 }),
269 ),
270 );
271 assert.equal(result.remoteUrl, "https://github.com/octocat/t3code.git");
272 assert.equal(result.cloneUrl, "https://user:s3cret@github.com/octocat/t3code.git");
273 }).pipe(Effect.provide(NodeServices.layer)),
274);
275​
276it.effect("discards only a directory git wrote to", () =>
277 Effect.gen(function* () {
278 const fs = yield* FileSystem.FileSystem;
279 const path = yield* Path.Path;
280 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-discard-" });
281 const partial = path.join(parent, "partial");
282 yield* fs.makeDirectory(path.join(partial, ".git"), { recursive: true });
283 yield* fs.writeFileString(path.join(partial, "README.md"), "half");
284 const foreign = path.join(parent, "foreign");
285 yield* fs.makeDirectory(foreign);
286 yield* fs.writeFileString(path.join(foreign, "notes.txt"), "mine");
287​
288 const replaced = path.join(parent, "replaced");
289 yield* fs.writeFileString(replaced, "not a directory");
290​
291 yield* Effect.gen(function* () {
292 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
293 yield* service.discardClone(partial);
294 const error = yield* Effect.flip(service.discardClone(foreign));
295 assert.include(error.detail, "not from the clone");
296 const replacedError = yield* Effect.flip(service.discardClone(replaced));
297 assert.include(replacedError.detail, "could not be inspected");
298 yield* service.discardClone(path.join(parent, "missing"));
299 }).pipe(Effect.provide(layer({})));
300​
301 assert.deepStrictEqual(yield* fs.readDirectory(partial), []);
302 assert.deepStrictEqual(yield* fs.readDirectory(foreign), ["notes.txt"]);
303 assert.strictEqual(yield* fs.readFileString(replaced), "not a directory");
304 }).pipe(Effect.provide(NodeServices.layer)),
305);
306​
307it.effect("redacts query tokens and userinfo containing '@' from reported URLs", () =>
308 Effect.gen(function* () {
309 const fs = yield* FileSystem.FileSystem;
310 const path = yield* Path.Path;
311 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-redact2-" });
312 yield* Effect.gen(function* () {
313 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
314 const query = yield* service.prepareClone({
315 remoteUrl: "https://github.com/octocat/t3code.git?access_token=s3cret",
316 destinationPath: path.join(parent, "a"),
317 });
318 assert.equal(query.remoteUrl, "https://github.com/octocat/t3code.git");
319 const nested = yield* service.prepareClone({
320 remoteUrl: "https://user:pa@rt@github.com/octocat/t3code.git",
321 destinationPath: path.join(parent, "b"),
322 });
323 assert.equal(nested.remoteUrl, "https://github.com/octocat/t3code.git");
324 }).pipe(Effect.provide(layer({})));
325 }).pipe(Effect.provide(NodeServices.layer)),
326);
327​
328it.effect("preserves destination probe failures instead of treating them as missing paths", () => {
329 const fileSystemCause = PlatformError.systemError({
330 _tag: "PermissionDenied",
331 module: "FileSystem",
332 method: "exists",
333 pathOrDescriptor: "/restricted/t3code",
334 });
335​
336 return Effect.gen(function* () {
337 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
338 const error = yield* Effect.flip(
339 service.cloneRepository({
340 remoteUrl: CLONE_URLS.sshUrl,
341 destinationPath: "/restricted/t3code",
342 }),
343 );
344​
345 assert.strictEqual(error.provider, "unknown");
346 assert.strictEqual(error.operation, "cloneRepository");
347 assert.strictEqual(error.cause, fileSystemCause);
348 }).pipe(
349 Effect.provide(
350 layer({
351 fileSystem: FileSystem.makeNoop({
352 exists: () => Effect.fail(fileSystemCause),
353 makeDirectory: () => Effect.void,
354 }),
355 }),
356 ),
357 );
358});
359​
360it.effect("publishes to the remote name returned by ensureRemote", () => {
361 const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
362​
363 return Effect.gen(function* () {
364 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
365 const result = yield* service.publishRepository({
366 cwd: "/workspace",
367 provider: SourceControlProviderKind.make("github"),
368 repository: "octocat/t3code",
369 visibility: "private",
370 remoteName: "origin",
371 protocol: "ssh",
372 });
373​
374 assert.equal(result.remoteName, "origin-1");
375 assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin-1" }]);
376 }).pipe(
377 Effect.provide(
378 layer({
379 git: {
380 ensureRemote: () => Effect.succeed("origin-1"),
381 pushCurrentBranch: (cwd, _fallbackBranch, options) =>
382 Effect.sync(() => {
383 pushCalls.push({ cwd, remoteName: options?.remoteName });
384 return {
385 status: "pushed" as const,
386 branch: "feature/remote-v1",
387 upstreamBranch: `${options?.remoteName ?? "missing"}/feature/remote-v1`,
388 setUpstream: true,
389 };
390 }),
391 },
392 }),
393 ),
394 );
395});
396​
397function failingPush(reason?: GitCommandError["reason"]) {
398 return {
399 pushCurrentBranch: (cwd: string) =>
400 Effect.fail(
401 new GitCommandError({
402 operation: "GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote",
403 command: "git",
404 cwd,
405 ...(reason === undefined ? {} : { reason }),
406 detail: "Git command exited with a non-zero status.",
407 }),
408 ),
409 } satisfies Partial<GitVcsDriver.GitVcsDriver["Service"]>;
411​
412it.effect("explains a rejected SSH push after creating the repository", () =>
413 Effect.gen(function* () {
414 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
415 const error = yield* Effect.flip(
416 service.publishRepository({
417 cwd: "/workspace",
418 provider: SourceControlProviderKind.make("github"),
419 repository: "octocat/t3code",
420 visibility: "private",
421 protocol: "ssh",
422 }),
423 );
424​
425 assert.strictEqual(error.operation, "publishRepository");
426 assert.strictEqual(
427 error.detail,
428 'Created octocat/t3code and added it as remote "origin", but the push failed because SSH authentication was rejected. Add an SSH key to your account, or switch the remote to HTTPS with "git remote set-url origin https://github.com/octocat/t3code", then push again.',
429 );
430 assert.instanceOf(error.cause, GitCommandError);
431 }).pipe(Effect.provide(layer({ git: failingPush("authentication_failed") }))),
432);
433​
434// regression: #19219 publishing did not explain why the first push failed
435it.effect("says the repository exists when an unclassified publish push fails", () =>
436 Effect.gen(function* () {
437 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
438 const error = yield* Effect.flip(
439 service.publishRepository({
440 cwd: "/workspace",
441 provider: SourceControlProviderKind.make("github"),
442 repository: "octocat/t3code",
443 visibility: "private",
444 protocol: "https",
445 }),
446 );
447​
448 assert.strictEqual(
449 error.detail,
450 'Created octocat/t3code and added it as remote "origin", but the push failed. Fix the problem, then push again.',
451 );
452 }).pipe(Effect.provide(layer({ git: failingPush() }))),
453);
454​
455it.effect("publish succeeds with status remote_added when the local repo has no commits", () => {
456 let pushCalls = 0;
457 return Effect.gen(function* () {
458 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
459 const result = yield* service.publishRepository({
460 cwd: "/workspace",
461 provider: SourceControlProviderKind.make("github"),
462 repository: "octocat/t3code",
463 visibility: "private",
464 remoteName: "origin",
465 protocol: "ssh",
466 });
467​
468 assert.deepStrictEqual(result, {
469 repository: { provider: SourceControlProviderKind.make("github"), ...CLONE_URLS },
470 remoteName: "origin",
471 remoteUrl: CLONE_URLS.sshUrl,
472 branch: "main",
473 status: "remote_added",
474 });
475 assert.strictEqual(pushCalls, 0);
476 }).pipe(
477 Effect.provide(
478 layer({
479 git: {
480 execute: (input) =>
481 input.args[0] === "rev-parse"
482 ? Effect.fail(
483 new GitCommandError({
484 operation: input.operation,
485 command: "git rev-parse --verify HEAD",
486 cwd: input.cwd,
487 detail: "fatal: Needed a single revision",
488 }),
489 )
490 : Effect.succeed(processOutput()),
491 statusDetails: () =>
492 Effect.succeed({
493 isRepo: true,
494 hasOriginRemote: true,
495 isDefaultBranch: true,
496 branch: "main",
497 upstreamRef: null,
498 hasWorkingTreeChanges: false,
499 workingTree: { files: [], insertions: 0, deletions: 0 },
500 hasUpstream: false,
501 aheadCount: 0,
502 behindCount: 0,
503 aheadOfDefaultCount: 0,
504 }),
505 pushCurrentBranch: () =>
506 Effect.sync(() => {
507 pushCalls += 1;
508 return {
509 status: "pushed" as const,
510 branch: "main",
511 upstreamBranch: "origin/main",
512 setUpstream: true,
513 };
514 }),
515 },
516 }),
517 ),
518 );
519});