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

uninstall.test.ts

342 lines14.2 KB

1// @effect-diagnostics nodeBuiltinImport:off - The test observes a real cleanup-shell spawn failure.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { assert, it } from "@effect/vitest";
5import * as ConfigProvider from "effect/ConfigProvider";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Path from "effect/Path";
10import * as TestConsole from "effect/testing/TestConsole";
11import { Command } from "effect/cli";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13import * as NetService from "@t3tools/shared/Net";
14import { afterEach, expect, vi } from "vite-plus/test";
15​
16import packageJson from "../../package.json" with { type: "json" };
17import * as BootService from "../cloud/bootService.ts";
18import { posixLauncherScript } from "../cloud/pinnedRuntime.ts";
19import {
20 findOwnedLauncher,
21 findRecordedLaunchers,
22 spawnWindowsRemoval,
23 uninstallCommand,
24} from "./uninstall.ts";
25​
26vi.mock("node:child_process", { spy: true });
27​
28afterEach(() => vi.restoreAllMocks());
29​
30it.live(
31 "runs the Windows cleanup from System32 and reports failure when its shell cannot start",
32 () =>
33 Effect.gen(function* () {
34 const fs = yield* FileSystem.FileSystem;
35 const path = yield* Path.Path;
36 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-uninstall-shell-" });
37 const runtimeDir = path.join(baseDir, "runtime");
38 yield* fs.makeDirectory(runtimeDir);
39 vi.spyOn(BootService, "layer").mockReturnValue(
40 Layer.succeed(
41 BootService.BootService,
42 BootService.BootService.of({
43 status: Effect.succeed({
44 supported: false,
45 installed: false,
46 current: false,
47 unitPath: "",
48 logPath: "",
49 }),
50 withStopped: (operation) => operation,
51 restart: Effect.die("unexpected restart"),
52 install: () => Effect.die("unexpected install"),
53 uninstall: Effect.die("unexpected uninstall"),
54 }),
55 ),
56 );
57 const actual = yield* Effect.promise(() =>
58 vi.importActual<typeof import("node:child_process")>("node:child_process"),
59 );
60 const spawn = actual.spawn;
61 const spawned: Array<Parameters<typeof spawn>> = [];
62 const failedSpawn = new Promise<Error>((resolve) => {
63 vi.spyOn(NodeChildProcess, "spawn").mockImplementation((...args) => {
64 spawned.push(args);
65 const child = spawn(...args);
66 // Observe the real spawn error without letting it terminate the test runner.
67 child.once("error", resolve);
68 return child;
69 });
70 });
71 const result = yield* Command.runWith(uninstallCommand, { version: packageJson.version })([
72 "--base-dir",
73 baseDir,
74 "--yes",
75 ]).pipe(
76 Effect.result,
77 Effect.provideService(HostProcess.Environment, {
78 ComSpec: path.join(baseDir, "missing-cmd.exe"),
79 SystemRoot: String.raw`C:\Windows`,
80 }),
81 Effect.provideService(HostProcess.Platform, "win32"),
82 Effect.provideService(HostProcess.IsExecutable, false),
83 Effect.provide(
84 Layer.mergeAll(
85 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
86 Layer.fresh(TestConsole.layer),
87 ),
88 ),
89 );
90 yield* Effect.promise(() => failedSpawn);
91 expect(result._tag, "an unavailable cleanup shell must fail uninstall").toBe("Failure");
92 const [, args, options] = spawned[0]!;
93 expect(args.at(-1)).toBe(
94 '"start "" /wait "%T3_UNINSTALL_CONHOST%" --headless "%T3_UNINSTALL_PING%" -n 3 127.0.0.1 >nul & rmdir /s /q "%T3_UNINSTALL_RUNTIME%""',
95 );
96 expect(options).toMatchObject({
97 cwd: String.raw`C:\Windows\System32`,
98 env: {
99 T3_UNINSTALL_CONHOST: String.raw`C:\Windows\System32\conhost.exe`,
100 T3_UNINSTALL_PING: String.raw`C:\Windows\System32\ping.exe`,
101 T3_UNINSTALL_RUNTIME: runtimeDir,
102 },
103 });
104 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NetService.layer))),
105);
106​
107it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 uninstall command", (it) => {
108 it.effect.each([
109 {
110 label: "names another home's service it leaves installed",
111 installedBaseDir: "/home/me/.t3",
112 otherFromRead: 1,
113 removed: [],
114 output: "--base-dir '/home/me/.t3'",
115 },
116 {
117 label: "leaves a service that serves another home by the time it is removed",
118 installedBaseDir: "/home/me/.t3",
119 otherFromRead: 2,
120 removed: [],
121 output: "Left the background service: it now serves another T3 home.",
122 },
123 {
124 // A unit that names no home T3 Code can read, such as a quoted Environment= line.
125 label: "names a service whose home it cannot read instead of saying nothing is installed",
126 installedBaseDir: undefined,
127 otherFromRead: Infinity,
128 removed: [],
129 output:
130 "A T3 Code service definition was found, but its T3 home could not be determined, so it was not removed. Check /home/me/.config/systemd/user/t3code.service.",
131 },
132 ])("$label", (input) =>
133 Effect.gen(function* () {
134 const fs = yield* FileSystem.FileSystem;
135 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-uninstall-cli-test-" });
136 const uninstalls: Array<true> = [];
137 let reads = 0;
138 vi.spyOn(BootService, "layer").mockReturnValue(
139 Layer.succeed(
140 BootService.BootService,
141 BootService.BootService.of({
142 status: Effect.sync(() => ({
143 supported: true,
144 installed: true,
145 current: true,
146 ...(input.installedBaseDir === undefined
147 ? {}
148 : { installedBaseDir: input.installedBaseDir }),
149 ...(++reads >= input.otherFromRead ? { otherBaseDir: "/home/me/.t3" } : {}),
150 unitPath: "/home/me/.config/systemd/user/t3code.service",
151 logPath: "/home/me/.t3/userdata/logs/boot-service.log",
152 })),
153 withStopped: (operation) => operation,
154 restart: Effect.die("unexpected restart"),
155 install: () => Effect.die("unexpected install"),
156 uninstall: Effect.sync(() => {
157 uninstalls.push(true);
158 return true;
159 }),
160 }),
161 ),
162 );
163​
164 const output = yield* Command.runWith(uninstallCommand, { version: packageJson.version })([
165 "--base-dir",
166 baseDir,
167 "--yes",
168 ]).pipe(
169 Effect.andThen(TestConsole.logLines),
170 Effect.map((lines) => lines.join("\n")),
171 Effect.provideService(HostProcess.Environment, {}),
172 Effect.provideService(HostProcess.IsExecutable, false),
173 Effect.provide(
174 Layer.mergeAll(
175 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
176 Layer.fresh(TestConsole.layer),
177 ),
178 ),
179 );
180 assert.deepStrictEqual(uninstalls, input.removed);
181 assert.include(output, input.output);
182 }),
183 );
184});
185​
186it.layer(NodeServices.layer)("t3 uninstall launcher", (it) => {
187 it.effect("claims only a launcher that points into this home's runtime tree", () =>
188 Effect.gen(function* () {
189 const fs = yield* FileSystem.FileSystem;
190 const path = yield* Path.Path;
191 // macOS spells the temp folder /var but resolves it to /private/var.
192 const root = yield* fs
193 .makeTempDirectoryScoped({ prefix: "t3-uninstall-" })
194 .pipe(Effect.flatMap(fs.realPath));
195 const versionsDir = path.join(root, "runtime/versions");
196 const exe = path.join(versionsDir, "1.0.0/t3");
197 const otherExe = path.join(root, "other/runtime/versions/1.0.0/t3");
198 const copy = path.join(root, "copy/t3");
199 for (const file of [exe, otherExe, copy]) {
200 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
201 yield* fs.writeFileString(file, "");
202 }
203 const ours = path.join(root, "bin/t3");
204 const theirs = path.join(root, "other/bin/t3");
205 yield* fs.makeDirectory(path.dirname(ours), { recursive: true });
206 yield* fs.makeDirectory(path.dirname(theirs), { recursive: true });
207 yield* fs.symlink(exe, ours);
208 yield* fs.symlink(otherExe, theirs);
209​
210 assert.equal(yield* findOwnedLauncher({ launchedAs: ours, versionsDir }), ours);
211 assert.isUndefined(yield* findOwnedLauncher({ launchedAs: theirs, versionsDir }));
212 assert.isUndefined(yield* findOwnedLauncher({ launchedAs: copy, versionsDir }));
213 assert.isUndefined(yield* findOwnedLauncher({ launchedAs: undefined, versionsDir }));
214 // A script launcher execs by absolute path, so argv0 names the executable.
215 const scriptDir = path.join(root, "script-bin");
216 const script = path.join(scriptDir, "t3");
217 yield* fs.makeDirectory(scriptDir);
218 yield* fs.writeFileString(script, posixLauncherScript(exe), { mode: 0o755 });
219 assert.equal(
220 yield* findOwnedLauncher({ launchedAs: exe, versionsDir }).pipe(
221 Effect.provideService(HostProcess.Environment, { PATH: scriptDir }),
222 ),
223 script,
224 );
225 const editedScript = path.join(scriptDir, "t3-edited");
226 yield* fs.writeFileString(editedScript, `${posixLauncherScript(exe)}# mine\n`);
227​
228 // On Windows, only the shim exactly as written is ours; a user's wrapper stays.
229 const shimDir = path.join(root, "win-bin");
230 const shim = path.join(shimDir, "t3.cmd");
231 yield* fs.makeDirectory(shimDir);
232 const windowsOwner = (contents: string) =>
233 fs
234 .writeFileString(shim, contents)
235 .pipe(
236 Effect.andThen(findOwnedLauncher({ launchedAs: exe, versionsDir })),
237 Effect.provideService(HostProcess.Platform, "win32"),
238 Effect.provideService(HostProcess.Environment, { PATH: shimDir }),
239 );
240 assert.equal(yield* windowsOwner(`@echo off\r\n"${exe}" %*`), shim);
241 assert.isUndefined(yield* windowsOwner(`@echo off\r\nset FOO=1\r\n"${exe}" %*`));
242​
243 // npx can run another version than the installed one, so uninstall also reads the
244 // recorded launchers: through a symlinked home, and dangling after a prune.
245 const throughAlias = path.join(root, "bin/t3-alias");
246 const pruned = path.join(root, "bin/t3-pruned");
247 const scriptThroughAlias = path.join(scriptDir, "t3-alias");
248 const prunedScript = path.join(scriptDir, "t3-pruned");
249 yield* fs.symlink(root, path.join(root, "alias"));
250 yield* fs.symlink(path.join(root, "alias/runtime/versions/1.0.0/t3"), throughAlias);
251 yield* fs.symlink(path.join(versionsDir, "0.9.0/t3"), pruned);
252 yield* fs.writeFileString(
253 scriptThroughAlias,
254 posixLauncherScript(path.join(root, "alias/runtime/versions/1.0.0/t3")),
255 { mode: 0o755 },
256 );
257 yield* fs.writeFileString(
258 prunedScript,
259 posixLauncherScript(path.join(versionsDir, "0.9.0/t3")),
260 { mode: 0o755 },
261 );
262 // Another program inside a version is not a launcher.
263 const sibling = path.join(root, "bin/t3-sibling");
264 yield* fs.symlink(path.join(versionsDir, "1.0.0/node"), sibling);
265 yield* fs.writeFileString(
266 path.join(root, "runtime/launchers"),
267 [
268 ours,
269 theirs,
270 copy,
271 throughAlias,
272 pruned,
273 sibling,
274 script,
275 scriptThroughAlias,
276 prunedScript,
277 editedScript,
278 path.join(root, "missing"),
279 ].join("\n") + "\n",
280 );
281 for (const dir of [versionsDir, path.join(root, "alias/runtime/versions")]) {
282 assert.deepStrictEqual(yield* findRecordedLaunchers(dir), [
283 ours,
284 throughAlias,
285 pruned,
286 script,
287 scriptThroughAlias,
288 prunedScript,
289 ]);
290 }
291​
292 // On Windows only an unedited t3.cmd is ours; a hand-edited wrapper belongs to the user.
293 const cmd = path.join(root, "bin/t3.cmd");
294 const edited = path.join(root, "bin/edited.cmd");
295 yield* fs.writeFileString(cmd, `@echo off\r\n"${exe}" %*`);
296 yield* fs.writeFileString(edited, `@echo off\r\nset "T3CODE_HOME=D:\\other"\r\n"${exe}" %*`);
297 yield* fs.writeFileString(path.join(root, "runtime/launchers"), `${cmd}\r\n${edited}\r\n`);
298 assert.deepStrictEqual(
299 yield* findRecordedLaunchers(versionsDir).pipe(
300 Effect.provideService(HostProcess.Platform, "win32"),
301 ),
302 [cmd],
303 );
304 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
305 );
306});
307​
308it.live.runIf(HostProcess.Platform.defaultValue() === "win32")(
309 "t3 uninstall has cmd.exe remove the runtime directory with System32 tools, preserving spaces and literal environment-variable syntax",
310 () =>
311 Effect.gen(function* () {
312 const fs = yield* FileSystem.FileSystem;
313 const path = yield* Path.Path;
314 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-uninstall-" });
315 const runtimeDir = path.join(root, "t3 home %COMSPEC% !COMSPEC! & data", "runtime");
316 yield* fs.makeDirectory(path.join(runtimeDir, "versions", "1.0.0"), { recursive: true });
317 yield* fs.writeFileString(path.join(runtimeDir, "versions", "1.0.0", "t3.exe"), "");
318​
319 // The directory `t3 uninstall` is run from holds its own `ping`, which must stay unused.
320 const marker = path.join(root, "ping-ran.txt");
321 yield* fs.writeFileString(path.join(root, "ping.cmd"), '@echo ran>"%~dp0ping-ran.txt"\r\n');
322 yield* Effect.acquireRelease(
323 Effect.sync(() => {
324 const previous = process.cwd();
325 process.chdir(root);
326 return previous;
327 }),
328 (previous) => Effect.sync(() => process.chdir(previous)),
329 );
330​
331 const child = spawnWindowsRemoval(yield* HostProcess.Environment, runtimeDir);
332 yield* Effect.callback<void, Error>((resume) => {
333 child.once("error", (error) => resume(Effect.fail(error)));
334 child.once("exit", (code) =>
335 resume(code === 0 ? Effect.void : Effect.die(`cmd.exe exited with ${code}`)),
336 );
337 });
338​
339 assert.isFalse(yield* fs.exists(runtimeDir));
340 assert.isFalse(yield* fs.exists(marker));
341 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
342);