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