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

uninstall.ts

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