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

uninstall.ts

328 lines12.7 KB

1// @effect-diagnostics nodeBuiltinImport:off
2// Windows cleanup must outlive this executable to delete its directory; scoped ChildProcess kills children on exit.
3import * as NodeChildProcess from "node:child_process";
4import * as NodePath from "node:path";
5​
6import * as HostProcess from "@t3tools/shared/HostProcess";
7import * as Console from "effect/Console";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import * as Schema from "effect/Schema";
13import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
14​
15import * as BootService from "../cloud/bootService.ts";
16import {
17 findPosixLauncher,
18 generatedWindowsShimTarget,
19 isVersionExecutable,
20 pinnedRuntimeVersionsDir,
21 readPosixLauncherTarget,
22 resolveLauncherPath,
23} from "../cloud/pinnedRuntime.ts";
24import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
25import * as CliService from "./service.ts";
26import { awaitDetachedSpawn } from "../process/windowsVerbatimSpawn.ts";
27import { windowsSystem32Path } from "@t3tools/shared/windowsSystem";
28import { findWindowsShim } from "./update.ts";
29​
30export class CliUninstallError extends Schema.TaggedError<CliUninstallError>()(
31 "CliUninstallError",
32 { reason: Schema.String },
33) {
34 override get message(): string {
35 return this.reason;
36 }
38​
39export interface UninstallPlan {
40 readonly service: boolean;
41 readonly otherHomeService: string | undefined;
42 /** The unit of an installed service whose T3 home could not be read. */
43 readonly unknownHomeService: string | undefined;
44 readonly versionsDir: string;
45 readonly launchers: ReadonlyArray<string>;
46 readonly runtimeDir: string | undefined;
47 readonly userdataDir: string;
49​
50/** Delete only launchers targeting this home's runtime/versions. */
51export const findOwnedLauncher = Effect.fn("cli.uninstall.find_launcher")(function* (input: {
52 readonly launchedAs: string | undefined;
53 readonly versionsDir: string;
54}) {
55 const fs = yield* FileSystem.FileSystem;
56 const path = yield* Path.Path;
57 const platform = yield* HostProcess.Platform;
58 if (input.launchedAs === undefined) return undefined;
59 if (platform === "win32") {
60 const shimPath = yield* findWindowsShim(input.launchedAs);
61 if (shimPath === undefined) return undefined;
62 const contents = yield* fs.readFileString(shimPath).pipe(Effect.option);
63 const target = Option.isSome(contents) ? generatedWindowsShimTarget(contents.value) : undefined;
64 return target !== undefined && isVersionExecutable(path, input.versionsDir, target)
65 ? shimPath
66 : undefined;
67 }
68 return yield* findPosixLauncher({ launchedAs: input.launchedAs, versionsDir: input.versionsDir });
69});
70​
71/** Whether `launcher` is a link, unedited `t3` script, or unedited `t3.cmd` into this home's runtime/versions. */
72const ownsLauncher = Effect.fn("cli.uninstall.owns_launcher")(function* (
73 launcher: string,
74 versionsDir: string,
75) {
76 const fs = yield* FileSystem.FileSystem;
77 const path = yield* Path.Path;
78 const platform = yield* HostProcess.Platform;
79 const realVersionsDir = yield* fs
80 .realPath(versionsDir)
81 .pipe(Effect.orElseSucceed(() => versionsDir));
82 const scriptTarget = platform === "win32" ? undefined : yield* readPosixLauncherTarget(launcher);
83 // The link or script text keeps a pruned (dangling) target; the real path sees through a
84 // symlinked T3 home.
85 const targets =
86 platform === "win32"
87 ? [
88 yield* fs.readFileString(launcher).pipe(
89 Effect.map(generatedWindowsShimTarget),
90 Effect.orElseSucceed(() => undefined),
91 ),
92 ]
93 : [
94 yield* fs.readLink(launcher).pipe(
95 Effect.map((link) => path.resolve(path.dirname(launcher), link)),
96 Effect.orElseSucceed(() => undefined),
97 ),
98 yield* fs.realPath(launcher).pipe(Effect.orElseSucceed(() => undefined)),
99 scriptTarget,
100 scriptTarget !== undefined
101 ? yield* fs.realPath(scriptTarget).pipe(Effect.orElseSucceed(() => undefined))
102 : undefined,
103 ];
104 return targets.some(
105 (target) =>
106 target !== undefined &&
107 (isVersionExecutable(path, versionsDir, target) ||
108 isVersionExecutable(path, realVersionsDir, target)),
109 );
110});
111​
112/**
113 * Launchers recorded in `runtime/launchers` by the install scripts and `t3 install` that still
114 * point into this home's runtime/versions. npx can run a different version than the installed
115 * one, so the launcher this process started from does not always name them.
116 */
117export const findRecordedLaunchers = Effect.fn("cli.uninstall.find_recorded_launchers")(function* (
118 versionsDir: string,
119) {
120 const fs = yield* FileSystem.FileSystem;
121 const path = yield* Path.Path;
122 const recorded = yield* fs
123 .readFileString(path.join(path.dirname(versionsDir), "launchers"))
124 .pipe(Effect.orElseSucceed(() => ""));
125 const owned: Array<string> = [];
126 for (const launcher of recorded.split(/\r?\n/).filter(Boolean)) {
127 if (yield* ownsLauncher(launcher, versionsDir)) owned.push(launcher);
128 }
129 return owned;
130});
131​
132// cmd.exe needs verbatim quoting and literal paths, with delayed expansion disabled. The shell
133// starts in System32 and runs ping from there, whatever directory `t3 uninstall` was run in.
134// Detached, it has no console, so ping would open a window of its own without headless conhost.
135export function spawnWindowsRemoval(environment: NodeJS.ProcessEnv, dir: string) {
136 const ping = windowsSystem32Path(environment, "ping.exe");
137 const conhost = windowsSystem32Path(environment, "conhost.exe");
138 return NodeChildProcess.spawn(
139 environment["ComSpec"] ?? environment["COMSPEC"] ?? windowsSystem32Path(environment, "cmd.exe"),
140 [
141 "/d",
142 "/v:off",
143 "/s",
144 "/c",
145 '"start "" /wait "%T3_UNINSTALL_CONHOST%" --headless "%T3_UNINSTALL_PING%" -n 3 127.0.0.1 >nul & rmdir /s /q "%T3_UNINSTALL_RUNTIME%""',
146 ],
147 {
148 cwd: NodePath.win32.dirname(ping),
149 env: {
150 ...process.env,
151 T3_UNINSTALL_CONHOST: conhost,
152 T3_UNINSTALL_PING: ping,
153 T3_UNINSTALL_RUNTIME: dir,
154 },
155 windowsVerbatimArguments: true,
156 detached: true,
157 stdio: "ignore",
158 windowsHide: true,
159 },
160 );
162​
163const planUninstall = Effect.fn("cli.uninstall.plan")(function* (input: {
164 readonly baseDir: string;
165}) {
166 const fs = yield* FileSystem.FileSystem;
167 const path = yield* Path.Path;
168 const service = yield* BootService.BootService;
169 const status = yield* service.status;
170 const installedBaseDir =
171 status.supported && status.installed ? status.installedBaseDir : undefined;
172 const servesThisHome = installedBaseDir !== undefined && status.otherBaseDir === undefined;
173 const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir);
174 const runtimeDir = path.dirname(versionsDir);
175 const launchedAs = (yield* HostProcess.IsExecutable) ? yield* resolveLauncherPath : undefined;
176 const launchedFrom = yield* findOwnedLauncher({ launchedAs, versionsDir });
177 const plan: UninstallPlan = {
178 service: servesThisHome,
179 otherHomeService: servesThisHome ? undefined : installedBaseDir,
180 unknownHomeService:
181 status.supported && status.installed && installedBaseDir === undefined
182 ? status.unitPath
183 : undefined,
184 versionsDir,
185 launchers: [
186 ...new Set([
187 ...(launchedFrom === undefined ? [] : [launchedFrom]),
188 ...(yield* findRecordedLaunchers(versionsDir)),
189 ]),
190 ],
191 runtimeDir: (yield* fs.exists(runtimeDir).pipe(Effect.orElseSucceed(() => false)))
192 ? runtimeDir
193 : undefined,
194 userdataDir: path.join(input.baseDir, "userdata"),
195 };
196 return plan;
197});
198​
199export const uninstallCommand = Command.make("uninstall", {
200 ...projectLocationFlags,
201 yes: Flag.Boolean("yes").pipe(
202 Flag.withAlias("y"),
203 Flag.withDescription(
204 "Remove everything without asking. Required from a script, where there is no prompt.",
205 ),
206 Flag.withDefault(false),
207 ),
208}).pipe(
209 Command.withDescription(
210 "Remove t3 from this machine: the background service, the launcher, and every downloaded version. Your projects and threads are kept.",
211 ),
212 Command.withHandler((flags) =>
213 Effect.gen(function* () {
214 const logLevel = yield* GlobalFlag.LogLevel;
215 const config = yield* resolveCliAuthConfig(flags, logLevel);
216 return yield* runUninstall({ baseDir: config.baseDir, assumeYes: flags.yes }).pipe(
217 Effect.provide(CliService.layer(config)),
218 );
219 }),
220 ),
221);
222​
223const logLeftService = (plan: UninstallPlan) =>
224 plan.unknownHomeService !== undefined
225 ? Console.log(
226 `A T3 Code service definition was found, but its T3 home could not be determined, so it was not removed. Check ${plan.unknownHomeService}.`,
227 )
228 : plan.otherHomeService === undefined
229 ? Effect.void
230 : Console.log(
231 `The T3 Code service serves ${plan.otherHomeService}, so it was not removed. Pass \`${BootService.formatBootServiceBaseDirOption(plan.otherHomeService)}\` to remove it.`,
232 );
233​
234const runUninstall = Effect.fn("cli.uninstall.run")(function* (input: {
235 readonly baseDir: string;
236 readonly assumeYes: boolean;
237}) {
238 const fs = yield* FileSystem.FileSystem;
239 const platform = yield* HostProcess.Platform;
240 const environment = yield* HostProcess.Environment;
241 const service = yield* BootService.BootService;
242 const plan = yield* planUninstall({ baseDir: input.baseDir });
243​
244 if (!plan.service && plan.launchers.length === 0 && plan.runtimeDir === undefined) {
245 yield* Console.log(`Nothing to remove: t3 is not installed for ${input.baseDir}.`);
246 if (!(yield* HostProcess.IsExecutable)) {
247 yield* Console.log(
248 " This t3 runs from a Node script, so it was installed by npm or built from source. Remove it the same way (`npm uninstall -g t3`, or delete the checkout).",
249 );
250 }
251 yield* logLeftService(plan);
252 return;
253 }
254​
255 yield* Console.log("This will remove:");
256 if (plan.service) yield* Console.log(" the background service (stopping it first)");
257 for (const launcher of plan.launchers) yield* Console.log(` the launcher at ${launcher}`);
258 if (plan.runtimeDir !== undefined) {
259 yield* Console.log(` every downloaded version under ${plan.runtimeDir}`);
260 }
261 yield* Console.log(
262 `Your projects, threads, and settings under ${plan.userdataDir} are kept. Delete that directory yourself if you want them gone too.`,
263 );
264​
265 if (!input.assumeYes) {
266 if (!(process.stdin.isTTY && process.stdout.isTTY)) {
267 return yield* new CliUninstallError({
268 reason:
269 "Not a terminal, so nothing was removed. Rerun with --yes to confirm from a script.",
270 });
271 }
272 const confirmed = yield* Prompt.run(
273 Prompt.Confirm({ message: "Remove t3 from this machine?", initial: false }),
274 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(false) }));
275 if (!confirmed) {
276 yield* Console.log("Left as is.");
277 return;
278 }
279 }
280​
281 // The prompt can wait a long time; keep a service or launcher that changed hands meanwhile.
282 if (plan.service && (yield* service.status).otherBaseDir !== undefined) {
283 yield* Console.log("Left the background service: it now serves another T3 home.");
284 } else if (plan.service) {
285 yield* service.uninstall;
286 yield* Console.log("Removed the background service.");
287 }
288 for (const launcher of plan.launchers) {
289 if (!(yield* ownsLauncher(launcher, plan.versionsDir))) {
290 yield* Console.log(`Left ${launcher}: it no longer runs this t3.`);
291 continue;
292 }
293 yield* fs
294 .remove(launcher, { force: true })
295 .pipe(
296 Effect.mapError(
297 () => new CliUninstallError({ reason: `Could not remove the launcher at ${launcher}.` }),
298 ),
299 );
300 yield* Console.log(`Removed ${launcher}.`);
301 }
302 if (plan.runtimeDir !== undefined) {
303 // Windows refuses to unlink this running executable; a detached shell removes it after exit.
304 if (platform === "win32") {
305 const runtimeDir = plan.runtimeDir;
306 const notScheduled = () =>
307 new CliUninstallError({
308 reason: `Could not schedule removal of ${runtimeDir}. Delete it yourself once this window is closed.`,
309 });
310 yield* awaitDetachedSpawn(() => spawnWindowsRemoval(environment, runtimeDir)).pipe(
311 Effect.mapError(notScheduled),
312 );
313 yield* Console.log(`${runtimeDir} will be removed once t3 exits.`);
314 } else {
315 yield* fs
316 .remove(plan.runtimeDir, { recursive: true, force: true })
317 .pipe(
318 Effect.mapError(
319 () => new CliUninstallError({ reason: `Could not remove ${plan.runtimeDir}.` }),
320 ),
321 );
322 yield* Console.log(`Removed ${plan.runtimeDir}.`);
323 }
324 }
325 yield* Console.log("");
326 yield* Console.log("t3 is uninstalled. Thanks for trying T3 Code.");
327 yield* logLeftService(plan);
328});