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

uninstall.ts

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