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

uninstall.ts

220 lines8.1 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 launcherOwnsVersionsDir,
17 pinnedRuntimeVersionsDir,
18 windowsShimTarget,
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 }
32​
33export interface UninstallPlan {
34 readonly service: boolean;
35 readonly launcher: string | undefined;
36 readonly runtimeDir: string | undefined;
37 readonly userdataDir: string;
39​
40/** Delete only launchers targeting this home's runtime/versions. */
41export const findOwnedLauncher = Effect.fn("cli.uninstall.find_launcher")(function* (input: {
42 readonly launchedAs: string | undefined;
43 readonly versionsDir: string;
44}) {
45 const fs = yield* FileSystem.FileSystem;
46 const path = yield* Path.Path;
47 const platform = yield* HostProcess.Platform;
48 if (input.launchedAs === undefined) return undefined;
49 if (platform === "win32") {
50 const shimPath = yield* findWindowsShim(input.launchedAs);
51 if (shimPath === undefined) return undefined;
52 const contents = yield* fs.readFileString(shimPath).pipe(Effect.option);
53 const target = Option.isSome(contents) ? windowsShimTarget(contents.value) : undefined;
54 return target !== undefined && launcherOwnsVersionsDir(path, input.versionsDir, target)
55 ? shimPath
56 : undefined;
57 }
58 const linkTarget = yield* fs.readLink(input.launchedAs).pipe(Effect.option);
59 if (Option.isNone(linkTarget)) return undefined;
60 const resolved = path.resolve(path.dirname(input.launchedAs), linkTarget.value);
61 return launcherOwnsVersionsDir(path, input.versionsDir, resolved) ? input.launchedAs : undefined;
62});
63​
64// cmd.exe needs verbatim quoting and a literal path, with delayed expansion disabled.
65export function spawnWindowsRemoval(comspec: string, dir: string) {
66 return NodeChildProcess.spawn(
67 comspec,
68 [
69 "/d",
70 "/v:off",
71 "/s",
72 "/c",
73 '"ping -n 3 127.0.0.1 >nul & rmdir /s /q "%T3_UNINSTALL_RUNTIME%""',
74 ],
75 {
76 env: { ...process.env, T3_UNINSTALL_RUNTIME: dir },
77 windowsVerbatimArguments: true,
78 detached: true,
79 stdio: "ignore",
80 windowsHide: true,
81 },
82 );
84​
85const planUninstall = Effect.fn("cli.uninstall.plan")(function* (input: {
86 readonly baseDir: string;
87}) {
88 const fs = yield* FileSystem.FileSystem;
89 const path = yield* Path.Path;
90 const service = yield* BootService.BootService;
91 const status = yield* service.status;
92 const servesThisHome =
93 status.installedBaseDir !== undefined &&
94 path.resolve(status.installedBaseDir) === path.resolve(input.baseDir);
95 const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir);
96 const runtimeDir = path.dirname(versionsDir);
97 const launchedAs = (yield* HostProcess.IsExecutable) ? yield* resolveLauncherPath : undefined;
98 const plan: UninstallPlan = {
99 service: status.supported && status.installed && servesThisHome,
100 launcher: yield* findOwnedLauncher({ launchedAs, versionsDir }),
101 runtimeDir: (yield* fs.exists(runtimeDir).pipe(Effect.orElseSucceed(() => false)))
102 ? runtimeDir
103 : undefined,
104 userdataDir: path.join(input.baseDir, "userdata"),
105 };
106 return plan;
107});
108​
109export const uninstallCommand = Command.make("uninstall", {
110 ...projectLocationFlags,
111 yes: Flag.Boolean("yes").pipe(
112 Flag.withAlias("y"),
113 Flag.withDescription(
114 "Remove everything without asking. Required from a script, where there is no prompt.",
115 ),
116 Flag.withDefault(false),
117 ),
118}).pipe(
119 Command.withDescription(
120 "Remove t3 from this machine: the background service, the launcher, and every downloaded version. Your projects and threads are kept.",
121 ),
122 Command.withHandler((flags) =>
123 Effect.gen(function* () {
124 const logLevel = yield* GlobalFlag.LogLevel;
125 const config = yield* resolveCliAuthConfig(flags, logLevel);
126 return yield* runUninstall({ baseDir: config.baseDir, assumeYes: flags.yes }).pipe(
127 Effect.provide(CliService.layer(config)),
128 );
129 }),
130 ),
131);
132​
133const runUninstall = Effect.fn("cli.uninstall.run")(function* (input: {
134 readonly baseDir: string;
135 readonly assumeYes: boolean;
136}) {
137 const fs = yield* FileSystem.FileSystem;
138 const platform = yield* HostProcess.Platform;
139 const environment = yield* HostProcess.Environment;
140 const service = yield* BootService.BootService;
141 const plan = yield* planUninstall({ baseDir: input.baseDir });
142​
143 if (!plan.service && plan.launcher === undefined && plan.runtimeDir === undefined) {
144 yield* Console.log(`Nothing to remove: t3 is not installed for ${input.baseDir}.`);
145 if (!(yield* HostProcess.IsExecutable)) {
146 yield* Console.log(
147 " 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).",
148 );
149 }
150 return;
151 }
152​
153 yield* Console.log("This will remove:");
154 if (plan.service) yield* Console.log(" the background service (stopping it first)");
155 if (plan.launcher !== undefined) yield* Console.log(` the launcher at ${plan.launcher}`);
156 if (plan.runtimeDir !== undefined) {
157 yield* Console.log(` every downloaded version under ${plan.runtimeDir}`);
158 }
159 yield* Console.log(
160 `Your projects, threads, and settings under ${plan.userdataDir} are kept. Delete that directory yourself if you want them gone too.`,
161 );
162​
163 if (!input.assumeYes) {
164 if (!(process.stdin.isTTY && process.stdout.isTTY)) {
165 return yield* new CliUninstallError({
166 reason:
167 "Not a terminal, so nothing was removed. Rerun with --yes to confirm from a script.",
168 });
169 }
170 const confirmed = yield* Prompt.run(
171 Prompt.Confirm({ message: "Remove t3 from this machine?", initial: false }),
172 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(false) }));
173 if (!confirmed) {
174 yield* Console.log("Left as is.");
175 return;
176 }
177 }
178​
179 if (plan.service) {
180 yield* service.uninstall;
181 yield* Console.log("Removed the background service.");
182 }
183 if (plan.launcher !== undefined) {
184 yield* fs
185 .remove(plan.launcher, { force: true })
186 .pipe(
187 Effect.mapError(
188 () =>
189 new CliUninstallError({ reason: `Could not remove the launcher at ${plan.launcher}.` }),
190 ),
191 );
192 yield* Console.log(`Removed ${plan.launcher}.`);
193 }
194 if (plan.runtimeDir !== undefined) {
195 // Windows refuses to unlink this running executable; a detached shell removes it after exit.
196 if (platform === "win32") {
197 const runtimeDir = plan.runtimeDir;
198 const comspec = environment["ComSpec"] ?? environment["COMSPEC"] ?? "cmd.exe";
199 yield* Effect.try({
200 try: () => spawnWindowsRemoval(comspec, runtimeDir).unref(),
201 catch: () =>
202 new CliUninstallError({
203 reason: `Could not schedule removal of ${runtimeDir}. Delete it yourself once this window is closed.`,
204 }),
205 });
206 yield* Console.log(`${runtimeDir} will be removed once t3 exits.`);
207 } else {
208 yield* fs
209 .remove(plan.runtimeDir, { recursive: true, force: true })
210 .pipe(
211 Effect.mapError(
212 () => new CliUninstallError({ reason: `Could not remove ${plan.runtimeDir}.` }),
213 ),
214 );
215 yield* Console.log(`Removed ${plan.runtimeDir}.`);
216 }
217 }
218 yield* Console.log("");
219 yield* Console.log("t3 is uninstalled. Thanks for trying T3 Code.");
220});