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 Deferred from "effect/Deferred";
6import * as FileSystem from "effect/FileSystem";
7import * as Fiber from "effect/Fiber";
8import * as Path from "effect/Path";
9import * as Layer from "effect/Layer";
10import * as PlatformError from "effect/PlatformError";
11import * as Sink from "effect/Sink";
12import * as Stream from "effect/Stream";
13import * as TestClock from "effect/testing/TestClock";
14import { ChildProcessSpawner } from "effect/unstable/process";
15
16import { GitCommandError, SourceControlProviderError } from "@t3tools/contracts";
17
18import * as ServerConfig from "../config.ts";
19import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
20import type * as SourceControlProvider from "./SourceControlProvider.ts";
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: "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 makeLayer(input: {
63 readonly provider?: SourceControlProvider.SourceControlProvider["Service"];
64 readonly git?: Partial<GitVcsDriver.GitVcsDriver["Service"]>;
65 readonly fileSystem?: FileSystem.FileSystem;
66}) {
67 const serviceLayer = SourceControlRepositoryService.layer.pipe(
68 Layer.provide(
69 Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({
70 get: () => Effect.succeed(input.provider ?? makeProvider()),
71 }),
72 ),
73 Layer.provide(
74 Layer.mock(GitVcsDriver.GitVcsDriver)({
75 execute: () => Effect.succeed(processOutput()),
76 ensureRemote: () => Effect.succeed("origin"),
77 pushCurrentBranch: () =>
78 Effect.succeed({
79 status: "pushed" as const,
80 branch: "feature/remote-v1",
81 upstreamBranch: "origin/feature/remote-v1",
82 setUpstream: true,
83 }),
84 ...input.git,
85 }),
86 ),
87 Layer.provide(
88 ServerConfig.layerTest(
89 process.cwd(),
90 input.fileSystem ? "/tmp/t3-source-control-repos" : { prefix: "t3-source-control-repos-" },
91 ),
92 ),
93 );
94
95 return input.fileSystem
96 ? serviceLayer.pipe(
97 Layer.provide(Layer.succeed(FileSystem.FileSystem, input.fileSystem)),
98 Layer.provideMerge(NodePath.layer),
99 )
100 : serviceLayer.pipe(Layer.provideMerge(NodeServices.layer));
101}
102
103it.effect("looks up repositories through the requested provider without search", () => {
104 const calls: Array<{ cwd: string; repository: string }> = [];
105 const provider = makeProvider({
106 getRepositoryCloneUrls: (input) =>
107 Effect.sync(() => {
108 calls.push({ cwd: input.cwd, repository: input.repository });
109 return CLONE_URLS;
110 }),
111 });
112
113 return Effect.gen(function* () {
114 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
115 const result = yield* service.lookupRepository({
116 provider: "github",
117 repository: "octocat/t3code",
118 cwd: "/workspace",
119 });
120
121 assert.deepStrictEqual(result, { provider: "github", ...CLONE_URLS });
122 assert.deepStrictEqual(calls, [{ cwd: "/workspace", repository: "octocat/t3code" }]);
123 }).pipe(Effect.provide(makeLayer({ provider })));
124});
125
126it.effect("preserves provider failures without deriving the repository message from them", () => {
127 const providerCause = new SourceControlProviderError({
128 provider: "github",
129 operation: "getRepositoryCloneUrls",
130 cwd: "/workspace",
131 repository: "octocat/t3code",
132 detail: "credential token abc123 was rejected",
133 });
134 const provider = makeProvider({
135 getRepositoryCloneUrls: () => Effect.fail(providerCause),
136 });
137
138 return Effect.gen(function* () {
139 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
140 const error = yield* Effect.flip(
141 service.lookupRepository({
142 provider: "github",
143 repository: "octocat/t3code",
144 cwd: "/workspace",
145 }),
146 );
147
148 assert.strictEqual(error.provider, "github");
149 assert.strictEqual(error.operation, "lookupRepository");
150 assert.strictEqual(error.detail, "The source control operation could not be completed.");
151 assert.strictEqual(
152 error.message,
153 "Source control repository operation lookupRepository failed for github: The source control operation could not be completed.",
154 );
155 assert.strictEqual(error.cause, providerCause);
156 }).pipe(Effect.provide(makeLayer({ provider })));
157});
158
159it.effect("clones a looked-up repository into the requested destination", () =>
160 Effect.gen(function* () {
161 const fs = yield* FileSystem.FileSystem;
162 const path = yield* Path.Path;
163 const parent = yield* fs.makeTempDirectoryScoped({
164 prefix: "t3-source-control-clone-parent-",
165 });
166 const destinationPath = path.join(parent, "t3code");
167 const cloneCalls: Array<{ cwd: string; args: ReadonlyArray<string> }> = [];
168
169 yield* Effect.gen(function* () {
170 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
171 const result = yield* service.cloneRepository({
172 provider: "github",
173 repository: "octocat/t3code",
174 destinationPath,
175 protocol: "https",
176 });
177
178 assert.deepStrictEqual(result, {
179 cwd: destinationPath,
180 remoteUrl: CLONE_URLS.url,
181 repository: { provider: "github", ...CLONE_URLS },
182 });
183 assert.deepStrictEqual(cloneCalls, [
184 {
185 cwd: parent,
186 args: ["clone", CLONE_URLS.url, "t3code"],
187 },
188 ]);
189 }).pipe(
190 Effect.provide(
191 makeLayer({
192 git: {
193 execute: (input) =>
194 Effect.sync(() => {
195 cloneCalls.push({ cwd: input.cwd, args: input.args });
196 return processOutput();
197 }),
198 },
199 }),
200 ),
201 );
202 }).pipe(Effect.provide(NodeServices.layer)),
203);
204
205it.effect("allows a clone to finish after more than two minutes", () =>
206 Effect.gen(function* () {
207 const fs = yield* FileSystem.FileSystem;
208 const parent = yield* fs.makeTempDirectoryScoped();
209 const path = yield* Path.Path;
210 const destinationPath = path.join(parent, "t3code");
211 const started = yield* Deferred.make<void>();
212 const git = yield* GitVcsDriver.make.pipe(
213 Effect.provideService(
214 ChildProcessSpawner.ChildProcessSpawner,
215 ChildProcessSpawner.make(() =>
216 Effect.succeed(
217 ChildProcessSpawner.makeHandle({
218 pid: ChildProcessSpawner.ProcessId(1),
219 exitCode: Deferred.succeed(started, undefined).pipe(
220 Effect.andThen(Effect.sleep("3 minutes")),
221 Effect.as(ChildProcessSpawner.ExitCode(0)),
222 ),
223 isRunning: Effect.succeed(true),
224 kill: () => Effect.void,
225 unref: Effect.succeed(Effect.void),
226 stdin: Sink.drain,
227 stdout: Stream.empty,
228 stderr: Stream.empty,
229 all: Stream.empty,
230 getInputFd: () => Sink.drain,
231 getOutputFd: () => Stream.empty,
232 }),
233 ),
234 ),
235 ),
236 );
237 const clone = yield* Effect.gen(function* () {
238 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
239 return yield* service.cloneRepository({ remoteUrl: CLONE_URLS.sshUrl, destinationPath });
240 }).pipe(Effect.provide(makeLayer({ git })), Effect.forkChild);
241
242 yield* Deferred.await(started);
243 yield* TestClock.adjust("3 minutes");
244 assert.deepStrictEqual(yield* Fiber.join(clone), {
245 cwd: destinationPath,
246 remoteUrl: CLONE_URLS.sshUrl,
247 repository: null,
248 });
249 }).pipe(
250 Effect.provide(
251 ServerConfig.layerTest(process.cwd(), { prefix: "t3-clone-timeout-" }).pipe(
252 Layer.provideMerge(NodeServices.layer),
253 ),
254 ),
255 ),
256);
257
258it.effect("preserves destination probe failures instead of treating them as missing paths", () => {
259 const fileSystemCause = PlatformError.systemError({
260 _tag: "PermissionDenied",
261 module: "FileSystem",
262 method: "exists",
263 pathOrDescriptor: "/restricted/t3code",
264 });
265
266 return Effect.gen(function* () {
267 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
268 const error = yield* Effect.flip(
269 service.cloneRepository({
270 remoteUrl: CLONE_URLS.sshUrl,
271 destinationPath: "/restricted/t3code",
272 }),
273 );
274
275 assert.strictEqual(error.provider, "unknown");
276 assert.strictEqual(error.operation, "cloneRepository");
277 assert.strictEqual(error.cause, fileSystemCause);
278 }).pipe(
279 Effect.provide(
280 makeLayer({
281 fileSystem: FileSystem.makeNoop({
282 exists: () => Effect.fail(fileSystemCause),
283 makeDirectory: () => Effect.void,
284 }),
285 }),
286 ),
287 );
288});
289
290it.effect("publishes by creating the repository, adding a remote, and pushing upstream", () => {
291 const createCalls: Array<{ cwd: string; repository: string; visibility: string }> = [];
292 const remoteCalls: Array<{ cwd: string; preferredName: string; url: string }> = [];
293 const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
294 const provider = makeProvider({
295 createRepository: (input) =>
296 Effect.sync(() => {
297 createCalls.push({
298 cwd: input.cwd,
299 repository: input.repository,
300 visibility: input.visibility,
301 });
302 return CLONE_URLS;
303 }),
304 });
305
306 return Effect.gen(function* () {
307 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
308 const result = yield* service.publishRepository({
309 cwd: "/workspace",
310 provider: "github",
311 repository: "octocat/t3code",
312 visibility: "private",
313 remoteName: "origin",
314 protocol: "ssh",
315 });
316
317 assert.deepStrictEqual(result, {
318 repository: { provider: "github", ...CLONE_URLS },
319 remoteName: "origin",
320 remoteUrl: CLONE_URLS.sshUrl,
321 branch: "feature/remote-v1",
322 upstreamBranch: "origin/feature/remote-v1",
323 status: "pushed",
324 });
325 assert.deepStrictEqual(createCalls, [
326 { cwd: "/workspace", repository: "octocat/t3code", visibility: "private" },
327 ]);
328 assert.deepStrictEqual(remoteCalls, [
329 { cwd: "/workspace", preferredName: "origin", url: CLONE_URLS.sshUrl },
330 ]);
331 assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin" }]);
332 }).pipe(
333 Effect.provide(
334 makeLayer({
335 provider,
336 git: {
337 ensureRemote: (input) =>
338 Effect.sync(() => {
339 remoteCalls.push(input);
340 return "origin";
341 }),
342 pushCurrentBranch: (cwd, _fallbackBranch, options) =>
343 Effect.sync(() => {
344 pushCalls.push({ cwd, remoteName: options?.remoteName });
345 return {
346 status: "pushed" as const,
347 branch: "feature/remote-v1",
348 upstreamBranch: "origin/feature/remote-v1",
349 setUpstream: true,
350 };
351 }),
352 },
353 }),
354 ),
355 );
356});
357
358it.effect("publishes to the remote name returned by ensureRemote", () => {
359 const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
360
361 return Effect.gen(function* () {
362 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
363 const result = yield* service.publishRepository({
364 cwd: "/workspace",
365 provider: "github",
366 repository: "octocat/t3code",
367 visibility: "private",
368 remoteName: "origin",
369 protocol: "ssh",
370 });
371
372 assert.equal(result.remoteName, "origin-1");
373 assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin-1" }]);
374 }).pipe(
375 Effect.provide(
376 makeLayer({
377 git: {
378 ensureRemote: () => Effect.succeed("origin-1"),
379 pushCurrentBranch: (cwd, _fallbackBranch, options) =>
380 Effect.sync(() => {
381 pushCalls.push({ cwd, remoteName: options?.remoteName });
382 return {
383 status: "pushed" as const,
384 branch: "feature/remote-v1",
385 upstreamBranch: `${options?.remoteName ?? "missing"}/feature/remote-v1`,
386 setUpstream: true,
387 };
388 }),
389 },
390 }),
391 ),
392 );
393});
394
395it.effect("publish succeeds with status remote_added when the local repo has no commits", () => {
396 let pushCalls = 0;
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: "main",
413 status: "remote_added",
414 });
415 assert.strictEqual(pushCalls, 0);
416 }).pipe(
417 Effect.provide(
418 makeLayer({
419 git: {
420 execute: (input) =>
421 input.args[0] === "rev-parse"
422 ? Effect.fail(
423 new GitCommandError({
424 operation: input.operation,
425 command: "git rev-parse --verify HEAD",
426 cwd: input.cwd,
427 detail: "fatal: Needed a single revision",
428 }),
429 )
430 : Effect.succeed(processOutput()),
431 statusDetails: () =>
432 Effect.succeed({
433 isRepo: true,
434 hasOriginRemote: true,
435 isDefaultBranch: true,
436 branch: "main",
437 upstreamRef: null,
438 hasWorkingTreeChanges: false,
439 workingTree: { files: [], insertions: 0, deletions: 0 },
440 hasUpstream: false,
441 aheadCount: 0,
442 behindCount: 0,
443 aheadOfDefaultCount: 0,
444 }),
445 pushCurrentBranch: () =>
446 Effect.sync(() => {
447 pushCalls += 1;
448 return {
449 status: "pushed" as const,
450 branch: "main",
451 upstreamBranch: "origin/main",
452 setUpstream: true,
453 };
454 }),
455 },
456 }),
457 ),
458 );
459});