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", 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("preserves destination probe failures instead of treating them as missing paths", () => {
201 const fileSystemCause = PlatformError.systemError({
202 _tag: "PermissionDenied",
203 module: "FileSystem",
204 method: "exists",
205 pathOrDescriptor: "/restricted/t3code",
206 });
207
208 return Effect.gen(function* () {
209 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
210 const error = yield* Effect.flip(
211 service.cloneRepository({
212 remoteUrl: CLONE_URLS.sshUrl,
213 destinationPath: "/restricted/t3code",
214 }),
215 );
216
217 assert.strictEqual(error.provider, "unknown");
218 assert.strictEqual(error.operation, "cloneRepository");
219 assert.strictEqual(error.cause, fileSystemCause);
220 }).pipe(
221 Effect.provide(
222 makeLayer({
223 fileSystem: FileSystem.makeNoop({
224 exists: () => Effect.fail(fileSystemCause),
225 makeDirectory: () => Effect.void,
226 }),
227 }),
228 ),
229 );
230});
231
232it.effect("publishes by creating the repository, adding a remote, and pushing upstream", () => {
233 const createCalls: Array<{ cwd: string; repository: string; visibility: string }> = [];
234 const remoteCalls: Array<{ cwd: string; preferredName: string; url: string }> = [];
235 const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
236 const provider = makeProvider({
237 createRepository: (input) =>
238 Effect.sync(() => {
239 createCalls.push({
240 cwd: input.cwd,
241 repository: input.repository,
242 visibility: input.visibility,
243 });
244 return CLONE_URLS;
245 }),
246 });
247
248 return Effect.gen(function* () {
249 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
250 const result = yield* service.publishRepository({
251 cwd: "/workspace",
252 provider: "github",
253 repository: "octocat/t3code",
254 visibility: "private",
255 remoteName: "origin",
256 protocol: "ssh",
257 });
258
259 assert.deepStrictEqual(result, {
260 repository: { provider: "github", ...CLONE_URLS },
261 remoteName: "origin",
262 remoteUrl: CLONE_URLS.sshUrl,
263 branch: "feature/remote-v1",
264 upstreamBranch: "origin/feature/remote-v1",
265 status: "pushed",
266 });
267 assert.deepStrictEqual(createCalls, [
268 { cwd: "/workspace", repository: "octocat/t3code", visibility: "private" },
269 ]);
270 assert.deepStrictEqual(remoteCalls, [
271 { cwd: "/workspace", preferredName: "origin", url: CLONE_URLS.sshUrl },
272 ]);
273 assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin" }]);
274 }).pipe(
275 Effect.provide(
276 makeLayer({
277 provider,
278 git: {
279 ensureRemote: (input) =>
280 Effect.sync(() => {
281 remoteCalls.push(input);
282 return "origin";
283 }),
284 pushCurrentBranch: (cwd, _fallbackBranch, options) =>
285 Effect.sync(() => {
286 pushCalls.push({ cwd, remoteName: options?.remoteName });
287 return {
288 status: "pushed" as const,
289 branch: "feature/remote-v1",
290 upstreamBranch: "origin/feature/remote-v1",
291 setUpstream: true,
292 };
293 }),
294 },
295 }),
296 ),
297 );
298});
299
300it.effect("publishes to the remote name returned by ensureRemote", () => {
301 const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
302
303 return Effect.gen(function* () {
304 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
305 const result = yield* service.publishRepository({
306 cwd: "/workspace",
307 provider: "github",
308 repository: "octocat/t3code",
309 visibility: "private",
310 remoteName: "origin",
311 protocol: "ssh",
312 });
313
314 assert.equal(result.remoteName, "origin-1");
315 assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin-1" }]);
316 }).pipe(
317 Effect.provide(
318 makeLayer({
319 git: {
320 ensureRemote: () => Effect.succeed("origin-1"),
321 pushCurrentBranch: (cwd, _fallbackBranch, options) =>
322 Effect.sync(() => {
323 pushCalls.push({ cwd, remoteName: options?.remoteName });
324 return {
325 status: "pushed" as const,
326 branch: "feature/remote-v1",
327 upstreamBranch: `${options?.remoteName ?? "missing"}/feature/remote-v1`,
328 setUpstream: true,
329 };
330 }),
331 },
332 }),
333 ),
334 );
335});
336
337it.effect("publish succeeds with status remote_added when the local repo has no commits", () => {
338 let pushCalls = 0;
339 return Effect.gen(function* () {
340 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
341 const result = yield* service.publishRepository({
342 cwd: "/workspace",
343 provider: "github",
344 repository: "octocat/t3code",
345 visibility: "private",
346 remoteName: "origin",
347 protocol: "ssh",
348 });
349
350 assert.deepStrictEqual(result, {
351 repository: { provider: "github", ...CLONE_URLS },
352 remoteName: "origin",
353 remoteUrl: CLONE_URLS.sshUrl,
354 branch: "main",
355 status: "remote_added",
356 });
357 assert.strictEqual(pushCalls, 0);
358 }).pipe(
359 Effect.provide(
360 makeLayer({
361 git: {
362 execute: (input) =>
363 input.args[0] === "rev-parse"
364 ? Effect.fail(
365 new GitCommandError({
366 operation: input.operation,
367 command: "git rev-parse --verify HEAD",
368 cwd: input.cwd,
369 detail: "fatal: Needed a single revision",
370 }),
371 )
372 : Effect.succeed(processOutput()),
373 statusDetails: () =>
374 Effect.succeed({
375 isRepo: true,
376 hasOriginRemote: true,
377 isDefaultBranch: true,
378 branch: "main",
379 upstreamRef: null,
380 hasWorkingTreeChanges: false,
381 workingTree: { files: [], insertions: 0, deletions: 0 },
382 hasUpstream: false,
383 aheadCount: 0,
384 behindCount: 0,
385 aheadOfDefaultCount: 0,
386 }),
387 pushCurrentBranch: () =>
388 Effect.sync(() => {
389 pushCalls += 1;
390 return {
391 status: "pushed" as const,
392 branch: "main",
393 upstreamBranch: "origin/main",
394 setUpstream: true,
395 };
396 }),
397 },
398 }),
399 ),
400 );
401});