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

uninstall.ts

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