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

install.test.ts

361 lines16.5 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as Console from "effect/Console";
5import * as Deferred from "effect/Deferred";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as FileSystem from "effect/FileSystem";
9import * as Path from "effect/Path";
10import * as TestClock from "effect/testing/TestClock";
11import { Command } from "effect/cli";
12​
13import packageJson from "../../package.json" with { type: "json" };
14import { posixLauncherScript } from "../cloud/pinnedRuntime.ts";
15import {
16 installCli,
17 installCommand,
18 isForegroundProcStat,
19 isForegroundPs,
20 offerCliInstall,
21} from "./install.ts";
22​
23const VERSION = packageJson.version;
24​
25/** A standalone runtime in a temp T3 home, started by the npm launcher from an npx cache. */
26const setup = Effect.gen(function* () {
27 const fs = yield* FileSystem.FileSystem;
28 const path = yield* Path.Path;
29 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-install-" });
30 const runtimeDir = path.join(root, ".t3/runtime");
31 const executable = path.join(runtimeDir, "versions", VERSION, "t3");
32 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
33 yield* fs.writeFileString(executable, "");
34 const npmPackage = path.join(root, ".npm/_npx/abc/node_modules/t3");
35 yield* fs.makeDirectory(path.join(npmPackage, "bin"), { recursive: true });
36 yield* fs.writeFileString(
37 path.join(npmPackage, "package.json"),
38 JSON.stringify({ name: "t3", version: VERSION }),
39 );
40 const binDir = path.join(root, "bin");
41 const provide = <A, E, R>(effect: Effect.Effect<A, E, R>, env: NodeJS.ProcessEnv = {}) =>
42 effect.pipe(
43 Effect.provideService(HostProcess.Platform, "linux"),
44 Effect.provideService(HostProcess.HomeDirectory, root),
45 Effect.provideService(HostProcess.IsExecutable, true),
46 Effect.provideService(HostProcess.ExecutablePath, executable),
47 Effect.provideService(HostProcess.Environment, {
48 PATH: "/usr/bin",
49 SHELL: "/bin/zsh",
50 T3CODE_INSTALL_BIN_DIR: binDir,
51 T3CODE_NPM_LAUNCHER_PATH: path.join(npmPackage, "bin/t3.mjs"),
52 ...env,
53 }),
54 );
55 return { root, npmPackage, runtimeDir, executable, link: path.join(binDir, "t3"), provide };
56});
57​
58it.layer(NodeServices.layer)("t3 install", (it) => {
59 it.effect("installs the running runtime, records it, and never replaces another t3", () =>
60 Effect.gen(function* () {
61 const fs = yield* FileSystem.FileSystem;
62 const path = yield* Path.Path;
63 const { root, runtimeDir, executable, link, provide } = yield* setup;
64​
65 const older = path.join(runtimeDir, "versions/0.0.1/t3");
66 yield* fs.makeDirectory(path.dirname(link), { recursive: true });
67 yield* fs.symlink(older, link);
68 const installed = yield* provide(installCli());
69 assert.equal(yield* fs.readFileString(link), posixLauncherScript(executable));
70 assert.isFalse(installed.onPath);
71 assert.include(installed.pathCommand, "$HOME/bin");
72​
73 // A link written through a symlinked T3 home is still ours.
74 const alias = path.join(root, "alias");
75 yield* fs.symlink(path.join(root, ".t3"), alias);
76 yield* fs.remove(link);
77 yield* fs.symlink(path.join(alias, "runtime/versions", VERSION, "t3"), link);
78 const onPath = yield* provide(installCli(), { PATH: `/usr/bin:${path.join(root, "bin")}/` });
79 assert.isTrue(onPath.onPath);
80 // Another t3 earlier on PATH still runs first, so `t3` would not run this one.
81 const binDir = path.join(root, "bin");
82 const otherBin = path.join(root, "other-bin");
83 yield* fs.makeDirectory(otherBin);
84 yield* fs.writeFileString(path.join(otherBin, "t3"), "", { mode: 0o755 });
85 const installIn = (cwd: string, PATH: string) =>
86 provide(installCli().pipe(Effect.provideService(HostProcess.WorkingDirectory, cwd)), {
87 PATH,
88 });
89 const assertShadowed = (result: Effect.Success<ReturnType<typeof installCli>>) => {
90 assert.isFalse(result.onPath);
91 assert.equal(result.shadowedBy, path.join(otherBin, "t3"));
92 assert.isUndefined(result.pathCommand);
93 };
94 assertShadowed(yield* provide(installCli(), { PATH: `${otherBin}:${binDir}` }));
95 // Relative and empty entries resolve against the working directory.
96 assertShadowed(yield* installIn(root, `other-bin:${binDir}`));
97 assertShadowed(yield* installIn(otherBin, `:${binDir}`));
98 // An empty PATH is not the working directory.
99 const offPath = yield* installIn(otherBin, "");
100 assert.isUndefined(offPath.shadowedBy);
101 assert.isDefined(offPath.pathCommand);
102 // A symlink to binDir, or a relative entry to it that wins first, is this install.
103 yield* fs.remove(alias);
104 yield* fs.symlink(binDir, alias);
105 for (const pathEnv of [`${alias}:${otherBin}`, `bin:other-bin:${binDir}`]) {
106 const installedOnPath = yield* installIn(root, pathEnv);
107 assert.isTrue(installedOnPath.onPath);
108 assert.isUndefined(installedOnPath.shadowedBy);
109 }
110 yield* fs.remove(alias);
111 yield* fs.remove(path.join(otherBin, "t3"));
112 yield* fs.makeDirectory(path.join(otherBin, "t3"));
113 const directory = yield* provide(installCli(), {
114 PATH: `${otherBin}:${path.join(root, "bin")}`,
115 });
116 assert.isTrue(directory.onPath);
117 assert.isUndefined(directory.shadowedBy);
118 const recorded = yield* fs.readFileString(path.join(runtimeDir, "launchers"));
119 assert.equal(recorded, `\n${yield* fs.realPath(path.join(root, "bin"))}/t3\n`);
120​
121 yield* fs.remove(link);
122 yield* fs.writeFileString(link, "#!/bin/sh\n");
123 const error = yield* provide(installCli()).pipe(Effect.flip);
124 assert.include(error.message, "Another t3 is already at");
125 assert.equal(yield* fs.readFileString(link), "#!/bin/sh\n");
126​
127 // Only `<version>/t3` is ours, not another program inside a version.
128 yield* fs.remove(link);
129 yield* fs.symlink(path.join(runtimeDir, "versions/0.0.1/node"), link);
130 const sibling = yield* provide(installCli()).pipe(Effect.flip);
131 assert.include(sibling.message, "Another t3 is already at");
132 // This home's desktop launcher is replaced, as install.sh does.
133 yield* fs.remove(link);
134 yield* fs.symlink(path.join(root, ".t3/bin/t3"), link);
135 yield* provide(installCli());
136 assert.equal(yield* fs.readFileString(link), posixLauncherScript(executable));
137​
138 // A script an earlier install wrote is ours too.
139 yield* fs.writeFileString(link, posixLauncherScript(older));
140 yield* provide(installCli());
141 assert.equal(yield* fs.readFileString(link), posixLauncherScript(executable));
142​
143 // An empty spot is created exclusively: a file that appears first is kept.
144 yield* fs.remove(link);
145 const racing = installCli().pipe(
146 Effect.provideService(FileSystem.FileSystem, {
147 ...fs,
148 link: (from, to) =>
149 fs
150 .writeFileString(to, "#!/bin/sh\necho raced\n")
151 .pipe(Effect.andThen(fs.link(from, to))),
152 }),
153 );
154 assert.include((yield* provide(racing).pipe(Effect.flip)).message, "Could not write");
155 assert.equal(yield* fs.readFileString(link), "#!/bin/sh\necho raced\n");
156 yield* fs.remove(link);
157​
158 // Windows writes a t3.cmd: only over its own, and only for paths cmd can run.
159 const shim = path.join(root, "bin", "t3.cmd");
160 const windows = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
161 provide(effect.pipe(Effect.provideService(HostProcess.Platform, "win32")));
162 const desktopShim =
163 '@echo off\r\nrem Written by T3 Code\r\n"C:\\T3 Code\\T3 Code.exe" "x" %*\r\n';
164 yield* fs.writeFileString(shim, desktopShim);
165 const foreignShim = yield* windows(installCli()).pipe(Effect.flip);
166 assert.include(foreignShim.message, "Another t3 is already at");
167 assert.equal(yield* fs.readFileString(shim), desktopShim);
168 // A user's wrapper that also runs a managed t3.exe is still theirs.
169 const wrapper = `@echo off\r\nset FOO=1\r\n"${path.join(runtimeDir, "versions/0.0.1/t3.exe")}" %*`;
170 yield* fs.writeFileString(shim, wrapper);
171 yield* windows(installCli()).pipe(Effect.flip);
172 assert.equal(yield* fs.readFileString(shim), wrapper);
173 // A dangling symlink is not free; writing through it would land outside the bin folder.
174 const elsewhere = path.join(root, "elsewhere.cmd");
175 yield* fs.remove(shim);
176 yield* fs.symlink(elsewhere, shim);
177 yield* windows(installCli()).pipe(Effect.flip);
178 assert.isFalse(yield* fs.exists(elsewhere));
179 yield* fs.remove(shim);
180 yield* fs.writeFileString(
181 shim,
182 `@echo off\r\n"${path.join(runtimeDir, "versions/0.0.1/t3.exe")}" %*`,
183 );
184 const windowsInstalled = yield* windows(installCli());
185 assert.equal(yield* fs.readFileString(shim), `@echo off\r\n"${executable}" %*`);
186 // A PowerShell command for this window; the saved PATH is left to the user.
187 assert.equal(windowsInstalled.pathCommand, `$env:Path += ';${path.join(root, "bin")}'`);
188 const unrunnable = yield* windows(
189 installCli().pipe(
190 Effect.provideService(
191 HostProcess.ExecutablePath,
192 path.join(runtimeDir, "versions/100%/t3"),
193 ),
194 ),
195 ).pipe(Effect.flip);
196 assert.include(unrunnable.message, "has % or non-ASCII characters");
197 }),
198 );
199​
200 it.effect("prints a shell-ready launcher command when another t3 runs first", () =>
201 Effect.gen(function* () {
202 const fs = yield* FileSystem.FileSystem;
203 const path = yield* Path.Path;
204 const { root, provide } = yield* setup;
205 const otherBin = path.join(root, "other-bin");
206 const newBin = path.join(root, "new bin");
207 yield* fs.makeDirectory(otherBin);
208 yield* fs.writeFileString(path.join(otherBin, "t3"), "", { mode: 0o755 });
209 const output: Array<string> = [];
210 yield* provide(Command.runWith(installCommand, { version: VERSION })([]), {
211 PATH: `${otherBin}:${newBin}`,
212 T3CODE_INSTALL_BIN_DIR: newBin,
213 }).pipe(
214 Effect.provideService(Console.Console, {
215 ...globalThis.console,
216 log: (...args: ReadonlyArray<unknown>) => {
217 output.push(args.join(" "));
218 },
219 }),
220 );
221 assert.include(output.join("\n"), `so run '${path.join(newBin, "t3")}' to use this one.`);
222 }),
223 );
224​
225 it.effect("asks npx users without a t3 command once per minor release and installs on yes", () =>
226 Effect.gen(function* () {
227 const fs = yield* FileSystem.FileSystem;
228 const path = yield* Path.Path;
229 const { root, npmPackage, runtimeDir, executable, link, provide } = yield* setup;
230 let asked = 0;
231 const offer = (
232 answer: boolean | undefined | Effect.Effect<boolean>,
233 options: {
234 readonly args?: ReadonlyArray<string>;
235 readonly env?: NodeJS.ProcessEnv;
236 readonly interactive?: boolean;
237 readonly foreground?: boolean;
238 } = {},
239 ) =>
240 provide(
241 offerCliInstall({
242 args: options.args ?? ["connect"],
243 interactive: options.interactive ?? true,
244 foreground: Effect.succeed(options.foreground ?? true),
245 confirm: Effect.andThen(
246 Effect.sync(() => (asked += 1)),
247 Effect.isEffect(answer) ? answer : Effect.succeed(answer),
248 ),
249 }),
250 options.env,
251 );
252​
253 // Scripts, CI, sudo, dumb terminals, background jobs, and help never ask.
254 yield* offer(false, { interactive: false });
255 yield* offer(false, { env: { CI: "true" } });
256 yield* offer(false, { env: { SUDO_USER: "theo" } });
257 yield* offer(false, { env: { TERM: "dumb" } });
258 yield* offer(false, { env: { npm_config_yes: "true" } });
259 yield* offer(false, { args: ["--completions", "zsh"] });
260 yield* offer(false, { foreground: false });
261 yield* offer(false, { args: ["connect", "--help"] });
262 yield* offer(false, { args: ["--log-level", "debug", "install"] });
263 yield* offer(false, { args: ["status", "--json"] });
264 yield* offer(false, { args: ["up", "--yes"] });
265 yield* offer(false, { args: ["status", "--json=true"] });
266 yield* offer(false, { args: ["auth", "session", "issue", "--token-only"] });
267 const globalBin = path.join(root, "global-bin");
268 yield* fs.makeDirectory(globalBin);
269 yield* fs.writeFileString(path.join(globalBin, "t3"), "");
270 yield* fs.chmod(path.join(globalBin, "t3"), 0o755);
271 yield* offer(false, { env: { PATH: globalBin } });
272 assert.equal(asked, 0);
273 assert.isFalse(yield* fs.exists(link));
274​
275 // A directory or non-executable file named `t3` on PATH is not an installed t3.
276 const dirBin = path.join(root, "dir-bin");
277 yield* fs.makeDirectory(path.join(dirBin, "t3"), { recursive: true });
278 const nonExecBin = path.join(root, "non-exec-bin");
279 yield* fs.makeDirectory(nonExecBin);
280 yield* fs.writeFileString(path.join(nonExecBin, "t3"), "");
281 assert.isFalse(yield* offer(undefined, { env: { PATH: dirBin } }));
282 assert.equal(asked, 1);
283 assert.isFalse(yield* offer(undefined, { env: { PATH: nonExecBin } }));
284 assert.equal(asked, 2);
285 asked = 0;
286​
287 // A runner's own .bin on PATH, even found through a bare launcher record, is not an installed t3.
288 const npxBin = path.join(npmPackage, "../.bin");
289 const pnpmBin = path.join(root, ".cache/pnpm/dlx/abc/node_modules/.bin");
290 for (const bin of [npxBin, pnpmBin]) {
291 yield* fs.makeDirectory(bin, { recursive: true });
292 yield* fs.writeFileString(path.join(bin, "t3"), "");
293 yield* fs.chmod(path.join(bin, "t3"), 0o755);
294 }
295 yield* fs.writeFileString(path.join(runtimeDir, "launchers"), "t3\n");
296 assert.isFalse(yield* offer(undefined, { env: { PATH: `${npxBin}:${pnpmBin}` } }));
297 assert.equal(asked, 1);
298 assert.isFalse(yield* fs.exists(path.join(runtimeDir, "install-prompt-declined")));
299 asked = 0;
300​
301 // `service install` is not `t3 install`; it still leaves the command unlinked.
302 yield* offer(false, { args: ["service", "install"] });
303 assert.equal(asked, 1);
304 yield* offer(false);
305 assert.equal(asked, 1);
306 assert.isFalse(yield* fs.exists(link));
307​
308 yield* fs.writeFileString(path.join(runtimeDir, "install-prompt-declined"), "0.0\n");
309 yield* offer(true);
310 assert.equal(asked, 2);
311 assert.equal(yield* fs.readFileString(link), posixLauncherScript(executable));
312​
313 yield* fs.remove(path.join(runtimeDir, "install-prompt-declined"));
314 yield* offer(true);
315 assert.equal(asked, 2);
316​
317 // A yes that cannot install, and no answer at all, also wait for the next minor release.
318 const declined = path.join(runtimeDir, "install-prompt-declined");
319 yield* fs.remove(link);
320 yield* fs.remove(path.join(runtimeDir, "launchers"));
321 yield* fs.writeFileString(link, "#!/bin/sh\necho mine\n");
322 asked = 0;
323 assert.isTrue(yield* offer(true));
324 assert.equal(yield* fs.readFileString(link), "#!/bin/sh\necho mine\n");
325 assert.equal(
326 (yield* fs.readFileString(declined)).trim(),
327 VERSION.split(".").slice(0, 2).join("."),
328 );
329 yield* offer(true);
330 assert.equal(asked, 1);
331​
332 yield* fs.remove(declined);
333 yield* fs.remove(link);
334 const waiting = yield* Deferred.make<void>();
335 const unanswered = yield* offer(
336 Effect.andThen(Deferred.succeed(waiting, undefined), Effect.never),
337 ).pipe(Effect.forkChild);
338 yield* Deferred.await(waiting);
339 yield* TestClock.adjust("30 seconds");
340 assert.isTrue(yield* Fiber.join(unanswered));
341 assert.isTrue(yield* fs.exists(declined));
342 assert.isFalse(yield* fs.exists(link));
343 }),
344 );
345​
346 it.effect("reads the terminal's foreground group from /proc and ps", () =>
347 Effect.sync(() => {
348 // The command name can hold spaces and parentheses.
349 const stat = (pgrp: number, tpgid: number) =>
350 `4242 (t3 (serve) x) S 100 ${pgrp} 100 34816 ${tpgid} 4194560 0 0`;
351 assert.isTrue(isForegroundProcStat(stat(4242, 4242)));
352 assert.isFalse(isForegroundProcStat(stat(4242, 4300)));
353 assert.isFalse(isForegroundProcStat(stat(4242, -1)));
354 assert.isFalse(isForegroundProcStat(""));
355 assert.isTrue(isForegroundPs(" 4242 4242\n"));
356 assert.isFalse(isForegroundPs(" 4300 4242\n"));
357 assert.isFalse(isForegroundPs(" -1 4242\n"));
358 assert.isFalse(isForegroundPs(""));
359 }),
360 );
361});