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

uninstall.ts

209 lines8.1 KB

1// @effect-diagnostics nodeBuiltinImport:off
2// The Windows cleanup shell must outlive this process (it deletes the
3// directory this executable runs from), which Effect's scoped ChildProcess
4// cannot express: it kills the child when the scope closes.
5import * as NodeChildProcess from "node:child_process";
6​
7import * as HostProcess from "@t3tools/shared/HostProcess";
8import * as Console from "effect/Console";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
13import * as Schema from "effect/Schema";
14import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
15​
16import * as BootService from "../cloud/bootService.ts";
17import { pinnedRuntimeVersionsDir } from "../cloud/pinnedRuntime.ts";
18import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
19import * as CliService from "./service.ts";
20import { findWindowsShim, launcherOwnsVersionsDir, resolveLauncherPath } from "./update.ts";
21​
22export class CliUninstallError extends Schema.TaggedError<CliUninstallError>()(
23 "CliUninstallError",
24 { reason: Schema.String },
25) {
26 override get message(): string {
27 return this.reason;
28 }
30​
31export interface UninstallPlan {
32 readonly service: boolean;
33 readonly launcher: string | undefined;
34 readonly runtimeDir: string | undefined;
35 readonly userdataDir: string;
37​
38/**
39 * Only a launcher that points into this home's `runtime/versions` is claimed: a plain copy of the
40 * executable, or a launcher for another home, is not ours to delete.
41 */
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) ? /^"([^"]+)"/m.exec(contents.value)?.[1] : undefined;
55 return target !== undefined && launcherOwnsVersionsDir(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 launcherOwnsVersionsDir(path, input.versionsDir, resolved) ? input.launchedAs : undefined;
63});
64​
65const planUninstall = Effect.fn("cli.uninstall.plan")(function* (input: {
66 readonly baseDir: string;
67}) {
68 const fs = yield* FileSystem.FileSystem;
69 const path = yield* Path.Path;
70 const service = yield* BootService.BootService;
71 const status = yield* service.status;
72 const servesThisHome =
73 status.installedBaseDir !== undefined &&
74 path.resolve(status.installedBaseDir) === path.resolve(input.baseDir);
75 const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir);
76 const runtimeDir = path.dirname(versionsDir);
77 const launchedAs = (yield* HostProcess.IsExecutable) ? yield* resolveLauncherPath : undefined;
78 const plan: UninstallPlan = {
79 service: status.supported && status.installed && servesThisHome,
80 launcher: yield* findOwnedLauncher({ launchedAs, versionsDir }),
81 runtimeDir: (yield* fs.exists(runtimeDir).pipe(Effect.orElseSucceed(() => false)))
82 ? runtimeDir
83 : undefined,
84 userdataDir: path.join(input.baseDir, "userdata"),
85 };
86 return plan;
87});
88​
89export const uninstallCommand = Command.make("uninstall", {
90 ...projectLocationFlags,
91 yes: Flag.Boolean("yes").pipe(
92 Flag.withAlias("y"),
93 Flag.withDescription(
94 "Remove everything without asking. Required from a script, where there is no prompt.",
95 ),
96 Flag.withDefault(false),
97 ),
98}).pipe(
99 Command.withDescription(
100 "Remove t3 from this machine: the background service, the launcher, and every downloaded version. Your projects and threads are kept.",
101 ),
102 Command.withHandler((flags) =>
103 Effect.gen(function* () {
104 const logLevel = yield* GlobalFlag.LogLevel;
105 const config = yield* resolveCliAuthConfig(flags, logLevel);
106 return yield* runUninstall({ baseDir: config.baseDir, assumeYes: flags.yes }).pipe(
107 Effect.provide(CliService.layer(config)),
108 );
109 }),
110 ),
111);
112​
113const runUninstall = Effect.fn("cli.uninstall.run")(function* (input: {
114 readonly baseDir: string;
115 readonly assumeYes: boolean;
116}) {
117 const fs = yield* FileSystem.FileSystem;
118 const platform = yield* HostProcess.Platform;
119 const environment = yield* HostProcess.Environment;
120 const service = yield* BootService.BootService;
121 const plan = yield* planUninstall({ baseDir: input.baseDir });
122​
123 if (!plan.service && plan.launcher === undefined && plan.runtimeDir === undefined) {
124 yield* Console.log(`Nothing to remove: t3 is not installed for ${input.baseDir}.`);
125 if (!(yield* HostProcess.IsExecutable)) {
126 yield* Console.log(
127 " 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).",
128 );
129 }
130 return;
131 }
132​
133 yield* Console.log("This will remove:");
134 if (plan.service) yield* Console.log(" the background service (stopping it first)");
135 if (plan.launcher !== undefined) yield* Console.log(` the launcher at ${plan.launcher}`);
136 if (plan.runtimeDir !== undefined) {
137 yield* Console.log(` every downloaded version under ${plan.runtimeDir}`);
138 }
139 yield* Console.log(
140 `Your projects, threads, and settings under ${plan.userdataDir} are kept. Delete that directory yourself if you want them gone too.`,
141 );
142​
143 if (!input.assumeYes) {
144 if (!(process.stdin.isTTY && process.stdout.isTTY)) {
145 return yield* new CliUninstallError({
146 reason:
147 "Not a terminal, so nothing was removed. Rerun with --yes to confirm from a script.",
148 });
149 }
150 const confirmed = yield* Prompt.run(
151 Prompt.Confirm({ message: "Remove t3 from this machine?", initial: false }),
152 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(false) }));
153 if (!confirmed) {
154 yield* Console.log("Left as is.");
155 return;
156 }
157 }
158​
159 if (plan.service) {
160 yield* service.uninstall;
161 yield* Console.log("Removed the background service.");
162 }
163 if (plan.launcher !== undefined) {
164 yield* fs
165 .remove(plan.launcher, { force: true })
166 .pipe(
167 Effect.mapError(
168 () =>
169 new CliUninstallError({ reason: `Could not remove the launcher at ${plan.launcher}.` }),
170 ),
171 );
172 yield* Console.log(`Removed ${plan.launcher}.`);
173 }
174 if (plan.runtimeDir !== undefined) {
175 // This process runs from inside runtimeDir. POSIX unlinks a running
176 // executable fine; Windows refuses, so the tree is removed after this
177 // process exits by a detached shell, and the user is told either way.
178 if (platform === "win32") {
179 const runtimeDir = plan.runtimeDir;
180 const comspec = environment["ComSpec"] ?? environment["COMSPEC"] ?? "cmd.exe";
181 yield* Effect.try({
182 try: () => {
183 const child = NodeChildProcess.spawn(
184 comspec,
185 ["/d", "/c", `ping -n 3 127.0.0.1 >nul & rmdir /s /q "${runtimeDir}"`],
186 { detached: true, stdio: "ignore", windowsHide: true },
187 );
188 child.unref();
189 },
190 catch: () =>
191 new CliUninstallError({
192 reason: `Could not schedule removal of ${runtimeDir}. Delete it yourself once this window is closed.`,
193 }),
194 });
195 yield* Console.log(`${runtimeDir} will be removed once t3 exits.`);
196 } else {
197 yield* fs
198 .remove(plan.runtimeDir, { recursive: true, force: true })
199 .pipe(
200 Effect.mapError(
201 () => new CliUninstallError({ reason: `Could not remove ${plan.runtimeDir}.` }),
202 ),
203 );
204 yield* Console.log(`Removed ${plan.runtimeDir}.`);
205 }
206 }
207 yield* Console.log("");
208 yield* Console.log("t3 is uninstalled. Thanks for trying T3 Code.");
209});