Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SourceControlRepositoryService.test.ts

401 lines13.2 KB

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 "@v12/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/v12",
20 url: "https://github.com/octocat/v12",
21 sshUrl: "git@github.com:octocat/v12.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 };
45​
46function processOutput(): GitVcsDriver.ExecuteGitResult {
47 return {
48 exitCode: ChildProcessSpawner.ExitCode(0),
49 stdout: "",
50 stderr: "",
51 stdoutTruncated: false,
52 stderrTruncated: false,
53 };
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
85 ? "/tmp/v12-source-control-repos"
86 : { prefix: "v12-source-control-repos-" },
87 ),
88 ),
89 );
90​
91 return input.fileSystem
92 ? serviceLayer.pipe(
93 Layer.provide(Layer.succeed(FileSystem.FileSystem, input.fileSystem)),
94 Layer.provideMerge(NodePath.layer),
95 )
96 : serviceLayer.pipe(Layer.provideMerge(NodeServices.layer));
98​
99it.effect("looks up repositories through the requested provider without search", () => {
100 const calls: Array<{ cwd: string; repository: string }> = [];
101 const provider = makeProvider({
102 getRepositoryCloneUrls: (input) =>
103 Effect.sync(() => {
104 calls.push({ cwd: input.cwd, repository: input.repository });
105 return CLONE_URLS;
106 }),
107 });
108​
109 return Effect.gen(function* () {
110 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
111 const result = yield* service.lookupRepository({
112 provider: "github",
113 repository: "octocat/v12",
114 cwd: "/workspace",
115 });
116​
117 assert.deepStrictEqual(result, { provider: "github", ...CLONE_URLS });
118 assert.deepStrictEqual(calls, [{ cwd: "/workspace", repository: "octocat/v12" }]);
119 }).pipe(Effect.provide(makeLayer({ provider })));
120});
121​
122it.effect("preserves provider failures without deriving the repository message from them", () => {
123 const providerCause = new SourceControlProviderError({
124 provider: "github",
125 operation: "getRepositoryCloneUrls",
126 cwd: "/workspace",
127 repository: "octocat/v12",
128 detail: "credential token abc123 was rejected",
129 });
130 const provider = makeProvider({
131 getRepositoryCloneUrls: () => Effect.fail(providerCause),
132 });
133​
134 return Effect.gen(function* () {
135 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
136 const error = yield* Effect.flip(
137 service.lookupRepository({
138 provider: "github",
139 repository: "octocat/v12",
140 cwd: "/workspace",
141 }),
142 );
143​
144 assert.strictEqual(error.provider, "github");
145 assert.strictEqual(error.operation, "lookupRepository");
146 assert.strictEqual(error.detail, "The source control operation could not be completed.");
147 assert.strictEqual(
148 error.message,
149 "Source control repository operation lookupRepository failed for github: The source control operation could not be completed.",
150 );
151 assert.strictEqual(error.cause, providerCause);
152 }).pipe(Effect.provide(makeLayer({ provider })));
153});
154​
155it.effect("clones a looked-up repository into the requested destination", () =>
156 Effect.gen(function* () {
157 const fs = yield* FileSystem.FileSystem;
158 const parent = yield* fs.makeTempDirectoryScoped({
159 prefix: "v12-source-control-clone-parent-",
160 });
161 const destinationPath = `${parent}/v12`;
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/v12",
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, "v12"],
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/v12",
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/v12",
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/v12",
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/v12", 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/v12",
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/v12",
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});