Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import { assert, it } from "@effect/vitest";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Path from "effect/Path";
9import * as Schema from "effect/Schema";
10import { ChildProcessSpawner } from "effect/process";
11import { HttpClient } from "effect/http";
12import { VcsProcessSpawnError } from "@t3tools/contracts";
13
14import * as ServerSettings from "../serverSettings.ts";
15import * as ServerConfig from "../config.ts";
16import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
17import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
18import * as VcsProcess from "../vcs/VcsProcess.ts";
19import * as AzureDevOpsCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsCli";
20import * as AzureDevOpsPullRequestCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsPullRequestCli";
21import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi";
22import * as BitbucketPullRequestApi from "@t3tools/source-control-bitbucket/server/BitbucketPullRequestApi";
23import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest";
24import * as GitHubRequestPolicy from "@t3tools/source-control-github/server/GitHubRequestPolicy";
25import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi";
26import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli";
27import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/GitLabPullRequestCli";
28import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
29import * as GitCafeApi from "@t3tools/source-control-gitcafe/server/GitCafeApi";
30import * as GitCafeCredentials from "@t3tools/source-control-gitcafe/server/GitCafeCredentials";
31import * as ForgejoSourceControlProvider from "@t3tools/source-control-forgejo/server/ForgejoSourceControlProvider";
32import * as SourceControlDiscovery from "./SourceControlDiscovery.ts";
33import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
34import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
35import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
36
37const layerSourceControlProviderRegistryTest = (input: {
38 readonly bitbucket: Partial<BitbucketApi.BitbucketApi["Service"]>;
39 readonly process: Partial<VcsProcess.VcsProcess["Service"]>;
40}) =>
41 SourceControlProviderRegistry.layer.pipe(
42 Layer.provide(
43 Layer.mergeAll(
44 ServerConfig.layerTest(process.cwd(), {
45 prefix: "t3-source-control-registry-test-",
46 }).pipe(Layer.provide(NodeServices.layer)),
47 Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
48 Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({}),
49 Layer.mock(BitbucketApi.BitbucketApi)(input.bitbucket),
50 Layer.mock(BitbucketPullRequestApi.BitbucketPullRequestApi)({}),
51 ServerSettings.ServerSettingsService.layerTest(),
52 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({}),
53 Layer.mock(GitHubRest.GitHubRest)({}),
54 // The GitHub provider's GraphQL reads go through these; no test here makes one.
55 Layer.mock(GitHubRequestPolicy.GitHubRequestPolicy)({}),
56 Layer.succeed(
57 HttpClient.HttpClient,
58 HttpClient.make(() => Effect.die(new Error("Unexpected GitHub GraphQL read"))),
59 ),
60 Layer.mock(GitVcsDriver.GitVcsDriver)({}),
61 Layer.mock(GitLabCli.GitLabCli)({}),
62 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({}),
63 Layer.mock(ForgejoCli.ForgejoCli)({ listLogins: () => Effect.succeed([]) }),
64 Layer.mock(GitCafeApi.GitCafeApi)({}),
65 Layer.mock(GitCafeCredentials.GitCafeCredentials)({
66 cliEnv: () => Effect.succeed({}),
67 }),
68 Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({}),
69 Layer.mock(VcsProcess.VcsProcess)(input.process),
70 ServerSourceControlHost.layer.pipe(
71 Layer.provide(
72 Layer.mergeAll(
73 Layer.mock(VcsProcess.VcsProcess)(input.process),
74 ServerSettings.ServerSettingsService.layerTest(),
75 Layer.mock(GitVcsDriver.GitVcsDriver)({}),
76 Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({}),
77 ),
78 ),
79 ),
80 ),
81 ),
82 );
83
84const processOutput = (
85 stdout: string,
86 options?: {
87 readonly stderr?: string;
88 readonly exitCode?: ChildProcessSpawner.ExitCode;
89 },
90): VcsProcess.VcsProcessOutput => ({
91 exitCode: options?.exitCode ?? ChildProcessSpawner.ExitCode(0),
92 stdout,
93 stderr: options?.stderr ?? "",
94 stdoutTruncated: false,
95 stderrTruncated: false,
96});
97
98const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
99
100it.effect("probes provider authentication without exposing token details", () => {
101 const processMock = {
102 run: (input: VcsProcess.VcsProcessInput) => {
103 if (input.args[0] === "--version") {
104 return Effect.succeed(processOutput(`${input.command} version test\n`));
105 }
106 if (input.command === "gh" && input.args.join(" ") === "auth status --json hosts") {
107 return Effect.succeed(
108 processOutput(
109 encodeJson({
110 hosts: {
111 "github.com": [
112 {
113 state: "success",
114 active: true,
115 host: "github.com",
116 login: "octocat",
117 tokenSource: "keyring",
118 gitProtocol: "ssh",
119 },
120 ],
121 },
122 }),
123 ),
124 );
125 }
126 if (input.command === "glab" && input.args.join(" ") === "auth status") {
127 return Effect.succeed(
128 processOutput(`gitlab.com
129Logged in to gitlab.com as gitlab-user
130`),
131 );
132 }
133 if (input.command === "tea" && input.args[0] === "login") {
134 return Effect.succeed(
135 processOutput(
136 encodeJson([
137 {
138 name: "forgejo",
139 url: "https://forgejo.example.com",
140 ssh_host: "forgejo.example.com",
141 user: "forgejo-user",
142 valid: "true",
143 default: "true",
144 },
145 ]),
146 ),
147 );
148 }
149 if (
150 input.command === "az" &&
151 input.args.join(" ") === "account show --query user.name -o tsv"
152 ) {
153 return Effect.succeed(processOutput("azure-user@example.com\n"));
154 }
155 if (input.command === "cafe" && input.args.slice(-3).join(" ") === "auth status --json") {
156 return Effect.succeed(
157 processOutput(
158 encodeJson({ schemaVersion: 1, data: { host: "git.cafe", username: "cafe-user" } }),
159 ),
160 );
161 }
162 return Effect.fail(
163 new VcsProcessSpawnError({
164 operation: input.operation,
165 command: input.command,
166 cwd: input.cwd,
167 cause: new Error(`${input.command} not found`),
168 }),
169 );
170 },
171 } satisfies Partial<VcsProcess.VcsProcess["Service"]>;
172 const layerTest = SourceControlDiscovery.layer.pipe(
173 Layer.provide(
174 ServerConfig.layerTest(process.cwd(), {
175 prefix: "t3-source-control-auth-discovery-",
176 }),
177 ),
178 Layer.provide(Layer.mock(VcsProcess.VcsProcess)(processMock)),
179 Layer.provide(
180 layerSourceControlProviderRegistryTest({
181 process: processMock,
182 bitbucket: {
183 probeAuth: Effect.succeed({
184 status: "authenticated",
185 account: Option.some("bitbucket-user"),
186 host: Option.some("bitbucket.org"),
187 detail: Option.none(),
188 }),
189 },
190 }),
191 ),
192 Layer.provideMerge(NodeServices.layer),
193 );
194
195 return Effect.gen(function* () {
196 const discovery = yield* SourceControlDiscovery.SourceControlDiscovery;
197 const result = yield* discovery.discover;
198
199 assert.deepStrictEqual(
200 result.sourceControlProviders.map((item) => ({
201 kind: item.kind,
202 auth: item.auth.status,
203 account: item.auth.account,
204 detail: item.auth.detail,
205 })),
206 [
207 {
208 kind: SourceControlProviderKind.make("github"),
209 auth: "authenticated",
210 account: Option.some("octocat"),
211 detail: Option.none(),
212 },
213 {
214 kind: SourceControlProviderKind.make("gitlab"),
215 auth: "authenticated",
216 account: Option.some("gitlab-user"),
217 detail: Option.none(),
218 },
219 {
220 kind: SourceControlProviderKind.make("azure-devops"),
221 auth: "authenticated",
222 account: Option.some("azure-user@example.com"),
223 detail: Option.none(),
224 },
225 {
226 kind: SourceControlProviderKind.make("bitbucket"),
227 auth: "authenticated",
228 account: Option.some("bitbucket-user"),
229 detail: Option.none(),
230 },
231 {
232 kind: SourceControlProviderKind.make("forgejo"),
233 auth: "authenticated",
234 account: Option.some("forgejo-user"),
235 detail: Option.none(),
236 },
237 {
238 kind: SourceControlProviderKind.make("gitcafe"),
239 auth: "authenticated",
240 account: Option.some("cafe-user"),
241 detail: Option.none(),
242 },
243 ],
244 );
245 }).pipe(Effect.provide(layerTest));
246});
247
248it.effect(
249 "checks out fj pull refs and preserves existing branches and dirty files until forced",
250 () =>
251 Effect.gen(function* () {
252 const fs = yield* FileSystem.FileSystem;
253 const git = yield* VcsProcess.VcsProcess;
254 const path = yield* Path.Path;
255 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-fj-checkout-" });
256 const source = path.join(root, "source");
257 const cwd = path.join(root, "checkout");
258 yield* fs.makeDirectory(source);
259 for (const args of [
260 ["init", "-b", "main"],
261 ["config", "user.name", "Test"],
262 ["config", "user.email", "test@example.com"],
263 ])
264 yield* git.run({ operation: "test.setup", command: "git", cwd: source, args });
265 yield* fs.writeFileString(path.join(source, "base.txt"), "base\n");
266 for (const args of [
267 ["add", "base.txt"],
268 ["commit", "-m", "base"],
269 ])
270 yield* git.run({ operation: "test.setup", command: "git", cwd: source, args });
271 const base = (yield* git.run({
272 operation: "test.setup",
273 command: "git",
274 cwd: source,
275 args: ["rev-parse", "HEAD"],
276 })).stdout.trim();
277 yield* git.run({
278 operation: "test.setup",
279 command: "git",
280 cwd: root,
281 args: ["clone", source, cwd],
282 });
283 yield* fs.writeFileString(path.join(source, "feature.txt"), "pull request change\n");
284 for (const args of [
285 ["add", "feature.txt"],
286 ["commit", "-m", "feature"],
287 ["update-ref", "refs/pull/42/head", "HEAD"],
288 ])
289 yield* git.run({ operation: "test.setup", command: "git", cwd: source, args });
290 const head = (yield* git.run({
291 operation: "test.setup",
292 command: "git",
293 cwd: source,
294 args: ["rev-parse", "HEAD"],
295 })).stdout.trim();
296 const fetched: string[] = [];
297 const host = yield* SourceControlHost.SourceControlHost;
298 const provider = yield* ForgejoSourceControlProvider.make.pipe(
299 Effect.provideService(
300 SourceControlHost.SourceControlHost,
301 SourceControlHost.SourceControlHost.of({
302 settings: host.settings,
303 git: host.git,
304 process: {
305 run: (input) => {
306 if (input.args[0] !== "fetch") return git.run(input);
307 const url = input.args[2];
308 assert.isDefined(url);
309 fetched.push(url!);
310 return git.run({
311 ...input,
312 args: input.args.map((arg) =>
313 arg === "git@forgejo.test:reviewer/project.git" ? source : arg,
314 ),
315 });
316 },
317 },
318 }),
319 ),
320 Effect.provide(
321 Layer.mock(ForgejoCli.ForgejoCli)({
322 resolveRepository: () =>
323 Effect.succeed({
324 command: "fj",
325 login: "work",
326 repository: "reviewer/project",
327 baseUrl: "https://forgejo.test",
328 }),
329 api: (input) => {
330 assert.include(
331 ["repos/reviewer/project", "repos/reviewer/project/pulls/42"],
332 input.path,
333 );
334 return Effect.succeed(
335 processOutput(
336 encodeJson(
337 input.path.endsWith("/pulls/42")
338 ? {
339 number: 42,
340 title: "Checkout",
341 html_url: "https://forgejo.test/reviewer/project/pulls/42",
342 state: "open",
343 merged: false,
344 base: { ref: "main", sha: base, repo: null },
345 head: { ref: "feature", sha: head, repo: null },
346 }
347 : {
348 full_name: "reviewer/project",
349 clone_url: source,
350 ssh_url: "git@forgejo.test:reviewer/project.git",
351 default_branch: "main",
352 },
353 ),
354 ),
355 );
356 },
357 }),
358 ),
359 );
360 yield* provider.checkoutChangeRequest({
361 cwd,
362 reference: "https://forgejo.test/reviewer/project/pulls/42",
363 });
364 assert.strictEqual(
365 (yield* git.run({
366 operation: "test.verify",
367 command: "git",
368 cwd,
369 args: ["branch", "--show-current"],
370 })).stdout.trim(),
371 "pulls/42",
372 );
373 assert.strictEqual(
374 (yield* git.run({
375 operation: "test.verify",
376 command: "git",
377 cwd,
378 args: ["rev-parse", "HEAD"],
379 })).stdout.trim(),
380 head,
381 );
382 assert.strictEqual(
383 yield* fs.readFileString(path.join(cwd, "feature.txt")),
384 "pull request change\n",
385 );
386 for (const args of [
387 ["checkout", "main"],
388 ["branch", "-f", "pulls/42", "main"],
389 ])
390 yield* git.run({ operation: "test.setup", command: "git", cwd, args });
391 yield* fs.writeFileString(path.join(cwd, "base.txt"), "uncommitted work\n");
392 yield* provider.checkoutChangeRequest({ cwd, reference: "42" });
393 assert.strictEqual(
394 (yield* git.run({
395 operation: "test.verify",
396 command: "git",
397 cwd,
398 args: ["rev-parse", "HEAD"],
399 })).stdout.trim(),
400 base,
401 );
402 assert.strictEqual(yield* fs.exists(path.join(cwd, "feature.txt")), false);
403 yield* provider.checkoutChangeRequest({
404 cwd,
405 reference: "42",
406 force: true,
407 context: {
408 provider: {
409 kind: SourceControlProviderKind.make("forgejo"),
410 name: "Forgejo",
411 baseUrl: "https://forgejo.test",
412 },
413 remoteName: "origin",
414 remoteUrl: "git@forgejo.test:maria/project.git",
415 },
416 });
417 assert.strictEqual(
418 (yield* git.run({
419 operation: "test.verify",
420 command: "git",
421 cwd,
422 args: ["rev-parse", "HEAD"],
423 })).stdout.trim(),
424 head,
425 );
426 assert.strictEqual(
427 yield* fs.readFileString(path.join(cwd, "base.txt")),
428 "uncommitted work\n",
429 );
430 assert.strictEqual(
431 yield* fs.readFileString(path.join(cwd, "feature.txt")),
432 "pull request change\n",
433 );
434 assert.deepStrictEqual(fetched, [source, source, "git@forgejo.test:reviewer/project.git"]);
435 }).pipe(
436 Effect.scoped,
437 Effect.provide(
438 ServerSourceControlHost.layer.pipe(
439 Layer.provideMerge(VcsProcess.layer),
440 Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
441 Layer.provideMerge(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
442 Layer.provideMerge(Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({})),
443 Layer.provideMerge(NodeServices.layer),
444 ),
445 ),
446 ),
447);