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