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