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