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