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

install.ts

392 lines16.1 KB

1import * as HostProcess from "@t3tools/shared/HostProcess";
2import { pathSetupCommand, resolveCommandPath } from "@t3tools/shared/shell";
3import * as Console from "effect/Console";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Option from "effect/Option";
8import * as Path from "effect/Path";
9import * as Schema from "effect/Schema";
10import { Command, Prompt } from "effect/cli";
11import * as ChildProcess from "effect/process/ChildProcess";
12import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
13​
14import packageJson from "../../package.json" with { type: "json" };
15import {
16 generatedWindowsShimTarget,
17 isVersionExecutable,
18 readPosixLauncherTarget,
19 recordPinnedRuntimeLauncher,
20 writePosixLauncher,
21} from "../cloud/pinnedRuntime.ts";
22import {
23 detectCliRunner,
24 hostShellWord,
25 resolveCliCommand,
26 resolveEntryPath,
27} from "./invocation.ts";
28​
29export class CliInstallError extends Schema.TaggedError<CliInstallError>()("CliInstallError", {
30 reason: Schema.String,
31 cause: Schema.optional(Schema.Defect()),
32}) {
33 override get message(): string {
34 return this.reason;
35 }
37​
38/** `<T3 home>/runtime/versions/<version>/t3`: the layout the install scripts and npm launcher share. */
39const standaloneRuntime = Effect.gen(function* () {
40 const path = yield* Path.Path;
41 if (!(yield* HostProcess.IsExecutable)) return Option.none();
42 const executable = yield* HostProcess.ExecutablePath;
43 const versionsDir = path.dirname(path.dirname(executable));
44 const runtimeDir = path.dirname(versionsDir);
45 if (path.basename(versionsDir) !== "versions" || path.basename(runtimeDir) !== "runtime") {
46 return Option.none();
47 }
48 return Option.some({ executable, versionsDir, runtimeDir });
49});
50​
51/** Installs this runtime as the `t3` command the way the install scripts do, replacing only our own launcher. */
52export const installCli = Effect.fn("cli.install.install")(function* () {
53 const fs = yield* FileSystem.FileSystem;
54 const path = yield* Path.Path;
55 const platform = yield* HostProcess.Platform;
56 const environment = yield* HostProcess.Environment;
57 const home = yield* HostProcess.HomeDirectory;
58 const runtime = yield* standaloneRuntime;
59 const windows = platform === "win32";
60 if (Option.isNone(runtime)) {
61 const script = windows
62 ? "irm https://t3.codes/install.ps1 | iex"
63 : "curl -fsSL https://t3.codes/install.sh | sh";
64 return yield* new CliInstallError({
65 reason: `Only the standalone t3 can install itself. Use \`${script}\`, or Settings in the desktop app.`,
66 });
67 }
68 const { executable, versionsDir, runtimeDir } = runtime.value;
69 // cmd.exe expands `%` and reads the shim in the OEM code page, so such a path would not run.
70 if (windows && /[%\u0080-\uffff]/.test(executable)) {
71 return yield* new CliInstallError({
72 reason: `A t3.cmd cannot run ${executable}, because the path has % or non-ASCII characters. Keep using npx t3.`,
73 });
74 }
75 // Absolute, so the PATH hint never adds a folder that changes with the working directory.
76 const binDir = path.resolve(
77 environment.T3CODE_INSTALL_BIN_DIR?.trim() || path.join(home, ".local", "bin"),
78 );
79 const name = windows ? "t3.cmd" : "t3";
80 const link = path.join(binDir, name);
81 const failed = (reason: string) => (cause: unknown) => new CliInstallError({ reason, cause });
82​
83 // Resolve fully so a link through a symlinked T3 home still counts as ours; a dangling one
84 // (a pruned version) falls back to its own text.
85 const realVersionsDir = yield* fs
86 .realPath(versionsDir)
87 .pipe(Effect.orElseSucceed(() => versionsDir));
88 const current = windows
89 ? yield* fs.readFileString(link).pipe(Effect.map(generatedWindowsShimTarget), Effect.option)
90 : yield* fs.readLink(link).pipe(
91 Effect.flatMap((target) =>
92 fs.realPath(link).pipe(Effect.orElseSucceed(() => path.resolve(binDir, target))),
93 ),
94 // Not a link: the script this command and the install scripts write.
95 Effect.catch(() => readPosixLauncherTarget(link)),
96 Effect.option,
97 Effect.map(Option.filter((target) => target !== undefined)),
98 );
99 // A dangling symlink is occupied too: writing the shim would follow it.
100 const occupied =
101 Option.isSome(current) ||
102 (yield* fs.exists(link)) ||
103 Option.isSome(yield* fs.readLink(link).pipe(Effect.option));
104 if (
105 occupied &&
106 !(
107 Option.isSome(current) &&
108 current.value !== undefined &&
109 (isVersionExecutable(path, versionsDir, current.value) ||
110 isVersionExecutable(path, realVersionsDir, current.value) ||
111 // This home's desktop launcher, which install.sh also replaces.
112 current.value === path.join(path.dirname(runtimeDir), "bin", name))
113 )
114 ) {
115 return yield* new CliInstallError({
116 reason: `Another t3 is already at ${link}. Remove it, then run this again.`,
117 });
118 }
119​
120 yield* fs
121 .makeDirectory(binDir, { recursive: true })
122 .pipe(Effect.mapError(failed(`Could not create ${binDir}.`)));
123 // An empty spot is created exclusively, so a file that appears after the check above is kept.
124 if (windows) {
125 yield* fs
126 .writeFileString(link, `@echo off\r\n"${executable}" %*`, occupied ? {} : { flag: "wx" })
127 .pipe(Effect.mapError(failed(`Could not write ${link}.`)));
128 } else {
129 yield* writePosixLauncher({ launcher: link, executable, exclusive: !occupied }).pipe(
130 Effect.mapError(failed(`Could not write ${link}.`)),
131 );
132 }
133​
134 // Pruning keeps what recorded launchers point at; a background service cannot see binDir otherwise.
135 const recorded = path.join(
136 yield* fs.realPath(binDir).pipe(Effect.orElseSucceed(() => binDir)),
137 name,
138 );
139 yield* recordPinnedRuntimeLauncher({
140 baseDir: path.dirname(runtimeDir),
141 launcher: recorded,
142 }).pipe(
143 Effect.catch(() =>
144 Console.error(
145 `Warning: could not record ${recorded} in ${path.join(runtimeDir, "launchers")}. Cleanup may remove the version it runs.`,
146 ),
147 ),
148 );
149​
150 // resolve() drops trailing separators, so `~/.local/bin/` on PATH still matches.
151 const normalize = (value: string) =>
152 windows ? path.resolve(value).toLowerCase() : path.resolve(value);
153 const same = (entry: string) => entry !== "" && normalize(entry) === normalize(binDir);
154 const rawPath = environment.PATH ?? environment.Path ?? "";
155 const entries = rawPath === "" ? [] : rawPath.split(windows ? ";" : ":");
156 let cwd = yield* Effect.catchDefect(HostProcess.WorkingDirectory, () => Effect.undefined);
157 // A t3 earlier on PATH runs instead, and an added folder goes last. Runner caches (npx's own
158 // .bin) are not installs.
159 const firstOther = Effect.gen(function* () {
160 for (const entry of entries) {
161 const absolute = path.isAbsolute(entry);
162 if ((windows || absolute) && same(entry)) return null;
163 const dir = absolute ? entry : windows || !cwd ? undefined : path.resolve(cwd, entry);
164 if (dir === undefined || detectCliRunner(`${dir}/`) !== null) continue;
165 for (const name of windows ? ["t3.cmd", "t3.exe"] : ["t3"]) {
166 const candidate = path.join(dir, name);
167 if (!(yield* resolveCommandPath(candidate, { env: environment }))) continue;
168 if (windows) return candidate;
169 const resolved = yield* fs.realPath(candidate).pipe(Effect.orElseSucceed(() => candidate));
170 if (normalize(resolved) !== normalize(recorded)) return candidate;
171 if (absolute) return null;
172 cwd = undefined; // Ours already won in cwd; later relative entries lose.
173 }
174 }
175 return undefined;
176 });
177 // null: this launcher runs first; a path: another t3 does; undefined: no t3 on PATH.
178 const found = yield* firstOther;
179 return {
180 link,
181 onPath: found === null,
182 shadowedBy: found ?? undefined,
183 pathCommand:
184 found !== undefined
185 ? undefined
186 : windows
187 ? // PowerShell; it covers this window only, since changing the saved PATH would flatten
188 // its %VAR% entries. A `;` would split the folder.
189 binDir.includes(";")
190 ? undefined
191 : `$env:Path += ';${binDir.replaceAll("'", "''")}'`
192 : pathSetupCommand({
193 directory: binDir,
194 home,
195 shell: environment.SHELL,
196 platform,
197 configHome: environment.XDG_CONFIG_HOME,
198 zdotdir: environment.ZDOTDIR,
199 }),
200 binDir,
201 };
202});
203​
204const reportInstalled = Effect.fn("cli.install.report")(function* (
205 installed: Effect.Success<ReturnType<typeof installCli>>,
206) {
207 yield* Console.log(`Installed t3 ${packageJson.version} at ${installed.link}.`);
208 if (installed.shadowedBy !== undefined) {
209 const platform = yield* HostProcess.Platform;
210 // Command Prompt and PowerShell share no quoted form, so Windows keeps the bare path.
211 const launcher =
212 platform === "win32" ? installed.link : hostShellWord(platform, installed.link);
213 return yield* Console.log(
214 `Another t3 at ${installed.shadowedBy} runs first, so run ${launcher} to use this one.`,
215 );
216 }
217 if (installed.onPath) return yield* Console.log("Run `t3` to get started.");
218 if (installed.pathCommand === undefined) {
219 return yield* Console.log(`Add ${installed.binDir} to your PATH, then run \`t3\`.`);
220 }
221 if ((yield* HostProcess.Platform) === "win32") {
222 yield* Console.log(
223 `${installed.binDir} is not on your PATH yet. In this PowerShell window, run:`,
224 );
225 yield* Console.log(` ${installed.pathCommand}`);
226 return yield* Console.log("Then run `t3`. For new windows, add the folder to your PATH.");
227 }
228 yield* Console.log(`${installed.binDir} is not on your PATH yet. Add it with:`);
229 yield* Console.log(` ${installed.pathCommand}`);
230 yield* Console.log("Then open a new terminal and run `t3`.");
231});
232​
233export const installCommand = Command.make("install").pipe(
234 Command.withDescription("Install this version as the `t3` command."),
235 Command.withHandler(() => installCli().pipe(Effect.flatMap(reportInstalled))),
236);
237​
238/** Saying no lasts until the next minor release: `0.2` covers `0.2.5` and `0.2.6-nightly.…`. */
239const minorRelease = (version: string) => version.split(".").slice(0, 2).join(".");
240​
241const SKIPPED_ARGUMENTS = new Set([
242 "help",
243 "--help",
244 "-h",
245 "--version",
246 "-v",
247 "--completions",
248 // Scripts and machine-readable output; a prompt would stall them or corrupt their output.
249 "--json",
250 "--token-only",
251 "--yes",
252 "-y",
253]);
254​
255/** The subcommand, past global flags that may come first (two take a value). */
256const topLevelCommand = (args: ReadonlyArray<string>) => {
257 for (let index = 0; index < args.length; index++) {
258 const arg = args[index]!;
259 if (arg === "--log-level" || arg === "--completions") index++;
260 else if (!arg.startsWith("-")) return arg;
261 }
262 return undefined;
263};
264​
265/** Agents can run commands in a terminal that nobody answers; no answer counts as no. */
266const PROMPT_TIMEOUT = Duration.seconds(30);
267​
268/** `/proc/<pid>/stat` fields after the parenthesized command name: state ppid pgrp session tty_nr tpgid. */
269export const isForegroundProcStat = (stat: string) => {
270 const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
271 return fields[2] !== undefined && fields[2] !== "" && fields[2] === fields[5];
272};
273​
274/** Output of `ps -o tpgid=,pgid=`; tpgid is -1 without a controlling terminal. */
275export const isForegroundPs = (output: string) => {
276 const [tpgid, pgid] = output.trim().split(/\s+/);
277 return tpgid !== undefined && tpgid !== "" && tpgid === pgid;
278};
279​
280/**
281 * A background job (`npx t3 serve &`) that reads the terminal is stopped by the shell, so only
282 * the terminal's foreground process group may prompt. Unknown counts as background.
283 */
284export const inTerminalForeground = Effect.gen(function* () {
285 const fs = yield* FileSystem.FileSystem;
286 const platform = yield* HostProcess.Platform;
287 if (platform === "win32") return true;
288 if (platform === "linux") {
289 return isForegroundProcStat(
290 yield* fs.readFileString("/proc/self/stat").pipe(Effect.orElseSucceed(() => "")),
291 );
292 }
293 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
294 return isForegroundPs(
295 yield* spawner
296 .string(
297 // Absolute: under npx, PATH starts with a project's node_modules/.bin.
298 ChildProcess.make("/bin/ps", ["-o", "tpgid=,pgid=", "-p", String(process.pid)], {
299 stdin: "ignore",
300 stderr: "ignore",
301 }),
302 )
303 .pipe(Effect.orElseSucceed(() => "")),
304 );
305});
306​
307/**
308 * Before a command run through npx, pnpm dlx, or bunx at a terminal, asks to install the `t3`
309 * command. Yes is the default. No, no answer, or a failed install is saved in the T3 home until
310 * the next minor release. Returns false when the user quits the prompt, so the command does not run.
311 */
312export const offerCliInstall = Effect.fn("cli.install.offer")(function* <E, R, E2, R2>(input: {
313 readonly args: ReadonlyArray<string>;
314 readonly interactive: boolean;
315 readonly foreground: Effect.Effect<boolean, E2, R2>;
316 /** Undefined when the user quits the prompt. */
317 readonly confirm: Effect.Effect<boolean | void, E, R>;
318}) {
319 const fs = yield* FileSystem.FileSystem;
320 const path = yield* Path.Path;
321 const platform = yield* HostProcess.Platform;
322 const environment = yield* HostProcess.Environment;
323 if (!input.interactive || environment.CI || environment.SUDO_USER) return true;
324 if (environment.TERM === "dumb") return true;
325 // `npx --yes` asks for no prompts; npm passes it on to the command as npm_config_yes.
326 if (environment.npm_config_yes === "true") return true;
327 // `--json=true` and `-y=true` are the same flags.
328 if (input.args.some((arg) => SKIPPED_ARGUMENTS.has(arg.split("=")[0]!))) return true;
329 const command = topLevelCommand(input.args);
330 if (command === "install" || command === "uninstall") return true;
331 if (detectCliRunner(yield* resolveEntryPath) === null) return true;
332 const runtime = yield* standaloneRuntime;
333 if (Option.isNone(runtime)) return true;
334 const { runtimeDir } = runtime.value;
335​
336 // Any t3 already installed means no prompt: ours (even when off PATH) or another on PATH.
337 // Runners put their own cache's node_modules/.bin on PATH, so skip those.
338 const windows = platform === "win32";
339 const names = windows ? ["t3.cmd", "t3.exe"] : ["t3"];
340 const launchers = yield* fs
341 .readFileString(path.join(runtimeDir, "launchers"))
342 .pipe(Effect.orElseSucceed(() => ""));
343 const candidates = [
344 ...launchers.split(/\r?\n/).filter((launcher) => path.isAbsolute(launcher)),
345 path.join(path.dirname(runtimeDir), "bin", windows ? "t3.cmd" : "t3"),
346 ...(environment.PATH ?? environment.Path ?? "")
347 .split(windows ? ";" : ":")
348 .filter(
349 (directory) => path.isAbsolute(directory) && detectCliRunner(`${directory}/`) === null,
350 )
351 .flatMap((directory) => names.map((name) => path.join(directory, name))),
352 ];
353 for (const candidate of candidates) {
354 if (yield* resolveCommandPath(candidate, { env: environment })) return true;
355 }
356​
357 const declinedFile = path.join(runtimeDir, "install-prompt-declined");
358 const declined = yield* fs.readFileString(declinedFile).pipe(Effect.orElseSucceed(() => ""));
359 const minor = minorRelease(packageJson.version);
360 if (declined.trim() === minor) return true;
361 if (!(yield* input.foreground)) return true;
362​
363 const installHint = `Run \`${yield* resolveCliCommand("install")}\` any time.`;
364 const saveDecline = fs.writeFileString(declinedFile, `${minor}\n`).pipe(Effect.ignore);
365 const answer = yield* input.confirm.pipe(Effect.timeoutOption(PROMPT_TIMEOUT));
366 if (Option.isNone(answer)) {
367 yield* saveDecline;
368 yield* Console.log(`\nNo answer, so t3 was not installed. ${installHint}\n`);
369 return true;
370 }
371 if (answer.value === undefined) return false;
372 if (!answer.value) {
373 yield* saveDecline;
374 yield* Console.log(`Skipped. ${installHint}\n`);
375 return true;
376 }
377 yield* installCli().pipe(
378 Effect.flatMap(reportInstalled),
379 Effect.catch((error) =>
380 Effect.andThen(saveDecline, Console.error(`Could not install t3: ${error.message}`)),
381 ),
382 );
383 yield* Console.log("");
384 return true;
385});
386​
387export const confirmCliInstall = Prompt.run(
388 Prompt.Confirm({
389 message: "Install the t3 command? Then you can run `t3` directly.",
390 initial: true,
391 }),
392).pipe(Effect.catchTags({ QuitError: () => Effect.void }));