Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as Effect from "effect/Effect";
4import type * as Context from "effect/Context";
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 { FetchHttpClient, HttpClient, HttpClientResponse } 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 GitHubApi from "@t3tools/source-control-github/server/GitHubApi";
24import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi";
25import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli";
26import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/GitLabPullRequestCli";
27import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
28import * as GitCafeApi from "@t3tools/source-control-gitcafe/server/GitCafeApi";
29import * as ForgejoSourceControlProvider from "@t3tools/source-control-forgejo/server/ForgejoSourceControlProvider";
30import * as ForgejoPullRequestProvider from "@t3tools/source-control-forgejo/server/ForgejoPullRequestProvider";
31import * as SourceControlDiscovery from "./SourceControlDiscovery.ts";
32import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
33import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
34import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
35
36const layerSourceControlProviderRegistryTest = (input: {
37 readonly bitbucket: Partial<BitbucketApi.BitbucketApi["Service"]>;
38 readonly process: Partial<VcsProcess.VcsProcess["Service"]>;
39}) =>
40 SourceControlProviderRegistry.layer.pipe(
41 Layer.provide(
42 Layer.mergeAll(
43 ServerConfig.layerTest(process.cwd(), {
44 prefix: "t3-source-control-registry-test-",
45 }).pipe(Layer.provide(NodeServices.layer)),
46 Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
47 Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({}),
48 Layer.mock(BitbucketApi.BitbucketApi)(input.bitbucket),
49 Layer.mock(BitbucketPullRequestApi.BitbucketPullRequestApi)({}),
50 ServerSettings.ServerSettingsService.layerTest(),
51 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({}),
52 Layer.mock(GitHubApi.GitHubApi)({}),
53 Layer.mock(GitVcsDriver.GitVcsDriver)({}),
54 Layer.mock(GitLabCli.GitLabCli)({}),
55 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({}),
56 Layer.mock(ForgejoCli.ForgejoCli)({ listLogins: () => Effect.succeed([]) }),
57 Layer.mock(GitCafeApi.GitCafeApi)({}),
58 Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({}),
59 Layer.mock(VcsProcess.VcsProcess)(input.process),
60 ServerSourceControlHost.layer.pipe(
61 Layer.provide(
62 Layer.mergeAll(
63 Layer.mock(VcsProcess.VcsProcess)(input.process),
64 ServerSettings.ServerSettingsService.layerTest(),
65 Layer.mock(GitVcsDriver.GitVcsDriver)({}),
66 Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({}),
67 ),
68 ),
69 ),
70 ),
71 ),
72 );
73
74const processOutput = (
75 stdout: string,
76 options?: {
77 readonly stderr?: string;
78 readonly exitCode?: ChildProcessSpawner.ExitCode;
79 },
80): VcsProcess.VcsProcessOutput => ({
81 exitCode: options?.exitCode ?? ChildProcessSpawner.ExitCode(0),
82 stdout,
83 stderr: options?.stderr ?? "",
84 stdoutTruncated: false,
85 stderrTruncated: false,
86});
87
88const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
89const encodeJsonEffect = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
90
91it.effect("reports implemented tools separately from locally available executables", () => {
92 const processMock = {
93 run: (input: VcsProcess.VcsProcessInput) => {
94 if (input.command === "git") {
95 return Effect.succeed(processOutput("git version 2.51.0\n"));
96 }
97 if (input.command === "gh" && input.args[0] === "--version") {
98 return Effect.succeed(processOutput("gh version 2.83.0\n"));
99 }
100 if (input.command === "gh" && input.args.join(" ") === "auth status --json hosts") {
101 return Effect.succeed(
102 processOutput(
103 encodeJson({
104 hosts: {
105 "github.com": [
106 {
107 state: "success",
108 active: true,
109 host: "github.com",
110 login: "juliusmarminge",
111 tokenSource: "keyring",
112 gitProtocol: "ssh",
113 },
114 ],
115 },
116 }),
117 ),
118 );
119 }
120 return Effect.fail(
121 new VcsProcessSpawnError({
122 operation: input.operation,
123 command: input.command,
124 cwd: input.cwd,
125 cause: new Error(`${input.command} not found`),
126 }),
127 );
128 },
129 } satisfies Partial<VcsProcess.VcsProcess["Service"]>;
130 const layerTest = SourceControlDiscovery.layer.pipe(
131 Layer.provide(
132 ServerConfig.layerTest(process.cwd(), {
133 prefix: "t3-source-control-discovery-",
134 }),
135 ),
136 Layer.provide(Layer.mock(VcsProcess.VcsProcess)(processMock)),
137 Layer.provide(
138 layerSourceControlProviderRegistryTest({
139 process: processMock,
140 bitbucket: {
141 probeAuth: Effect.succeed({
142 status: "unauthenticated",
143 account: Option.none(),
144 host: Option.some("bitbucket.org"),
145 detail: Option.some(
146 "Add a Bitbucket token in Settings → Source Control, or set the T3CODE_BITBUCKET_* environment variables on the server.",
147 ),
148 }),
149 },
150 }),
151 ),
152 Layer.provideMerge(NodeServices.layer),
153 );
154
155 return Effect.gen(function* () {
156 const discovery = yield* SourceControlDiscovery.SourceControlDiscovery;
157 const result = yield* discovery.discover;
158
159 assert.deepStrictEqual(
160 result.versionControlSystems.map((item) => ({
161 kind: item.kind,
162 implemented: item.implemented,
163 status: item.status,
164 })),
165 [
166 { kind: "git", implemented: true, status: "available" },
167 { kind: "jj", implemented: false, status: "missing" },
168 ],
169 );
170 assert.deepStrictEqual(
171 result.sourceControlProviders.map((item) => ({
172 kind: item.kind,
173 status: item.status,
174 auth: item.auth.status,
175 account: item.auth.account,
176 })),
177 [
178 {
179 kind: "github",
180 status: "available",
181 auth: "authenticated",
182 account: Option.some("juliusmarminge"),
183 },
184 {
185 kind: "gitlab",
186 status: "missing",
187 auth: "unknown",
188 account: Option.none(),
189 },
190 {
191 kind: "azure-devops",
192 status: "missing",
193 auth: "unknown",
194 account: Option.none(),
195 },
196 {
197 kind: "bitbucket",
198 status: "available",
199 auth: "unauthenticated",
200 account: Option.none(),
201 },
202 {
203 kind: "forgejo",
204 status: "missing",
205 auth: "unknown",
206 account: Option.none(),
207 },
208 {
209 kind: "gitcafe",
210 status: "missing",
211 auth: "unknown",
212 account: Option.none(),
213 },
214 ],
215 );
216 const bitbucket = result.sourceControlProviders.find((item) => item.kind === "bitbucket");
217 assert.ok(bitbucket);
218 assert.strictEqual(bitbucket.executable, undefined);
219 }).pipe(Effect.provide(layerTest));
220});
221
222it.effect("probes provider authentication without exposing token details", () => {
223 const processMock = {
224 run: (input: VcsProcess.VcsProcessInput) => {
225 if (input.args[0] === "--version") {
226 return Effect.succeed(processOutput(`${input.command} version test\n`));
227 }
228 if (input.command === "gh" && input.args.join(" ") === "auth status --json hosts") {
229 return Effect.succeed(
230 processOutput(
231 encodeJson({
232 hosts: {
233 "github.com": [
234 {
235 state: "success",
236 active: true,
237 host: "github.com",
238 login: "octocat",
239 tokenSource: "keyring",
240 gitProtocol: "ssh",
241 },
242 ],
243 },
244 }),
245 ),
246 );
247 }
248 if (input.command === "glab" && input.args.join(" ") === "auth status") {
249 return Effect.succeed(
250 processOutput(`gitlab.com
251Logged in to gitlab.com as gitlab-user
252`),
253 );
254 }
255 if (input.command === "tea" && input.args[0] === "login") {
256 return Effect.succeed(
257 processOutput(
258 encodeJson([
259 {
260 name: "forgejo",
261 url: "https://forgejo.example.com",
262 ssh_host: "forgejo.example.com",
263 user: "forgejo-user",
264 valid: "true",
265 default: "true",
266 },
267 ]),
268 ),
269 );
270 }
271 if (
272 input.command === "az" &&
273 input.args.join(" ") === "account show --query user.name -o tsv"
274 ) {
275 return Effect.succeed(processOutput("azure-user@example.com\n"));
276 }
277 if (input.command === "cafe" && input.args.slice(-3).join(" ") === "auth status --json") {
278 return Effect.succeed(
279 processOutput(
280 encodeJson({ schemaVersion: 1, data: { host: "git.cafe", username: "cafe-user" } }),
281 ),
282 );
283 }
284 return Effect.fail(
285 new VcsProcessSpawnError({
286 operation: input.operation,
287 command: input.command,
288 cwd: input.cwd,
289 cause: new Error(`${input.command} not found`),
290 }),
291 );
292 },
293 } satisfies Partial<VcsProcess.VcsProcess["Service"]>;
294 const layerTest = SourceControlDiscovery.layer.pipe(
295 Layer.provide(
296 ServerConfig.layerTest(process.cwd(), {
297 prefix: "t3-source-control-auth-discovery-",
298 }),
299 ),
300 Layer.provide(Layer.mock(VcsProcess.VcsProcess)(processMock)),
301 Layer.provide(
302 layerSourceControlProviderRegistryTest({
303 process: processMock,
304 bitbucket: {
305 probeAuth: Effect.succeed({
306 status: "authenticated",
307 account: Option.some("bitbucket-user"),
308 host: Option.some("bitbucket.org"),
309 detail: Option.none(),
310 }),
311 },
312 }),
313 ),
314 Layer.provideMerge(NodeServices.layer),
315 );
316
317 return Effect.gen(function* () {
318 const discovery = yield* SourceControlDiscovery.SourceControlDiscovery;
319 const result = yield* discovery.discover;
320
321 assert.deepStrictEqual(
322 result.sourceControlProviders.map((item) => ({
323 kind: item.kind,
324 auth: item.auth.status,
325 account: item.auth.account,
326 detail: item.auth.detail,
327 })),
328 [
329 {
330 kind: "github",
331 auth: "authenticated",
332 account: Option.some("octocat"),
333 detail: Option.none(),
334 },
335 {
336 kind: "gitlab",
337 auth: "authenticated",
338 account: Option.some("gitlab-user"),
339 detail: Option.none(),
340 },
341 {
342 kind: "azure-devops",
343 auth: "authenticated",
344 account: Option.some("azure-user@example.com"),
345 detail: Option.none(),
346 },
347 {
348 kind: "bitbucket",
349 auth: "authenticated",
350 account: Option.some("bitbucket-user"),
351 detail: Option.none(),
352 },
353 {
354 kind: "forgejo",
355 auth: "authenticated",
356 account: Option.some("forgejo-user"),
357 detail: Option.none(),
358 },
359 {
360 kind: "gitcafe",
361 auth: "authenticated",
362 account: Option.some("cafe-user"),
363 detail: Option.none(),
364 },
365 ],
366 );
367 }).pipe(Effect.provide(layerTest));
368});
369
370it.effect(
371 "checks out fj pull refs and preserves existing branches and dirty files until forced",
372 () =>
373 Effect.gen(function* () {
374 const fs = yield* FileSystem.FileSystem;
375 const git = yield* VcsProcess.VcsProcess;
376 const path = yield* Path.Path;
377 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-fj-checkout-" });
378 const source = path.join(root, "source");
379 const cwd = path.join(root, "checkout");
380 yield* fs.makeDirectory(source);
381 for (const args of [
382 ["init", "-b", "main"],
383 ["config", "user.name", "Test"],
384 ["config", "user.email", "test@example.com"],
385 ])
386 yield* git.run({ operation: "test.setup", command: "git", cwd: source, args });
387 yield* fs.writeFileString(path.join(source, "base.txt"), "base\n");
388 for (const args of [
389 ["add", "base.txt"],
390 ["commit", "-m", "base"],
391 ])
392 yield* git.run({ operation: "test.setup", command: "git", cwd: source, args });
393 const base = (yield* git.run({
394 operation: "test.setup",
395 command: "git",
396 cwd: source,
397 args: ["rev-parse", "HEAD"],
398 })).stdout.trim();
399 yield* git.run({
400 operation: "test.setup",
401 command: "git",
402 cwd: root,
403 args: ["clone", source, cwd],
404 });
405 yield* fs.writeFileString(path.join(source, "feature.txt"), "pull request change\n");
406 for (const args of [
407 ["add", "feature.txt"],
408 ["commit", "-m", "feature"],
409 ["update-ref", "refs/pull/42/head", "HEAD"],
410 ])
411 yield* git.run({ operation: "test.setup", command: "git", cwd: source, args });
412 const head = (yield* git.run({
413 operation: "test.setup",
414 command: "git",
415 cwd: source,
416 args: ["rev-parse", "HEAD"],
417 })).stdout.trim();
418 const fetched: string[] = [];
419 const host = yield* SourceControlHost.SourceControlHost;
420 const provider = yield* ForgejoSourceControlProvider.make.pipe(
421 Effect.provideService(
422 SourceControlHost.SourceControlHost,
423 SourceControlHost.SourceControlHost.of({
424 settings: host.settings,
425 git: host.git,
426 process: {
427 run: (input) => {
428 if (input.args[0] !== "fetch") return git.run(input);
429 const url = input.args[2];
430 assert.isDefined(url);
431 fetched.push(url!);
432 // Only SSH transport is substituted; both paths fetch the real pull ref.
433 return git.run({
434 ...input,
435 args: input.args.map((arg) =>
436 arg === "git@forgejo.test:reviewer/project.git" ? source : arg,
437 ),
438 });
439 },
440 },
441 }),
442 ),
443 Effect.provide(
444 Layer.mock(ForgejoCli.ForgejoCli)({
445 resolveRepository: () =>
446 Effect.succeed({
447 command: "fj",
448 login: "work",
449 repository: "reviewer/project",
450 baseUrl: "https://forgejo.test",
451 }),
452 api: (input) => {
453 assert.include(
454 ["repos/reviewer/project", "repos/reviewer/project/pulls/42"],
455 input.path,
456 );
457 return Effect.succeed(
458 processOutput(
459 encodeJson(
460 input.path.endsWith("/pulls/42")
461 ? {
462 number: 42,
463 title: "Checkout",
464 html_url: "https://forgejo.test/reviewer/project/pulls/42",
465 state: "open",
466 merged: false,
467 base: { ref: "main", sha: base, repo: null },
468 head: { ref: "feature", sha: head, repo: null },
469 }
470 : {
471 full_name: "reviewer/project",
472 clone_url: source,
473 ssh_url: "git@forgejo.test:reviewer/project.git",
474 default_branch: "main",
475 },
476 ),
477 ),
478 );
479 },
480 }),
481 ),
482 );
483 yield* provider.checkoutChangeRequest({
484 cwd,
485 reference: "https://forgejo.test/reviewer/project/pulls/42",
486 });
487 assert.strictEqual(
488 (yield* git.run({
489 operation: "test.verify",
490 command: "git",
491 cwd,
492 args: ["branch", "--show-current"],
493 })).stdout.trim(),
494 "pulls/42",
495 );
496 assert.strictEqual(
497 (yield* git.run({
498 operation: "test.verify",
499 command: "git",
500 cwd,
501 args: ["rev-parse", "HEAD"],
502 })).stdout.trim(),
503 head,
504 );
505 assert.strictEqual(
506 yield* fs.readFileString(path.join(cwd, "feature.txt")),
507 "pull request change\n",
508 );
509 for (const args of [
510 ["checkout", "main"],
511 ["branch", "-f", "pulls/42", "main"],
512 ])
513 yield* git.run({ operation: "test.setup", command: "git", cwd, args });
514 yield* fs.writeFileString(path.join(cwd, "base.txt"), "uncommitted work\n");
515 yield* provider.checkoutChangeRequest({ cwd, reference: "42" });
516 assert.strictEqual(
517 (yield* git.run({
518 operation: "test.verify",
519 command: "git",
520 cwd,
521 args: ["rev-parse", "HEAD"],
522 })).stdout.trim(),
523 base,
524 );
525 assert.strictEqual(yield* fs.exists(path.join(cwd, "feature.txt")), false);
526 yield* provider.checkoutChangeRequest({
527 cwd,
528 reference: "42",
529 force: true,
530 context: {
531 provider: { kind: "forgejo", name: "Forgejo", baseUrl: "https://forgejo.test" },
532 remoteName: "origin",
533 remoteUrl: "git@forgejo.test:maria/project.git",
534 },
535 });
536 assert.strictEqual(
537 (yield* git.run({
538 operation: "test.verify",
539 command: "git",
540 cwd,
541 args: ["rev-parse", "HEAD"],
542 })).stdout.trim(),
543 head,
544 );
545 assert.strictEqual(
546 yield* fs.readFileString(path.join(cwd, "base.txt")),
547 "uncommitted work\n",
548 );
549 assert.strictEqual(
550 yield* fs.readFileString(path.join(cwd, "feature.txt")),
551 "pull request change\n",
552 );
553 assert.deepStrictEqual(fetched, [source, source, "git@forgejo.test:reviewer/project.git"]);
554 }).pipe(
555 Effect.scoped,
556 Effect.provide(
557 ServerSourceControlHost.layer.pipe(
558 Layer.provideMerge(VcsProcess.layer),
559 Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
560 Layer.provideMerge(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
561 Layer.provideMerge(Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({})),
562 Layer.provideMerge(NodeServices.layer),
563 ),
564 ),
565 ),
566);