Open History to see the last commit
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 '""%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_PING: String.raw`C:\Windows\System32\ping.exe`,
100 T3_UNINSTALL_RUNTIME: runtimeDir,
101 },
102 });
103 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NetService.layer))),
104);
105
106it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 uninstall command", (it) => {
107 it.effect.each([
108 {
109 label: "names another home's service it leaves installed",
110 otherFromRead: 1,
111 removed: [],
112 output: "--base-dir '/home/me/.t3'",
113 },
114 {
115 label: "leaves a service that serves another home by the time it is removed",
116 otherFromRead: 2,
117 removed: [],
118 output: "Left the background service: it now serves another T3 home.",
119 },
120 ])("$label", (input) =>
121 Effect.gen(function* () {
122 const fs = yield* FileSystem.FileSystem;
123 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-uninstall-cli-test-" });
124 const uninstalls: Array<true> = [];
125 let reads = 0;
126 vi.spyOn(BootService, "layer").mockReturnValue(
127 Layer.succeed(
128 BootService.BootService,
129 BootService.BootService.of({
130 status: Effect.sync(() => ({
131 supported: true,
132 installed: true,
133 current: true,
134 installedBaseDir: "/home/me/.t3",
135 ...(++reads >= input.otherFromRead ? { otherBaseDir: "/home/me/.t3" } : {}),
136 unitPath: "/home/me/.config/systemd/user/t3code.service",
137 logPath: "/home/me/.t3/userdata/logs/boot-service.log",
138 })),
139 withStopped: (operation) => operation,
140 restart: Effect.die("unexpected restart"),
141 install: () => Effect.die("unexpected install"),
142 uninstall: Effect.sync(() => {
143 uninstalls.push(true);
144 return true;
145 }),
146 }),
147 ),
148 );
149
150 const output = yield* Command.runWith(uninstallCommand, { version: packageJson.version })([
151 "--base-dir",
152 baseDir,
153 "--yes",
154 ]).pipe(
155 Effect.andThen(TestConsole.logLines),
156 Effect.map((lines) => lines.join("\n")),
157 Effect.provideService(HostProcess.Environment, {}),
158 Effect.provideService(HostProcess.IsExecutable, false),
159 Effect.provide(
160 Layer.mergeAll(
161 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
162 Layer.fresh(TestConsole.layer),
163 ),
164 ),
165 );
166 assert.deepStrictEqual(uninstalls, input.removed);
167 assert.include(output, input.output);
168 }),
169 );
170});
171
172it.layer(NodeServices.layer)("t3 uninstall launcher", (it) => {
173 it.effect("claims only a launcher that points into this home's runtime tree", () =>
174 Effect.gen(function* () {
175 const fs = yield* FileSystem.FileSystem;
176 const path = yield* Path.Path;
177 // macOS spells the temp folder /var but resolves it to /private/var.
178 const root = yield* fs
179 .makeTempDirectoryScoped({ prefix: "t3-uninstall-" })
180 .pipe(Effect.flatMap(fs.realPath));
181 const versionsDir = path.join(root, "runtime/versions");
182 const exe = path.join(versionsDir, "1.0.0/t3");
183 const otherExe = path.join(root, "other/runtime/versions/1.0.0/t3");
184 const copy = path.join(root, "copy/t3");
185 for (const file of [exe, otherExe, copy]) {
186 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
187 yield* fs.writeFileString(file, "");
188 }
189 const ours = path.join(root, "bin/t3");
190 const theirs = path.join(root, "other/bin/t3");
191 yield* fs.makeDirectory(path.dirname(ours), { recursive: true });
192 yield* fs.makeDirectory(path.dirname(theirs), { recursive: true });
193 yield* fs.symlink(exe, ours);
194 yield* fs.symlink(otherExe, theirs);
195
196 assert.equal(yield* findOwnedLauncher({ launchedAs: ours, versionsDir }), ours);
197 assert.isUndefined(yield* findOwnedLauncher({ launchedAs: theirs, versionsDir }));
198 assert.isUndefined(yield* findOwnedLauncher({ launchedAs: copy, versionsDir }));
199 assert.isUndefined(yield* findOwnedLauncher({ launchedAs: undefined, versionsDir }));
200 // A script launcher execs by absolute path, so argv0 names the executable.
201 const scriptDir = path.join(root, "script-bin");
202 const script = path.join(scriptDir, "t3");
203 yield* fs.makeDirectory(scriptDir);
204 yield* fs.writeFileString(script, posixLauncherScript(exe), { mode: 0o755 });
205 assert.equal(
206 yield* findOwnedLauncher({ launchedAs: exe, versionsDir }).pipe(
207 Effect.provideService(HostProcess.Environment, { PATH: scriptDir }),
208 ),
209 script,
210 );
211 const editedScript = path.join(scriptDir, "t3-edited");
212 yield* fs.writeFileString(editedScript, `${posixLauncherScript(exe)}# mine\n`);
213
214 // On Windows, only the shim exactly as written is ours; a user's wrapper stays.
215 const shimDir = path.join(root, "win-bin");
216 const shim = path.join(shimDir, "t3.cmd");
217 yield* fs.makeDirectory(shimDir);
218 const windowsOwner = (contents: string) =>
219 fs
220 .writeFileString(shim, contents)
221 .pipe(
222 Effect.andThen(findOwnedLauncher({ launchedAs: exe, versionsDir })),
223 Effect.provideService(HostProcess.Platform, "win32"),
224 Effect.provideService(HostProcess.Environment, { PATH: shimDir }),
225 );
226 assert.equal(yield* windowsOwner(`@echo off\r\n"${exe}" %*`), shim);
227 assert.isUndefined(yield* windowsOwner(`@echo off\r\nset FOO=1\r\n"${exe}" %*`));
228
229 // npx can run another version than the installed one, so uninstall also reads the
230 // recorded launchers: through a symlinked home, and dangling after a prune.
231 const throughAlias = path.join(root, "bin/t3-alias");
232 const pruned = path.join(root, "bin/t3-pruned");
233 const scriptThroughAlias = path.join(scriptDir, "t3-alias");
234 const prunedScript = path.join(scriptDir, "t3-pruned");
235 yield* fs.symlink(root, path.join(root, "alias"));
236 yield* fs.symlink(path.join(root, "alias/runtime/versions/1.0.0/t3"), throughAlias);
237 yield* fs.symlink(path.join(versionsDir, "0.9.0/t3"), pruned);
238 yield* fs.writeFileString(
239 scriptThroughAlias,
240 posixLauncherScript(path.join(root, "alias/runtime/versions/1.0.0/t3")),
241 { mode: 0o755 },
242 );
243 yield* fs.writeFileString(
244 prunedScript,
245 posixLauncherScript(path.join(versionsDir, "0.9.0/t3")),
246 { mode: 0o755 },
247 );
248 // Another program inside a version is not a launcher.
249 const sibling = path.join(root, "bin/t3-sibling");
250 yield* fs.symlink(path.join(versionsDir, "1.0.0/node"), sibling);
251 yield* fs.writeFileString(
252 path.join(root, "runtime/launchers"),
253 [
254 ours,
255 theirs,
256 copy,
257 throughAlias,
258 pruned,
259 sibling,
260 script,
261 scriptThroughAlias,
262 prunedScript,
263 editedScript,
264 path.join(root, "missing"),
265 ].join("\n") + "\n",
266 );
267 for (const dir of [versionsDir, path.join(root, "alias/runtime/versions")]) {
268 assert.deepStrictEqual(yield* findRecordedLaunchers(dir), [
269 ours,
270 throughAlias,
271 pruned,
272 script,
273 scriptThroughAlias,
274 prunedScript,
275 ]);
276 }
277
278 // On Windows only an unedited t3.cmd is ours; a hand-edited wrapper belongs to the user.
279 const cmd = path.join(root, "bin/t3.cmd");
280 const edited = path.join(root, "bin/edited.cmd");
281 yield* fs.writeFileString(cmd, `@echo off\r\n"${exe}" %*`);
282 yield* fs.writeFileString(edited, `@echo off\r\nset "T3CODE_HOME=D:\\other"\r\n"${exe}" %*`);
283 yield* fs.writeFileString(path.join(root, "runtime/launchers"), `${cmd}\r\n${edited}\r\n`);
284 assert.deepStrictEqual(
285 yield* findRecordedLaunchers(versionsDir).pipe(
286 Effect.provideService(HostProcess.Platform, "win32"),
287 ),
288 [cmd],
289 );
290 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
291 );
292});
293
294it.live.runIf(HostProcess.Platform.defaultValue() === "win32")(
295 "t3 uninstall has cmd.exe remove the runtime directory with System32 tools, preserving spaces and literal environment-variable syntax",
296 () =>
297 Effect.gen(function* () {
298 const fs = yield* FileSystem.FileSystem;
299 const path = yield* Path.Path;
300 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-uninstall-" });
301 const runtimeDir = path.join(root, "t3 home %COMSPEC% !COMSPEC! & data", "runtime");
302 yield* fs.makeDirectory(path.join(runtimeDir, "versions", "1.0.0"), { recursive: true });
303 yield* fs.writeFileString(path.join(runtimeDir, "versions", "1.0.0", "t3.exe"), "");
304
305 // The directory `t3 uninstall` is run from holds its own `ping`, which must stay unused.
306 const marker = path.join(root, "ping-ran.txt");
307 yield* fs.writeFileString(path.join(root, "ping.cmd"), '@echo ran>"%~dp0ping-ran.txt"\r\n');
308 yield* Effect.acquireRelease(
309 Effect.sync(() => {
310 const previous = process.cwd();
311 process.chdir(root);
312 return previous;
313 }),
314 (previous) => Effect.sync(() => process.chdir(previous)),
315 );
316
317 const child = spawnWindowsRemoval(yield* HostProcess.Environment, runtimeDir);
318 yield* Effect.callback<void, Error>((resume) => {
319 child.once("error", (error) => resume(Effect.fail(error)));
320 child.once("exit", (code) =>
321 resume(code === 0 ? Effect.void : Effect.die(`cmd.exe exited with ${code}`)),
322 );
323 });
324
325 assert.isFalse(yield* fs.exists(runtimeDir));
326 assert.isFalse(yield* fs.exists(marker));
327 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
328);