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

SourceControlDiscovery.test.ts

318 lines11.5 KB

1import {
2 SourceControlProviderKind,
3 type VcsError,
4 VcsProcessExitError,
5 VcsProcessSpawnError,
6 VcsProcessTimeoutError,
7} from "@t3tools/contracts";
8import { assert, it } from "@effect/vitest";
9import * as NodeServices from "@effect/platform-node/NodeServices";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Path from "effect/Path";
15import * as PlatformError from "effect/PlatformError";
16import {
17 providerAuth,
18 type SourceControlProviderDiscoverySpec,
19} from "@t3tools/source-control-core/server/discovery";
20import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
21import {
22 fakeDiscovery,
23 fakeSourceControlProvider,
24} from "@t3tools/source-control-testing/fakeSourceControlDriver";
25import * as HostProcess from "@t3tools/shared/HostProcess";
26import { SpawnExecutableResolution } from "@t3tools/shared/shell";
27import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
28​
29import * as ServerConfig from "../config.ts";
30import * as ServerSettings from "../serverSettings.ts";
31import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
32import * as VcsProcess from "../vcs/VcsProcess.ts";
33import * as SourceControlDiscovery from "./SourceControlDiscovery.ts";
34import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
35​
36const kind = SourceControlProviderKind.make;
37​
38// Serves both the host's runs and the server's own VCS probes, whose inputs share these fields.
39const run = (
40 input: Pick<
41 SourceControlHost.SourceControlProcessInput,
42 "operation" | "command" | "args" | "cwd"
43 >,
44): Effect.Effect<SourceControlHost.SourceControlProcessOutput, VcsError> => {
45 const context = { operation: input.operation, command: input.command, cwd: input.cwd };
46 if (input.command === "slow-cli") {
47 return Effect.fail(new VcsProcessTimeoutError({ ...context, timeoutMs: 5_000 }));
48 }
49 if (input.command === "broken-cli") {
50 return Effect.fail(
51 new VcsProcessExitError({ ...context, exitCode: 1, detail: "broken-cli: bad install" }),
52 );
53 }
54 if (input.command === "absent-cli") {
55 return Effect.fail(
56 new VcsProcessSpawnError({
57 ...context,
58 cause: PlatformError.systemError({
59 _tag: "NotFound",
60 module: "ChildProcess",
61 method: "spawn",
62 pathOrDescriptor: input.command,
63 }),
64 }),
65 );
66 }
67 if (input.args[0] === "--version") {
68 return input.command === "missing-cli"
69 ? Effect.fail(
70 new VcsProcessSpawnError({
71 operation: input.operation,
72 command: input.command,
73 cwd: input.cwd,
74 cause: new Error(`${input.command} not found`),
75 }),
76 )
77 : Effect.succeed(TestSourceControlHost.processOutput(`${input.command} version test\n`));
78 }
79 return Effect.succeed(
80 TestSourceControlHost.processOutput(`signed in as ${input.command}-user\n`),
81 );
82};
83​
84const cliDiscovery = (
85 name: string,
86 executable = name === "beta" ? "missing-cli" : `${name}-cli`,
87) => ({
88 type: "cli" as const,
89 kind: kind(name),
90 label: name,
91 installHint: `Install ${name}.`,
92 executable,
93 versionArgs: ["--version"],
94 authArgs: ["auth", "status"],
95 parseAuth: ({ stdout }: { readonly stdout: string }) =>
96 providerAuth({ status: "authenticated", account: /as (\S+)/.exec(stdout)?.[1] }),
97});
98​
99const defaultDiscoveries = [
100 cliDiscovery("alpha"),
101 cliDiscovery("beta"),
102 fakeDiscovery("gamma", {
103 probeAuth: Effect.succeed(providerAuth({ status: "authenticated", account: "api-user" })),
104 }),
105];
106​
107const layerDiscovery = (
108 runProcess = run,
109 discoveries: ReadonlyArray<SourceControlProviderDiscoverySpec> = defaultDiscoveries,
110) =>
111 Layer.effect(
112 SourceControlProviderRegistry.SourceControlProviderRegistry,
113 SourceControlProviderRegistry.makeWithProviders(
114 discoveries.map((discovery) => ({
115 kind: discovery.kind,
116 provider: fakeSourceControlProvider(discovery.kind),
117 discovery,
118 })),
119 ),
120 ).pipe(
121 Layer.provideMerge(TestSourceControlHost.layer({ process: { run: runProcess } })),
122 Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
123 Layer.provideMerge(Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({})),
124 Layer.provideMerge(Layer.mock(VcsProcess.VcsProcess)({ run: runProcess })),
125 Layer.provideMerge(
126 ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-discovery-" }),
127 ),
128 Layer.provideMerge(NodeServices.layer),
129 );
130​
131it.effect("reports every hosting integration in registry order with its sign-in", () =>
132 Effect.gen(function* () {
133 const discovery = yield* SourceControlDiscovery.SourceControlDiscovery;
134 const result = yield* discovery.discover;
135​
136 assert.deepStrictEqual(
137 result.sourceControlProviders.map((item) => ({
138 kind: item.kind,
139 status: item.status,
140 version: item.version,
141 auth: item.auth.status,
142 account: item.auth.account,
143 })),
144 [
145 {
146 kind: kind("alpha"),
147 status: "available",
148 version: Option.some("alpha-cli version test"),
149 auth: "authenticated",
150 account: Option.some("alpha-cli-user"),
151 },
152 {
153 kind: kind("beta"),
154 status: "missing",
155 version: Option.none(),
156 auth: "unknown",
157 account: Option.none(),
158 },
159 {
160 kind: kind("gamma"),
161 status: "available",
162 version: Option.none(),
163 auth: "authenticated",
164 account: Option.some("api-user"),
165 },
166 ],
167 );
168 assert.deepStrictEqual(
169 result.versionControlSystems.map((item) => [item.kind, item.status]),
170 [
171 ["git", "available"],
172 ["jj", "available"],
173 ],
174 );
175 }).pipe(Effect.provide(SourceControlDiscovery.layer.pipe(Layer.provide(layerDiscovery())))),
176);
177​
178it.effect("explains a CLI whose version probe failed instead of advising an install", () =>
179 Effect.gen(function* () {
180 const discovery = yield* SourceControlDiscovery.SourceControlDiscovery;
181 const result = yield* discovery.discover;
182 const item = (name: string) => {
183 const found = result.sourceControlProviders.find((entry) => entry.kind === kind(name));
184 assert.isDefined(found);
185 return found;
186 };
187 const authDetail = (name: string) => Option.getOrElse(item(name).auth.detail, () => "");
188​
189 assert.notInclude(item("slow").installHint, "Install slow.");
190 assert.include(item("slow").installHint, "timed out after 5000ms");
191 assert.strictEqual(authDetail("slow"), item("slow").installHint);
192​
193 assert.notInclude(item("broken").installHint, "Install broken.");
194 assert.include(item("broken").installHint, "exited with status 1");
195 assert.strictEqual(authDetail("broken"), item("broken").installHint);
196​
197 assert.strictEqual(item("absent").installHint, "Install absent.");
198​
199 const git = result.versionControlSystems.find((entry) => entry.kind === "git");
200 assert.isDefined(git);
201 assert.notInclude(git.installHint, "Install Git from");
202 assert.include(git.installHint, "`git --version` exited with status 1");
203 }).pipe(
204 Effect.provide(
205 SourceControlDiscovery.layer.pipe(
206 Layer.provide(
207 layerDiscovery(
208 (input) => run(input.command === "git" ? { ...input, command: "broken-cli" } : input),
209 [
210 cliDiscovery("slow", "slow-cli"),
211 cliDiscovery("broken", "broken-cli"),
212 cliDiscovery("absent", "absent-cli"),
213 ],
214 ),
215 ),
216 ),
217 ),
218 ),
219);
220​
221it.effect.each(["darwin", "linux"] as const)(
222 "names incompatible executables only on macOS (%s)",
223 (platform) => {
224 const runProcess: typeof run = (input) =>
225 Effect.fail(
226 new VcsProcessSpawnError({
227 operation: input.operation,
228 command: input.command,
229 cwd: input.cwd,
230 cause:
231 input.command === "missing-cli"
232 ? new Error("not found")
233 : Object.assign(new Error("spawn Unknown system error -86"), { errno: -86 }),
234 }),
235 );
236 return Effect.gen(function* () {
237 const discovery = yield* SourceControlDiscovery.SourceControlDiscovery;
238 const result = yield* discovery.discover;
239 for (const item of [...result.versionControlSystems, ...result.sourceControlProviders]) {
240 if (item.kind === kind("gamma")) continue;
241 assert.strictEqual(item.status, "missing");
242 if (platform === "darwin" && item.executable !== "missing-cli") {
243 assert.include(
244 item.installHint,
245 `\`/usr/local/bin/${item.executable}\` is built for another CPU architecture, so this arm64 machine cannot run it. Remove or replace it.`,
246 );
247 } else {
248 assert.notInclude(item.installHint, "CPU architecture");
249 }
250 }
251 }).pipe(
252 Effect.provide(SourceControlDiscovery.layer.pipe(Layer.provide(layerDiscovery(runProcess)))),
253 Effect.provideService(SpawnExecutableResolution, (command) => `/usr/local/bin/${command}`),
254 Effect.provideService(HostProcess.Platform, platform),
255 Effect.provideService(HostProcess.Architecture, "arm64"),
256 );
257 },
258);
259​
260// Spawns a real login shell and `jj`, so it runs on wall-clock time; the fixture shell is POSIX sh.
261it.live.skipIf(HostProcess.Platform.defaultValue() === "win32")(
262 "rescans with tools the login shell gained after the server started",
263 () =>
264 Effect.gen(function* () {
265 const fs = yield* FileSystem.FileSystem;
266 const path = yield* Path.Path;
267 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-discovery-login-shell-" });
268 const home = path.join(root, "home");
269 const fakebin = path.join(home, "fakebin");
270 const loginShell = path.join(root, "loginsh");
271 yield* fs.makeDirectory(fakebin, { recursive: true });
272 // Stands in for `$SHELL -ilc <capture>` and sources only the fixture
273 // profile, so the host's own shell init cannot change the result.
274 yield* fs.writeFileString(
275 loginShell,
276 `#!/bin/sh\nexport HOME=${home}\n. "$HOME/.profile"\nshift\nexec /bin/sh -c "$1"\n`,
277 { mode: 0o755 },
278 );
279 const env = yield* HostProcess.Environment;
280 yield* Effect.acquireRelease(
281 Effect.sync(() => {
282 const saved = { PATH: env.PATH, SHELL: env.SHELL };
283 env.SHELL = loginShell;
284 return saved;
285 }),
286 (saved) =>
287 Effect.sync(() => {
288 env.PATH = saved.PATH;
289 if (saved.SHELL === undefined) delete env.SHELL;
290 else env.SHELL = saved.SHELL;
291 }),
292 );
293​
294 // The user installs a tool after launch; their login shell now finds it.
295 yield* fs.writeFileString(path.join(fakebin, "jj"), "#!/bin/sh\necho 'jj 0.99.0-test'\n", {
296 mode: 0o755,
297 });
298 yield* fs.writeFileString(path.join(home, ".profile"), 'export PATH="$HOME/fakebin:$PATH"\n');
299​
300 const discovery = yield* SourceControlDiscovery.SourceControlDiscovery;
301 const jj = (yield* discovery.discover).versionControlSystems.find(
302 (item) => item.kind === "jj",
303 );
304​
305 assert.deepStrictEqual(
306 { status: jj?.status, version: jj?.version },
307 { status: "available", version: Option.some("jj 0.99.0-test") },
308 );
309 }).pipe(
310 Effect.scoped,
311 Effect.provide(
312 SourceControlDiscovery.layer.pipe(
313 Layer.provide(VcsProcess.layer),
314 Layer.provideMerge(layerDiscovery()),
315 ),
316 ),
317 ),
318);