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