Open History to see the last commit
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 };
45}
46
47function processOutput(): GitVcsDriver.ExecuteGitResult {
48 return {
49 exitCode: ChildProcessSpawner.ExitCode(0),
50 stdout: "",
51 stderr: "",
52 stdoutTruncated: false,
53 stderrTruncated: false,
54 };
55}
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));
96}
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", "--progress", 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("reports clone progress from git's stderr and keeps its error text on failure", () =>
201 Effect.gen(function* () {
202 const fs = yield* FileSystem.FileSystem;
203 const path = yield* Path.Path;
204 const parent = yield* fs.makeTempDirectoryScoped({
205 prefix: "t3-source-control-clone-progress-",
206 });
207 const destinationPath = path.join(parent, "t3code");
208 const progress: Array<{ stage: string; percent: number | null; detail: string | null }> = [];
209
210 const stderrLines = [
211 "Cloning into 't3code'...",
212 "remote: Enumerating objects: 10, done.",
213 "Receiving objects: 40% (4/10), 1.00 MiB | 2.00 MiB/s",
214 "Receiving objects: 100% (10/10), 2.50 MiB | 2.00 MiB/s, done.",
215 "fatal: early EOF",
216 "fatal: unable to access 'https://user:s3c@ret@github.com/octocat/t3code.git/': could not resolve host",
217 ];
218 const error = yield* Effect.gen(function* () {
219 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
220 return yield* Effect.flip(
221 service.cloneRepository(
222 { remoteUrl: CLONE_URLS.sshUrl, destinationPath },
223 { onProgress: (line) => Effect.sync(() => void progress.push(line)) },
224 ),
225 );
226 }).pipe(
227 Effect.provide(
228 makeLayer({
229 git: {
230 execute: (input) =>
231 Effect.gen(function* () {
232 for (const line of stderrLines) {
233 yield* input.progress?.onStderrLine?.(line) ?? Effect.void;
234 }
235 return yield* new GitCommandError({
236 operation: input.operation,
237 command: "git",
238 cwd: input.cwd,
239 detail: "Git command exited with a non-zero status.",
240 exitCode: 128,
241 });
242 }),
243 },
244 }),
245 ),
246 );
247
248 assert.deepStrictEqual(progress, [
249 { stage: "counting", percent: null, detail: null },
250 { stage: "receiving", percent: 40, detail: "1.00 MiB | 2.00 MiB/s" },
251 { stage: "receiving", percent: 100, detail: "2.50 MiB | 2.00 MiB/s" },
252 ]);
253 // Git echoes the remote in some failures; the credentials must not follow.
254 assert.strictEqual(
255 error.detail,
256 "fatal: early EOF fatal: unable to access 'https://github.com/octocat/t3code.git/': could not resolve host",
257 );
258 }).pipe(Effect.provide(NodeServices.layer)),
259);
260
261it.effect("strips embedded credentials from the remote URL it reports", () =>
262 Effect.gen(function* () {
263 const fs = yield* FileSystem.FileSystem;
264 const path = yield* Path.Path;
265 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-redact-" });
266 const destinationPath = path.join(parent, "t3code");
267 const cloneArgs: Array<ReadonlyArray<string>> = [];
268 const result = yield* Effect.gen(function* () {
269 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
270 return yield* service.prepareClone({
271 remoteUrl: "https://user:s3cret@github.com/octocat/t3code.git",
272 destinationPath,
273 });
274 }).pipe(
275 Effect.provide(
276 makeLayer({
277 git: {
278 execute: (input) =>
279 Effect.sync(() => {
280 cloneArgs.push(input.args);
281 return processOutput();
282 }),
283 },
284 }),
285 ),
286 );
287 assert.equal(result.remoteUrl, "https://github.com/octocat/t3code.git");
288 // Git itself still receives the credentials.
289 assert.equal(result.cloneUrl, "https://user:s3cret@github.com/octocat/t3code.git");
290 }).pipe(Effect.provide(NodeServices.layer)),
291);
292
293it.effect("discards only a directory git wrote to", () =>
294 Effect.gen(function* () {
295 const fs = yield* FileSystem.FileSystem;
296 const path = yield* Path.Path;
297 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-discard-" });
298 const partial = path.join(parent, "partial");
299 yield* fs.makeDirectory(path.join(partial, ".git"), { recursive: true });
300 yield* fs.writeFileString(path.join(partial, "README.md"), "half");
301 const foreign = path.join(parent, "foreign");
302 yield* fs.makeDirectory(foreign);
303 yield* fs.writeFileString(path.join(foreign, "notes.txt"), "mine");
304
305 // A file where the directory should be must not be removed either.
306 const replaced = path.join(parent, "replaced");
307 yield* fs.writeFileString(replaced, "not a directory");
308
309 yield* Effect.gen(function* () {
310 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
311 yield* service.discardClone(partial);
312 const error = yield* Effect.flip(service.discardClone(foreign));
313 assert.include(error.detail, "not from the clone");
314 const replacedError = yield* Effect.flip(service.discardClone(replaced));
315 assert.include(replacedError.detail, "could not be inspected");
316 // A destination that never got created is nothing to discard.
317 yield* service.discardClone(path.join(parent, "missing"));
318 }).pipe(Effect.provide(makeLayer({})));
319
320 // The partial clone is emptied but its directory (the workspace root) stays.
321 assert.deepStrictEqual(yield* fs.readDirectory(partial), []);
322 assert.deepStrictEqual(yield* fs.readDirectory(foreign), ["notes.txt"]);
323 assert.strictEqual(yield* fs.readFileString(replaced), "not a directory");
324 }).pipe(Effect.provide(NodeServices.layer)),
325);
326
327it.effect("redacts query tokens and userinfo containing '@' from reported URLs", () =>
328 Effect.gen(function* () {
329 const fs = yield* FileSystem.FileSystem;
330 const path = yield* Path.Path;
331 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-redact2-" });
332 yield* Effect.gen(function* () {
333 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
334 const query = yield* service.prepareClone({
335 remoteUrl: "https://github.com/octocat/t3code.git?access_token=s3cret",
336 destinationPath: path.join(parent, "a"),
337 });
338 assert.equal(query.remoteUrl, "https://github.com/octocat/t3code.git");
339 const nested = yield* service.prepareClone({
340 remoteUrl: "https://user:pa@rt@github.com/octocat/t3code.git",
341 destinationPath: path.join(parent, "b"),
342 });
343 assert.equal(nested.remoteUrl, "https://github.com/octocat/t3code.git");
344 }).pipe(Effect.provide(makeLayer({})));
345 }).pipe(Effect.provide(NodeServices.layer)),
346);
347
348it.effect("preserves destination probe failures instead of treating them as missing paths", () => {
349 const fileSystemCause = PlatformError.systemError({
350 _tag: "PermissionDenied",
351 module: "FileSystem",
352 method: "exists",
353 pathOrDescriptor: "/restricted/t3code",
354 });
355
356 return Effect.gen(function* () {
357 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
358 const error = yield* Effect.flip(
359 service.cloneRepository({
360 remoteUrl: CLONE_URLS.sshUrl,
361 destinationPath: "/restricted/t3code",
362 }),
363 );
364
365 assert.strictEqual(error.provider, "unknown");
366 assert.strictEqual(error.operation, "cloneRepository");
367 assert.strictEqual(error.cause, fileSystemCause);
368 }).pipe(
369 Effect.provide(
370 makeLayer({
371 fileSystem: FileSystem.makeNoop({
372 exists: () => Effect.fail(fileSystemCause),
373 makeDirectory: () => Effect.void,
374 }),
375 }),
376 ),
377 );
378});
379
380it.effect("publishes by creating the repository, adding a remote, and pushing upstream", () => {
381 const createCalls: Array<{ cwd: string; repository: string; visibility: string }> = [];
382 const remoteCalls: Array<{ cwd: string; preferredName: string; url: string }> = [];
383 const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
384 const provider = makeProvider({
385 createRepository: (input) =>
386 Effect.sync(() => {
387 createCalls.push({
388 cwd: input.cwd,
389 repository: input.repository,
390 visibility: input.visibility,
391 });
392 return CLONE_URLS;
393 }),
394 });
395
396 return Effect.gen(function* () {
397 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
398 const result = yield* service.publishRepository({
399 cwd: "/workspace",
400 provider: "github",
401 repository: "octocat/t3code",
402 visibility: "private",
403 remoteName: "origin",
404 protocol: "ssh",
405 });
406
407 assert.deepStrictEqual(result, {
408 repository: { provider: "github", ...CLONE_URLS },
409 remoteName: "origin",
410 remoteUrl: CLONE_URLS.sshUrl,
411 branch: "feature/remote-v1",
412 upstreamBranch: "origin/feature/remote-v1",
413 status: "pushed",
414 });
415 assert.deepStrictEqual(createCalls, [
416 { cwd: "/workspace", repository: "octocat/t3code", visibility: "private" },
417 ]);
418 assert.deepStrictEqual(remoteCalls, [
419 { cwd: "/workspace", preferredName: "origin", url: CLONE_URLS.sshUrl },
420 ]);
421 assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin" }]);
422 }).pipe(
423 Effect.provide(
424 makeLayer({
425 provider,
426 git: {
427 ensureRemote: (input) =>
428 Effect.sync(() => {
429 remoteCalls.push(input);
430 return "origin";
431 }),
432 pushCurrentBranch: (cwd, _fallbackBranch, options) =>
433 Effect.sync(() => {
434 pushCalls.push({ cwd, remoteName: options?.remoteName });
435 return {
436 status: "pushed" as const,
437 branch: "feature/remote-v1",
438 upstreamBranch: "origin/feature/remote-v1",
439 setUpstream: true,
440 };
441 }),
442 },
443 }),
444 ),
445 );
446});
447
448it.effect("publishes to the remote name returned by ensureRemote", () => {
449 const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
450
451 return Effect.gen(function* () {
452 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
453 const result = yield* service.publishRepository({
454 cwd: "/workspace",
455 provider: "github",
456 repository: "octocat/t3code",
457 visibility: "private",
458 remoteName: "origin",
459 protocol: "ssh",
460 });
461
462 assert.equal(result.remoteName, "origin-1");
463 assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin-1" }]);
464 }).pipe(
465 Effect.provide(
466 makeLayer({
467 git: {
468 ensureRemote: () => Effect.succeed("origin-1"),
469 pushCurrentBranch: (cwd, _fallbackBranch, options) =>
470 Effect.sync(() => {
471 pushCalls.push({ cwd, remoteName: options?.remoteName });
472 return {
473 status: "pushed" as const,
474 branch: "feature/remote-v1",
475 upstreamBranch: `${options?.remoteName ?? "missing"}/feature/remote-v1`,
476 setUpstream: true,
477 };
478 }),
479 },
480 }),
481 ),
482 );
483});
484
485it.effect("publish succeeds with status remote_added when the local repo has no commits", () => {
486 let pushCalls = 0;
487 return Effect.gen(function* () {
488 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
489 const result = yield* service.publishRepository({
490 cwd: "/workspace",
491 provider: "github",
492 repository: "octocat/t3code",
493 visibility: "private",
494 remoteName: "origin",
495 protocol: "ssh",
496 });
497
498 assert.deepStrictEqual(result, {
499 repository: { provider: "github", ...CLONE_URLS },
500 remoteName: "origin",
501 remoteUrl: CLONE_URLS.sshUrl,
502 branch: "main",
503 status: "remote_added",
504 });
505 assert.strictEqual(pushCalls, 0);
506 }).pipe(
507 Effect.provide(
508 makeLayer({
509 git: {
510 execute: (input) =>
511 input.args[0] === "rev-parse"
512 ? Effect.fail(
513 new GitCommandError({
514 operation: input.operation,
515 command: "git rev-parse --verify HEAD",
516 cwd: input.cwd,
517 detail: "fatal: Needed a single revision",
518 }),
519 )
520 : Effect.succeed(processOutput()),
521 statusDetails: () =>
522 Effect.succeed({
523 isRepo: true,
524 hasOriginRemote: true,
525 isDefaultBranch: true,
526 branch: "main",
527 upstreamRef: null,
528 hasWorkingTreeChanges: false,
529 workingTree: { files: [], insertions: 0, deletions: 0 },
530 hasUpstream: false,
531 aheadCount: 0,
532 behindCount: 0,
533 aheadOfDefaultCount: 0,
534 }),
535 pushCurrentBranch: () =>
536 Effect.sync(() => {
537 pushCalls += 1;
538 return {
539 status: "pushed" as const,
540 branch: "main",
541 upstreamBranch: "origin/main",
542 setUpstream: true,
543 };
544 }),
545 },
546 }),
547 ),
548 );
549});