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

SourceControlDiscovery.test.ts

324 lines11.6 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 onPath = (command: string) => `/usr/local/bin/${command}`;
108​
109const layerDiscovery = (
110 runProcess = run,
111 discoveries: ReadonlyArray<SourceControlProviderDiscoverySpec> = defaultDiscoveries,
112) =>
113 Layer.effect(
114 SourceControlProviderRegistry.SourceControlProviderRegistry,
115 SourceControlProviderRegistry.makeWithProviders(
116 discoveries.map((discovery) => ({
117 kind: discovery.kind,
118 provider: fakeSourceControlProvider(discovery.kind),
119 discovery,
120 })),
121 ),
122 ).pipe(
123 Layer.provideMerge(TestSourceControlHost.layer({ process: { run: runProcess } })),
124 Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
125 Layer.provideMerge(Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({})),
126 Layer.provideMerge(Layer.mock(VcsProcess.VcsProcess)({ run: runProcess })),
127 Layer.provideMerge(
128 ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-discovery-" }),
129 ),
130 Layer.provideMerge(NodeServices.layer),
131 );
132​
133it.effect("reports every hosting integration in registry order with its sign-in", () =>
134 Effect.gen(function* () {
135 const discovery = yield* SourceControlDiscovery.SourceControlDiscovery;
136 const result = yield* discovery.discover;
137​
138 assert.deepStrictEqual(
139 result.sourceControlProviders.map((item) => ({
140 kind: item.kind,
141 status: item.status,
142 version: item.version,
143 auth: item.auth.status,
144 account: item.auth.account,
145 })),
146 [
147 {
148 kind: kind("alpha"),
149 status: "available",
150 version: Option.some("alpha-cli version test"),
151 auth: "authenticated",
152 account: Option.some("alpha-cli-user"),
153 },
154 {
155 kind: kind("beta"),
156 status: "missing",
157 version: Option.none(),
158 auth: "unknown",
159 account: Option.none(),
160 },
161 {
162 kind: kind("gamma"),
163 status: "available",
164 version: Option.none(),
165 auth: "authenticated",
166 account: Option.some("api-user"),
167 },
168 ],
169 );
170 assert.deepStrictEqual(
171 result.versionControlSystems.map((item) => [item.kind, item.status]),
172 [
173 ["git", "available"],
174 ["jj", "available"],
175 ],
176 );
177 }).pipe(
178 Effect.provide(SourceControlDiscovery.layer.pipe(Layer.provide(layerDiscovery()))),
179 Effect.provideService(SpawnExecutableResolution, onPath),
180 ),
181);
182​
183it.effect("explains a CLI whose version probe failed instead of advising an install", () =>
184 Effect.gen(function* () {
185 const discovery = yield* SourceControlDiscovery.SourceControlDiscovery;
186 const result = yield* discovery.discover;
187 const item = (name: string) => {
188 const found = result.sourceControlProviders.find((entry) => entry.kind === kind(name));
189 assert.isDefined(found);
190 return found;
191 };
192 const authDetail = (name: string) => Option.getOrElse(item(name).auth.detail, () => "");
193​
194 assert.notInclude(item("slow").installHint, "Install slow.");
195 assert.include(item("slow").installHint, "timed out after 5000ms");
196 assert.strictEqual(authDetail("slow"), item("slow").installHint);
197​
198 assert.notInclude(item("broken").installHint, "Install broken.");
199 assert.include(item("broken").installHint, "exited with status 1");
200 assert.strictEqual(authDetail("broken"), item("broken").installHint);
201​
202 assert.strictEqual(item("absent").installHint, "Install absent.");
203​
204 const git = result.versionControlSystems.find((entry) => entry.kind === "git");
205 assert.isDefined(git);
206 assert.notInclude(git.installHint, "Install Git from");
207 assert.include(git.installHint, "`git --version` exited with status 1");
208 }).pipe(
209 Effect.provideService(SpawnExecutableResolution, onPath),
210 Effect.provide(
211 SourceControlDiscovery.layer.pipe(
212 Layer.provide(
213 layerDiscovery(
214 (input) => run(input.command === "git" ? { ...input, command: "broken-cli" } : input),
215 [
216 cliDiscovery("slow", "slow-cli"),
217 cliDiscovery("broken", "broken-cli"),
218 cliDiscovery("absent", "absent-cli"),
219 ],
220 ),
221 ),
222 ),
223 ),
224 ),
225);
226​
227it.effect.each(["darwin", "linux"] as const)(
228 "names incompatible executables only on macOS (%s)",
229 (platform) => {
230 const runProcess: typeof run = (input) =>
231 Effect.fail(
232 new VcsProcessSpawnError({
233 operation: input.operation,
234 command: input.command,
235 cwd: input.cwd,
236 cause:
237 input.command === "missing-cli"
238 ? new Error("not found")
239 : Object.assign(new Error("spawn Unknown system error -86"), { errno: -86 }),
240 }),
241 );
242 return Effect.gen(function* () {
243 const discovery = yield* SourceControlDiscovery.SourceControlDiscovery;
244 const result = yield* discovery.discover;
245 for (const item of [...result.versionControlSystems, ...result.sourceControlProviders]) {
246 if (item.kind === kind("gamma")) continue;
247 assert.strictEqual(item.status, "missing");
248 if (platform === "darwin" && item.executable !== "missing-cli") {
249 assert.include(
250 item.installHint,
251 `\`/usr/local/bin/${item.executable}\` is built for another CPU architecture, so this arm64 machine cannot run it. Remove or replace it.`,
252 );
253 } else {
254 assert.notInclude(item.installHint, "CPU architecture");
255 }
256 }
257 }).pipe(
258 Effect.provide(SourceControlDiscovery.layer.pipe(Layer.provide(layerDiscovery(runProcess)))),
259 Effect.provideService(SpawnExecutableResolution, onPath),
260 Effect.provideService(HostProcess.Platform, platform),
261 Effect.provideService(HostProcess.Architecture, "arm64"),
262 );
263 },
264);
265​
266// Spawns a real login shell and `jj`, so it runs on wall-clock time; the fixture shell is POSIX sh.
267it.live.skipIf(HostProcess.Platform.defaultValue() === "win32")(
268 "rescans with tools the login shell gained after the server started",
269 () =>
270 Effect.gen(function* () {
271 const fs = yield* FileSystem.FileSystem;
272 const path = yield* Path.Path;
273 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-discovery-login-shell-" });
274 const home = path.join(root, "home");
275 const fakebin = path.join(home, "fakebin");
276 const loginShell = path.join(root, "loginsh");
277 yield* fs.makeDirectory(fakebin, { recursive: true });
278 // Stands in for `$SHELL -ilc <capture>` and sources only the fixture
279 // profile, so the host's own shell init cannot change the result.
280 yield* fs.writeFileString(
281 loginShell,
282 `#!/bin/sh\nexport HOME=${home}\n. "$HOME/.profile"\nshift\nexec /bin/sh -c "$1"\n`,
283 { mode: 0o755 },
284 );
285 const env = yield* HostProcess.Environment;
286 yield* Effect.acquireRelease(
287 Effect.sync(() => {
288 const saved = { PATH: env.PATH, SHELL: env.SHELL };
289 env.SHELL = loginShell;
290 return saved;
291 }),
292 (saved) =>
293 Effect.sync(() => {
294 env.PATH = saved.PATH;
295 if (saved.SHELL === undefined) delete env.SHELL;
296 else env.SHELL = saved.SHELL;
297 }),
298 );
299​
300 // The user installs a tool after launch; their login shell now finds it.
301 yield* fs.writeFileString(path.join(fakebin, "jj"), "#!/bin/sh\necho 'jj 0.99.0-test'\n", {
302 mode: 0o755,
303 });
304 yield* fs.writeFileString(path.join(home, ".profile"), 'export PATH="$HOME/fakebin:$PATH"\n');
305​
306 const discovery = yield* SourceControlDiscovery.SourceControlDiscovery;
307 const jj = (yield* discovery.discover).versionControlSystems.find(
308 (item) => item.kind === "jj",
309 );
310​
311 assert.deepStrictEqual(
312 { status: jj?.status, version: jj?.version },
313 { status: "available", version: Option.some("jj 0.99.0-test") },
314 );
315 }).pipe(
316 Effect.scoped,
317 Effect.provide(
318 SourceControlDiscovery.layer.pipe(
319 Layer.provide(VcsProcess.layer),
320 Layer.provideMerge(layerDiscovery()),
321 ),
322 ),
323 ),
324);