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