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

uninstall.ts

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