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

shell.test.ts

1,218 lines42.7 KB

1// @effect-diagnostics nodeBuiltinImport:off -- The synchronous shell probe runs real commands with isolated config files.
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { it as effectIt } from "@effect/vitest";
4import * as HostProcess from "@t3tools/shared/HostProcess";
5import { DesktopHostTelemetryMessage } from "@t3tools/contracts";
6import * as Schema from "effect/Schema";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as FileSystem from "effect/FileSystem";
10import * as Path from "effect/Path";
11import * as Option from "effect/Option";
12import * as TestClock from "effect/testing/TestClock";
13import * as NodeChildProcess from "node:child_process";
14import * as NodeFS from "node:fs";
15import * as NodeOS from "node:os";
16import * as NodePath from "node:path";
17import { describe, expect, it, vi } from "vite-plus/test";
18​
19import {
20 applyShellEnvironment,
21 pathSetup,
22 pathSetupCommand,
23 CommandAvailability,
24 CommandResolutionCache,
25 type CommandAvailabilityChecker,
26 isCommandAvailable,
27 listLoginShellCandidates,
28 mergePathEntries,
29 mergePathValues,
30 npmShimExecutable,
31 preferGitForWindowsBinary,
32 readEnvironmentFromLoginShell,
33 readEnvironmentFromWindowsShell,
34 resolveCommandPath,
35 resolveSpawnCommand,
36 resolveWindowsEnvironment,
37 runsGitWithoutConsole,
38 SpawnExecutableResolution,
39 WindowsShellEnvironment,
40 withPathDirectoryListings,
41 type WindowsShellEnvironmentReader,
42 XcodeGitLocation,
43} from "./shell.ts";
44​
45const decodeDesktopHostMessage = Schema.decodeUnknownSync(DesktopHostTelemetryMessage);
46​
47const nativeProbe = vi.hoisted(() => ({
48 execFile: vi.fn<typeof import("node:child_process").execFile>(),
49 original: undefined as unknown as typeof import("node:child_process").execFile,
50}));
51​
52vi.mock("node:child_process", async (importOriginal) => {
53 const original = await importOriginal<typeof import("node:child_process")>();
54 nativeProbe.original = original.execFile;
55 return { ...original, execFile: nativeProbe.execFile.mockImplementation(original.execFile) };
56});
57​
58const withWindowsEnvironmentMocks = <A, E, R>(
59 effect: Effect.Effect<A, E, R>,
60 readEnvironment: (
61 ...args: Parameters<WindowsShellEnvironmentReader>
62 ) => Partial<Record<string, string>>,
63 commandAvailable: CommandAvailabilityChecker,
64) =>
65 effect.pipe(
66 Effect.provideService(WindowsShellEnvironment, (...args) =>
67 Effect.sync(() => readEnvironment(...args)),
68 ),
69 Effect.provideService(CommandAvailability, commandAvailable),
70 );
71​
72describe("readEnvironmentFromLoginShell", () => {
73 // Opt in with an explicit binary, like the provider live probes; CI need not install Nu.
74 it.runIf(process.env.T3_TEST_NU_PATH !== undefined)(
75 "captures Nushell PATH and multiline values without external tools",
76 () => {
77 const shell = process.env.T3_TEST_NU_PATH!;
78 const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-nu-env-"));
79 try {
80 const toolPath = NodePath.join(home, "nu tools", "bin");
81 const extraToolPath = NodePath.join(home, "extra-tools", "bin");
82 NodeFS.mkdirSync(toolPath, { recursive: true });
83 NodeFS.mkdirSync(extraToolPath, { recursive: true });
84 const config = NodePath.join(home, "config.nu");
85 const envConfig = NodePath.join(home, "env.nu");
86 NodeFS.writeFileSync(envConfig, "");
87 NodeFS.writeFileSync(
88 config,
89 [
90 `$env.PATH = [${JSON.stringify(toolPath)}, "~/extra-tools/bin", "rel/dir", ""]`,
91 '$env.CUSTOM_VAR = " first\\nsecond "',
92 '$env.EMPTY_VAR = ""',
93 'print "startup noise"',
94 ].join("\n"),
95 );
96​
97 expect(
98 readEnvironmentFromLoginShell(
99 shell,
100 ["MISSING_VAR", "PATH", "EMPTY_VAR", "CUSTOM_VAR"],
101 (file, args, options) =>
102 NodeChildProcess.execFileSync(
103 file,
104 ["--no-history", "--config", config, "--env-config", envConfig, ...args],
105 {
106 ...options,
107 env: { HOME: home, XDG_CONFIG_HOME: home, PATH: toolPath },
108 },
109 ),
110 ),
111 ).toEqual({
112 PATH: `${toolPath}:${extraToolPath}:rel/dir:`,
113 CUSTOM_VAR: " first\nsecond ",
114 });
115 } finally {
116 NodeFS.rmSync(home, { recursive: true, force: true });
117 }
118 },
119 );
120​
121 it("extracts multiple environment variables from a login shell command", () => {
122 const execFile = vi.fn<
123 (
124 file: string,
125 args: ReadonlyArray<string>,
126 options: { encoding: "utf8"; timeout: number },
127 ) => string
128 >(() =>
129 [
130 "__T3CODE_ENV_PATH_START__",
131 "/a:/b",
132 "__T3CODE_ENV_PATH_END__",
133 "__T3CODE_ENV_SSH_AUTH_SOCK_START__",
134 "/tmp/secretive.sock",
135 "__T3CODE_ENV_SSH_AUTH_SOCK_END__",
136 ].join("\n"),
137 );
138​
139 expect(readEnvironmentFromLoginShell("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"], execFile)).toEqual({
140 PATH: "/a:/b",
141 SSH_AUTH_SOCK: "/tmp/secretive.sock",
142 });
143 expect(execFile).toHaveBeenCalledTimes(1);
144 expect(execFile).toHaveBeenCalledWith("/bin/zsh", expect.any(Array), {
145 encoding: "utf8",
146 timeout: 5000,
147 killSignal: "SIGKILL",
148 detached: true,
149 stdio: ["ignore", "pipe", "ignore"],
150 });
151 });
152​
153 it("omits environment variables that are missing or empty", () => {
154 const execFile = vi.fn<
155 (
156 file: string,
157 args: ReadonlyArray<string>,
158 options: { encoding: "utf8"; timeout: number },
159 ) => string
160 >(() =>
161 [
162 "__T3CODE_ENV_PATH_START__",
163 "/a:/b",
164 "__T3CODE_ENV_PATH_END__",
165 "__T3CODE_ENV_SSH_AUTH_SOCK_START__",
166 "__T3CODE_ENV_SSH_AUTH_SOCK_END__",
167 ].join("\n"),
168 );
169​
170 expect(readEnvironmentFromLoginShell("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"], execFile)).toEqual({
171 PATH: "/a:/b",
172 });
173 });
174​
175 it("preserves multiline values and surrounding whitespace", () => {
176 const execFile = vi.fn<
177 (
178 file: string,
179 args: ReadonlyArray<string>,
180 options: { encoding: "utf8"; timeout: number },
181 ) => string
182 >(() =>
183 [
184 "__T3CODE_ENV_CUSTOM_VAR_START__",
185 " first\nsecond ",
186 "__T3CODE_ENV_CUSTOM_VAR_END__",
187 ].join("\n"),
188 );
189​
190 expect(readEnvironmentFromLoginShell("/bin/zsh", ["CUSTOM_VAR"], execFile)).toEqual({
191 CUSTOM_VAR: " first\nsecond ",
192 });
193 });
194});
195​
196describe("listLoginShellCandidates", () => {
197 it("returns env shell, user shell, then the platform fallback without duplicates", () => {
198 expect(listLoginShellCandidates("darwin", " /opt/homebrew/bin/nu ", "/bin/zsh")).toEqual([
199 "/opt/homebrew/bin/nu",
200 "/bin/zsh",
201 ]);
202 });
203});
204​
205describe("mergePathEntries", () => {
206 it("prefers login-shell PATH entries and keeps inherited extras", () => {
207 expect(
208 mergePathEntries("/opt/homebrew/bin:/usr/bin", "/Users/test/.local/bin:/usr/bin", "darwin"),
209 ).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
210 });
211});
212​
213describe("readEnvironmentFromWindowsShell", () => {
214 effectIt.effect("yields while the native shell probe is pending", () =>
215 Effect.gen(function* () {
216 let completed = false;
217 const [environment, completedBeforeProbeReturned] = yield* Effect.all(
218 [
219 readEnvironmentFromWindowsShell(["PATH"]).pipe(
220 Effect.tap(() =>
221 Effect.sync(() => {
222 completed = true;
223 }),
224 ),
225 ),
226 Effect.sync(() => completed),
227 ],
228 { concurrency: 2 },
229 );
230 expect(completedBeforeProbeReturned).toBe(false);
231 expect(environment).toBeTypeOf("object");
232 }),
233 );
234​
235 effectIt.layer(NodeServices.layer)("synchronous spawn failures", (it) => {
236 it.effect("tries both shells and preserves baseline PATH repair", () =>
237 Effect.gen(function* () {
238 const execFile = nativeProbe.execFile;
239 execFile.mockImplementationOnce(() => {
240 throw new Error("spawn EPERM");
241 });
242 execFile.mockImplementationOnce(() => {
243 throw new Error("spawn EINVAL");
244 });
245 try {
246 const patch = yield* resolveWindowsEnvironment({
247 PATH: "C:\\Windows",
248 APPDATA: "C:\\Roaming",
249 }).pipe(Effect.provideService(CommandAvailability, () => Effect.succeed(true)));
250 expect(patch).toEqual({ PATH: "C:\\Windows;C:\\Roaming\\npm" });
251 expect(execFile.mock.calls.slice(-2).map(([file]) => file)).toEqual([
252 "pwsh.exe",
253 "powershell.exe",
254 ]);
255 } finally {
256 execFile.mockClear();
257 }
258 }),
259 );
260 });
261​
262 effectIt.effect("returns an empty environment after both shell candidates fail", () =>
263 Effect.gen(function* () {
264 const execFile = vi.fn(() => Effect.succeed(Option.none<string>()));
265 expect(yield* readEnvironmentFromWindowsShell(["PATH"], {}, execFile)).toEqual({});
266 expect(execFile).toHaveBeenCalledTimes(2);
267 }),
268 );
269​
270 effectIt.effect("does not launch a shell when no variables are requested", () =>
271 Effect.gen(function* () {
272 const execFile = vi.fn(() => Effect.succeed(Option.none<string>()));
273 expect(yield* readEnvironmentFromWindowsShell([], {}, execFile)).toEqual({});
274 expect(execFile).not.toHaveBeenCalled();
275 }),
276 );
277​
278 effectIt.effect(
279 "kills the native probe child on interruption without trying the next shell",
280 () =>
281 Effect.gen(function* () {
282 const started = Promise.withResolvers<void>();
283 const kill = vi.fn(() => true);
284 const child = { kill, unref: vi.fn() } as unknown as ReturnType<
285 typeof import("node:child_process").execFile
286 >;
287 const execFile = nativeProbe.execFile;
288 execFile.mockClear();
289 execFile.mockImplementationOnce(() => {
290 started.resolve();
291 return child;
292 });
293 try {
294 const fiber = yield* readEnvironmentFromWindowsShell(["PATH"]).pipe(Effect.forkChild);
295 yield* Effect.promise(() => started.promise);
296 yield* Fiber.interrupt(fiber);
297 expect(kill).toHaveBeenCalledTimes(1);
298 expect(execFile).toHaveBeenCalledTimes(1);
299 expect(execFile.mock.calls[0]?.[0]).toBe("pwsh.exe");
300 } finally {
301 execFile.mockClear();
302 }
303 }),
304 );
305​
306 effectIt.effect("gives up on a shell that survives the kill and holds stdout open", () =>
307 Effect.gen(function* () {
308 const stdout = { destroy: vi.fn() };
309 const unref = vi.fn();
310 const child = { kill: vi.fn(() => true), stdout, unref } as unknown as ReturnType<
311 typeof import("node:child_process").execFile
312 >;
313 const execFile = nativeProbe.execFile;
314 execFile.mockClear();
315 execFile.mockImplementation(() => child);
316 try {
317 const fiber = yield* readEnvironmentFromWindowsShell(["PATH"]).pipe(Effect.forkChild);
318 yield* Effect.yieldNow;
319 yield* TestClock.adjust("6 seconds");
320 expect(execFile.mock.calls.map(([file]) => file)).toEqual(["pwsh.exe", "powershell.exe"]);
321 yield* TestClock.adjust("6 seconds");
322 expect(yield* Fiber.join(fiber)).toEqual({});
323 expect(stdout.destroy).toHaveBeenCalledTimes(2);
324 expect(unref).toHaveBeenCalledTimes(2);
325 } finally {
326 execFile.mockReset();
327 execFile.mockImplementation(nativeProbe.original);
328 }
329 }),
330 );
331​
332 effectIt.effect("extracts environment variables from a PowerShell command", () =>
333 Effect.gen(function* () {
334 const execFile = vi.fn<
335 (
336 file: string,
337 args: ReadonlyArray<string>,
338 options: { encoding: "utf8"; timeout: number },
339 ) => string
340 >(
341 () =>
342 "__T3CODE_ENV_PATH_START__\nC:\\Users\\testuser\\AppData\\Roaming\\npm\n__T3CODE_ENV_PATH_END__\n",
343 );
344​
345 expect(
346 yield* readEnvironmentFromWindowsShell(["PATH"], {}, (...args) =>
347 Effect.sync(() => Option.liftThrowable(execFile)(...args)),
348 ),
349 ).toEqual({
350 PATH: "C:\\Users\\testuser\\AppData\\Roaming\\npm",
351 });
352 expect(execFile).toHaveBeenCalledWith(
353 "pwsh.exe",
354 expect.arrayContaining(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"]),
355 { encoding: "utf8", timeout: 5000 },
356 );
357 }),
358 );
359​
360 effectIt.effect("strips CRLF delimiters from captured PowerShell values", () =>
361 Effect.gen(function* () {
362 const execFile = vi.fn<
363 (
364 file: string,
365 args: ReadonlyArray<string>,
366 options: { encoding: "utf8"; timeout: number },
367 ) => string
368 >(
369 () =>
370 "__T3CODE_ENV_FNM_DIR_START__\r\nC:\\Users\\testuser\\AppData\\Roaming\\fnm\r\n__T3CODE_ENV_FNM_DIR_END__\r\n",
371 );
372​
373 expect(
374 yield* readEnvironmentFromWindowsShell(["FNM_DIR"], {}, (...args) =>
375 Effect.sync(() => Option.liftThrowable(execFile)(...args)),
376 ),
377 ).toEqual({
378 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
379 });
380 }),
381 );
382​
383 effectIt.effect("omits -NoProfile when loadProfile is enabled", () =>
384 Effect.gen(function* () {
385 const execFile = vi.fn<
386 (
387 file: string,
388 args: ReadonlyArray<string>,
389 options: { encoding: "utf8"; timeout: number },
390 ) => string
391 >(() => "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n");
392​
393 expect(
394 yield* readEnvironmentFromWindowsShell(["PATH"], { loadProfile: true }, (...args) =>
395 Effect.sync(() => Option.liftThrowable(execFile)(...args)),
396 ),
397 ).toEqual({
398 PATH: "C:\\Tools",
399 });
400 expect(execFile).toHaveBeenCalledWith(
401 "pwsh.exe",
402 expect.arrayContaining(["-NoLogo", "-NonInteractive", "-Command"]),
403 { encoding: "utf8", timeout: 5000 },
404 );
405 expect(execFile.mock.calls[0]?.[1]).not.toContain("-NoProfile");
406 }),
407 );
408​
409 effectIt.effect("falls back to Windows PowerShell when pwsh.exe is unavailable", () =>
410 Effect.gen(function* () {
411 const execFile = vi.fn<
412 (
413 file: string,
414 args: ReadonlyArray<string>,
415 options: { encoding: "utf8"; timeout: number },
416 ) => string
417 >((file) => {
418 if (file === "pwsh.exe") {
419 throw new Error("spawn pwsh.exe ENOENT");
420 }
421 return "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n";
422 });
423​
424 expect(
425 yield* readEnvironmentFromWindowsShell(["PATH"], {}, (...args) =>
426 Effect.sync(() => Option.liftThrowable(execFile)(...args)),
427 ),
428 ).toEqual({
429 PATH: "C:\\Tools",
430 });
431 expect(execFile).toHaveBeenNthCalledWith(1, "pwsh.exe", expect.any(Array), {
432 encoding: "utf8",
433 timeout: 5000,
434 });
435 expect(execFile).toHaveBeenNthCalledWith(2, "powershell.exe", expect.any(Array), {
436 encoding: "utf8",
437 timeout: 5000,
438 });
439 }),
440 );
441});
442​
443describe("mergePathValues", () => {
444 it("sanitizes and dedupes Windows entries while preserving preferred order", () => {
445 expect(
446 mergePathValues(
447 'C:\\Users\\testuser\\AppData\\Roaming\\npm;"C:\\Program Files\\nodejs"',
448 "c:\\users\\testuser\\appdata\\roaming\\npm;C:\\Windows\\System32",
449 "win32",
450 ),
451 ).toBe(
452 "C:\\Users\\testuser\\AppData\\Roaming\\npm;C:\\Program Files\\nodejs;C:\\Windows\\System32",
453 );
454 });
455​
456 it("removes stray quotes from Windows entries", () => {
457 expect(
458 mergePathValues(
459 'C:\\Windows\\System32;C:\\cloudflared.exe;C:";C:\\Program Files\\nodejs',
460 undefined,
461 "win32",
462 ),
463 ).toBe("C:\\Windows\\System32;C:\\cloudflared.exe;C:;C:\\Program Files\\nodejs");
464 });
465​
466 it("dedupes case-sensitively on POSIX", () => {
467 expect(mergePathValues("/usr/local/bin:/usr/bin", "/usr/bin:/USR/BIN", "linux")).toBe(
468 "/usr/local/bin:/usr/bin:/USR/BIN",
469 );
470 });
471});
472​
473effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => {
474 const recordProbes = (env: NodeJS.ProcessEnv) =>
475 Effect.gen(function* () {
476 const probed: Array<string> = [];
477 const result = yield* resolveCommandPath("definitely-not-installed", { env }).pipe(
478 Effect.provideService(HostProcess.Platform, "win32"),
479 Effect.provideService(CommandResolutionCache, new Map()),
480 Effect.provide(
481 FileSystem.layerNoop({
482 stat: (filePath) =>
483 Effect.sync(() => {
484 probed.push(filePath);
485 return { type: "Directory" } as FileSystem.File.Info;
486 }),
487 }),
488 ),
489 );
490​
491 expect(result).toBeNull();
492 return probed;
493 });
494​
495 it.effect("still visits a PATH entry that differs only in case", () =>
496 Effect.gen(function* () {
497 const probed = yield* recordProbes({
498 PATH: "C:\\bin;C:\\BIN",
499 PATHEXT: ".COM;.EXE",
500 });
501​
502 // Windows PATH directories can be case-sensitive; preserve both spellings.
503 expect(probed).toHaveLength(8);
504 }),
505 );
506​
507 it.effect.each(["audit-command", "audit-command.CMD"])(
508 "resolves lowercase executable files for %s in a case-sensitive Windows PATH directory",
509 (command) =>
510 Effect.gen(function* () {
511 const fs = yield* FileSystem.FileSystem;
512 const path = yield* Path.Path;
513 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-case-sensitive-path-" });
514 const executable = path.join(cwd, "audit-command.cmd");
515 yield* fs.writeFileString(executable, "@echo off\n");
516​
517 const resolved = yield* resolveCommandPath(command, {
518 env: { PATH: cwd, PATHEXT: ".CMD" },
519 }).pipe(
520 Effect.provideService(HostProcess.Platform, "win32"),
521 Effect.provideService(CommandResolutionCache, new Map()),
522 Effect.provideService(FileSystem.FileSystem, {
523 ...fs,
524 stat: (filePath) =>
525 fs.stat(filePath === executable ? filePath : path.join(cwd, "missing")),
526 }),
527 );
528​
529 expect(resolved).toBe(executable);
530 }),
531 );
532​
533 it.effect("probes only listed PATH names and relists a directory that changes", () =>
534 Effect.gen(function* () {
535 const fs = yield* FileSystem.FileSystem;
536 const path = yield* Path.Path;
537 const first = yield* fs.makeTempDirectoryScoped();
538 const second = yield* fs.makeTempDirectoryScoped();
539 yield* fs.writeFileString(path.join(first, "cursor.CMD"), "");
540 yield* fs.writeFileString(path.join(second, "cursor.EXE"), "");
541 const env = { PATH: `${first};${second}`, PATHEXT: ".EXE;.CMD" };
542 const probed: Array<string> = [];
543 yield* Effect.gen(function* () {
544 expect(yield* resolveCommandPath("cursor", { env })).toBe(path.join(first, "cursor.CMD"));
545 expect(yield* isCommandAvailable("absent", { env })).toBe(false);
546 yield* fs.writeFileString(path.join(second, "late.EXE"), "");
547 yield* fs.utimes(second, 4_102_444_800, 4_102_444_800);
548 expect(yield* resolveCommandPath("late", { env })).toBe(path.join(second, "late.EXE"));
549 }).pipe(
550 withPathDirectoryListings,
551 Effect.provideService(FileSystem.FileSystem, {
552 ...fs,
553 stat: (file) => {
554 if (file !== first && file !== second) probed.push(file);
555 return fs.stat(file);
556 },
557 }),
558 );
559 expect(probed).toEqual([path.join(first, "cursor.CMD"), path.join(second, "late.EXE")]);
560 }).pipe(
561 Effect.provideService(HostProcess.Platform, "win32"),
562 Effect.provideService(CommandResolutionCache, new Map()),
563 ),
564 );
565});
566​
567describe("runsGitWithoutConsole", () => {
568 const git = "C:\\Program Files\\Git\\ucrt64\\bin\\git.exe";
569​
570 it.each([
571 [["rev-parse", "--git-path", "index"], true],
572 [["--git-dir", "C:\\repo\\.git", "symbolic-ref", "refs/remotes/origin/HEAD"], true],
573 [["remote", "get-url", "--", "origin"], true],
574 [["config", "--get", "branch.main.pushRemote"], true],
575 [["symbolic-ref", "--quiet", "HEAD"], true],
576 [["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], true],
577 [["rev-parse", "HEAD"], false],
578 [["symbolic-ref", "HEAD", "refs/heads/x"], false],
579 [["symbolic-ref", "-qd", "refs/remotes/origin/HEAD"], false],
580 [["config", "--get", "--edit"], false],
581 [["-c", "core.pager=x", "config", "--get", "user.name"], false],
582 ])("Git for Windows %j without a console: %s", (args, expected) => {
583 expect(runsGitWithoutConsole("win32", git, args)).toBe(expected);
584 });
585​
586 it.each([
587 ["win32", "C:\\Program Files\\Git\\cmd\\git.exe"],
588 ["win32", "C:\\Users\\x\\scoop\\shims\\git.exe"],
589 ["linux", git],
590 ] as const)("keeps the console on %s for %s", (platform, executable) => {
591 expect(runsGitWithoutConsole(platform, executable, ["rev-parse", "--show-toplevel"])).toBe(
592 false,
593 );
594 });
595});
596​
597describe("preferGitForWindowsBinary", () => {
598 const files =
599 (...paths: Array<string>) =>
600 (filePath: string) =>
601 paths.includes(filePath);
602​
603 it("runs the git.exe Git for Windows' launcher would start", () => {
604 expect(
605 preferGitForWindowsBinary(
606 "C:\\Program Files\\Git\\cmd\\git.EXE",
607 {},
608 files(
609 "C:\\Program Files\\Git\\ucrt64\\bin\\git.exe",
610 "C:\\Program Files\\Git\\mingw64\\bin\\git.exe",
611 ),
612 ),
613 ).toBe("C:\\Program Files\\Git\\ucrt64\\bin\\git.exe");
614 expect(
615 preferGitForWindowsBinary(
616 "D:\\PortableGit\\bin\\git.exe",
617 {},
618 files("D:\\PortableGit\\mingw64\\bin\\git.exe"),
619 ),
620 ).toBe("D:\\PortableGit\\mingw64\\bin\\git.exe");
621 expect(
622 preferGitForWindowsBinary(
623 "C:\\Program Files\\Git\\cmd\\git.exe",
624 {},
625 files("C:\\Program Files\\Git\\clangarm64\\bin\\git.exe"),
626 ),
627 ).toBe("C:\\Program Files\\Git\\clangarm64\\bin\\git.exe");
628 });
629​
630 it("keeps the launcher when MSYSTEM is set", () => {
631 // git.exe adds hook dependencies to PATH only when MSYSTEM is unset.
632 expect(
633 preferGitForWindowsBinary(
634 "C:\\Program Files\\Git\\cmd\\git.exe",
635 { MSYSTEM: "MINGW64" },
636 files("C:\\Program Files\\Git\\mingw64\\bin\\git.exe"),
637 ),
638 ).toBe("C:\\Program Files\\Git\\cmd\\git.exe");
639 });
640​
641 it("leaves other gits and other launchers alone", () => {
642 const everything = () => true;
643 expect(preferGitForWindowsBinary("C:\\Users\\me\\scoop\\shims\\git.exe", {}, everything)).toBe(
644 "C:\\Users\\me\\scoop\\shims\\git.exe",
645 );
646 expect(preferGitForWindowsBinary("C:\\Program Files\\Git\\cmd\\gitk.exe", {}, everything)).toBe(
647 "C:\\Program Files\\Git\\cmd\\gitk.exe",
648 );
649 });
650});
651​
652// Byte for byte what `npm install -g opencode-ai` writes as `opencode.cmd`.
653const NPM_OPENCODE_SHIM = [
654 "@ECHO off",
655 "GOTO start",
656 ":find_dp0",
657 "SET dp0=%~dp0",
658 "EXIT /b",
659 ":start",
660 "SETLOCAL",
661 "CALL :find_dp0",
662 '"%dp0%\\node_modules\\opencode-ai\\bin\\opencode.exe" %*',
663 "",
664].join("\r\n");
665​
666describe("npmShimExecutable", () => {
667 const shimPath = "C:\\Users\\me\\AppData\\Roaming\\npm\\opencode.cmd";
668 const executable =
669 "C:\\Users\\me\\AppData\\Roaming\\npm\\node_modules\\opencode-ai\\bin\\opencode.exe";
670 const exists = (filePath: string) => filePath === executable;
671​
672 it("finds the executable npm's shim runs", () => {
673 expect(npmShimExecutable(shimPath, () => NPM_OPENCODE_SHIM, exists)).toBe(executable);
674 expect(
675 npmShimExecutable(shimPath.replace(".cmd", ".CMD"), () => NPM_OPENCODE_SHIM, exists),
676 ).toBe(executable);
677 });
678​
679 it("keeps a shim that does more than run the executable", () => {
680 const withSetting = NPM_OPENCODE_SHIM.replace(
681 "SETLOCAL",
682 "SETLOCAL\r\nSET OPENCODE_CONFIG=C:\\x",
683 );
684 expect(npmShimExecutable(shimPath, () => withSetting, exists)).toBeUndefined();
685 const nodeScript = NPM_OPENCODE_SHIM.replace(
686 '"%dp0%\\node_modules\\opencode-ai\\bin\\opencode.exe" %*',
687 '"%_prog%" "%dp0%\\node_modules\\opencode-ai\\bin\\opencode.js" %*',
688 );
689 expect(
690 npmShimExecutable(
691 shimPath,
692 () => nodeScript,
693 () => true,
694 ),
695 ).toBeUndefined();
696 });
697​
698 it("keeps a shim CMD would read differently", () => {
699 // CMD preserves trailing SET whitespace, changing the executable path.
700 for (const suffix of ["\u00a0", "\t", " "]) {
701 const altered = NPM_OPENCODE_SHIM.replace("SET dp0=%~dp0", `SET dp0=%~dp0${suffix}`);
702 expect(
703 npmShimExecutable(
704 shimPath,
705 () => altered,
706 () => true,
707 ),
708 ).toBeUndefined();
709 }
710 const nonBreakingSeparator = NPM_OPENCODE_SHIM.replace(
711 'opencode.exe" %*',
712 'opencode.exe"\u00a0%*',
713 );
714 expect(
715 npmShimExecutable(
716 shimPath,
717 () => nonBreakingSeparator,
718 () => true,
719 ),
720 ).toBeUndefined();
721 const indented = NPM_OPENCODE_SHIM.replace("SETLOCAL", " SETLOCAL");
722 expect(
723 npmShimExecutable(
724 shimPath,
725 () => indented,
726 () => true,
727 ),
728 ).toBeUndefined();
729 });
730​
731 it("keeps the shim when its executable is missing or it is not a .cmd", () => {
732 expect(
733 npmShimExecutable(
734 shimPath,
735 () => NPM_OPENCODE_SHIM,
736 () => false,
737 ),
738 ).toBeUndefined();
739 expect(
740 npmShimExecutable(
741 shimPath,
742 () => undefined,
743 () => true,
744 ),
745 ).toBeUndefined();
746 expect(
747 npmShimExecutable(
748 shimPath.replace(".cmd", ".bat"),
749 () => NPM_OPENCODE_SHIM,
750 () => true,
751 ),
752 ).toBeUndefined();
753 });
754});
755​
756effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => {
757 it.effect("runs Windows executables directly without a shell", () =>
758 Effect.gen(function* () {
759 const command = yield* resolveSpawnCommand("node.exe", ["script.js", "hello & goodbye"], {
760 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
761 }).pipe(
762 Effect.provideService(HostProcess.Platform, "win32"),
763 Effect.provideService(CommandResolutionCache, new Map()),
764 );
765​
766 expect(command).toEqual({
767 command: "node.exe",
768 args: ["script.js", "hello & goodbye"],
769 shell: false,
770 });
771 }),
772 );
773​
774 it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")(
775 "runs the executable behind an npm shim directly when asked",
776 () =>
777 Effect.scoped(
778 Effect.gen(function* () {
779 const fs = yield* FileSystem.FileSystem;
780 const path = yield* Path.Path;
781 const prefix = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-shim-" });
782 const shim = path.join(prefix, "opencode.cmd");
783 const executable = path.join(
784 prefix,
785 "node_modules",
786 "opencode-ai",
787 "bin",
788 "opencode.exe",
789 );
790 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
791 yield* fs.writeFileString(executable, "");
792 yield* fs.writeFileString(shim, NPM_OPENCODE_SHIM);
793 const resolve = (bypassNpmShim: boolean) =>
794 resolveSpawnCommand("opencode", ["serve", "--port=4096"], {
795 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
796 bypassNpmShim,
797 }).pipe(
798 Effect.provideService(HostProcess.Platform, "win32"),
799 Effect.provideService(CommandResolutionCache, new Map()),
800 Effect.provideService(SpawnExecutableResolution, () => shim),
801 );
802​
803 expect(yield* resolve(true)).toEqual({
804 command: executable,
805 args: ["serve", "--port=4096"],
806 shell: false,
807 });
808 expect((yield* resolve(false)).shell).toBe(true);
809 }),
810 ),
811 );
812​
813 it.effect("builds one escaped cmd.exe line for Windows command shims", () =>
814 Effect.gen(function* () {
815 const command = yield* resolveSpawnCommand(
816 "vp",
817 [
818 "run",
819 "value & calc",
820 "%PATH%",
821 'quote"value',
822 "C:\\dir with space\\",
823 'slash\\"quote',
824 "x|y<z>^",
825 ],
826 { env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" } },
827 ).pipe(
828 Effect.provideService(HostProcess.Platform, "win32"),
829 Effect.provideService(CommandResolutionCache, new Map()),
830 Effect.provideService(
831 SpawnExecutableResolution,
832 () => "C:\\Program Files\\npm & tools\\vp.cmd",
833 ),
834 );
835​
836 // No args alongside `shell: true`: Node prints DEP0190 for that pairing.
837 expect(command).toEqual({
838 command: [
839 String.raw`^"C:\Program^ Files\npm^ ^&^ tools\vp.cmd^"`,
840 String.raw`^"run^"`,
841 String.raw`^"value^ ^&^ calc^"`,
842 String.raw`^"^%PATH^%^"`,
843 String.raw`^"quote\^"value^"`,
844 String.raw`^"C:\dir^ with^ space\\^"`,
845 String.raw`^"slash\\\^"quote^"`,
846 String.raw`^"x^|y^<z^>^^^"`,
847 ].join(" "),
848 args: [],
849 shell: true,
850 });
851 }),
852 );
853​
854 it.effect("resolves against the effective environment when extending host env", () =>
855 Effect.gen(function* () {
856 let resolvedEnvironment: NodeJS.ProcessEnv | undefined;
857 yield* resolveSpawnCommand("codex", ["app-server"], {
858 env: { CODEX_HOME: "C:\\Users\\tester\\.codex" },
859 extendEnv: true,
860 }).pipe(
861 Effect.provideService(HostProcess.Platform, "win32"),
862 Effect.provideService(CommandResolutionCache, new Map()),
863 Effect.provideService(HostProcess.Environment, {
864 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
865 PATHEXT: ".COM;.EXE;.BAT;.CMD",
866 }),
867 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) => {
868 resolvedEnvironment = env;
869 return "C:\\Users\\tester\\AppData\\Roaming\\npm\\codex.cmd";
870 }),
871 );
872​
873 expect(resolvedEnvironment).toEqual({
874 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
875 PATHEXT: ".COM;.EXE;.BAT;.CMD",
876 CODEX_HOME: "C:\\Users\\tester\\.codex",
877 });
878 }),
879 );
880​
881 describe("macOS git", () => {
882 // Files that exist, the git first on PATH, and what `xcrun --find git` prints.
883 const setup = (options: {
884 readonly platform?: NodeJS.Platform;
885 readonly gitOnPath: string;
886 readonly xcrunGit: string | undefined;
887 }) => {
888 const files = new Set([options.gitOnPath, ...(options.xcrunGit ? [options.xcrunGit] : [])]);
889 const host = { xcrunGit: options.xcrunGit, xcrunCalls: 0 };
890 const resolve = resolveSpawnCommand("git", ["status"], { env: { PATH: "/fake/bin" } }).pipe(
891 Effect.map((resolved) => resolved.command),
892 Effect.provideService(HostProcess.Platform, options.platform ?? "darwin"),
893 Effect.provideService(SpawnExecutableResolution, (command) =>
894 command === "git" ? options.gitOnPath : files.has(command) ? command : undefined,
895 ),
896 Effect.provideService(XcodeGitLocation, () => {
897 host.xcrunCalls += 1;
898 return host.xcrunGit;
899 }),
900 );
901 return { files, host, resolve };
902 };
903​
904 const XCODE_GIT = "/Applications/Xcode.app/Contents/Developer/usr/bin/git";
905​
906 it.effect("runs the git behind the xcrun shim and looks it up once", () =>
907 Effect.gen(function* () {
908 const { host, resolve } = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
909 expect(yield* resolve).toBe(XCODE_GIT);
910 expect(yield* resolve).toBe(XCODE_GIT);
911 expect(host.xcrunCalls).toBe(1);
912 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
913 );
914​
915 it.effect("keeps git when PATH has another git or the host is not macOS", () =>
916 Effect.gen(function* () {
917 const homebrew = setup({ gitOnPath: "/opt/homebrew/bin/git", xcrunGit: XCODE_GIT });
918 expect(yield* homebrew.resolve).toBe("git");
919 expect(homebrew.host.xcrunCalls).toBe(0);
920​
921 const linux = setup({ platform: "linux", gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
922 expect(yield* linux.resolve).toBe("git");
923 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
924 );
925​
926 it.effect("keeps git when xcrun fails or names a missing file", () =>
927 Effect.gen(function* () {
928 const failed = setup({ gitOnPath: "/usr/bin/git", xcrunGit: undefined });
929 expect(yield* failed.resolve).toBe("git");
930​
931 const missing = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
932 missing.files.delete(XCODE_GIT);
933 expect(yield* missing.resolve).toBe("git");
934 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
935 );
936​
937 it.effect("looks again when the resolved git disappears", () =>
938 Effect.gen(function* () {
939 const betaGit = "/Applications/Xcode-beta.app/Contents/Developer/usr/bin/git";
940 const { files, host, resolve } = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
941 expect(yield* resolve).toBe(XCODE_GIT);
942​
943 files.delete(XCODE_GIT);
944 files.add(betaGit);
945 host.xcrunGit = betaGit;
946 expect(yield* resolve).toBe(betaGit);
947 expect(host.xcrunCalls).toBe(2);
948 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
949 );
950 });
951​
952 it.effect("does not fall back to a shell for unresolved Windows commands", () =>
953 Effect.gen(function* () {
954 const command = yield* resolveSpawnCommand("missing & calc", ["unsafe & value"], {
955 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
956 }).pipe(
957 Effect.provideService(HostProcess.Platform, "win32"),
958 Effect.provideService(CommandResolutionCache, new Map()),
959 );
960​
961 expect(command).toEqual({
962 command: "missing & calc",
963 args: ["unsafe & value"],
964 shell: false,
965 });
966 }),
967 );
968});
969​
970effectIt.layer(NodeServices.layer)("resolveWindowsEnvironment", (it) => {
971 it.effect("uses known CLI directories as a fallback without changing shell PATH priority", () =>
972 Effect.gen(function* () {
973 const readEnvironment = vi.fn(
974 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
975 options?.loadProfile
976 ? { PATH: "C:\\Profile\\Bin" }
977 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
978 );
979 const commandAvailable = vi.fn(() => Effect.succeed(true));
980​
981 expect(
982 yield* withWindowsEnvironmentMocks(
983 resolveWindowsEnvironment({
984 PATH: "C:\\Windows\\System32",
985 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
986 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
987 USERPROFILE: "C:\\Users\\testuser",
988 }),
989 readEnvironment,
990 commandAvailable,
991 ),
992 ).toEqual({
993 PATH: [
994 "C:\\Shell\\Bin",
995 "C:\\Windows\\System32",
996 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
997 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
998 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
999 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
1000 "C:\\Users\\testuser\\.local\\bin",
1001 "C:\\Users\\testuser\\.bun\\bin",
1002 "C:\\Users\\testuser\\scoop\\shims",
1003 ].join(";"),
1004 });
1005 expect(readEnvironment).toHaveBeenCalledTimes(1);
1006 expect(readEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
1007 expect(commandAvailable).toHaveBeenCalledWith(
1008 "node",
1009 expect.objectContaining({ env: expect.any(Object) }),
1010 );
1011 }),
1012 );
1013​
1014 it.effect(
1015 "probes node with one PATH key when inherited environment records have mixed casing",
1016 () =>
1017 Effect.gen(function* () {
1018 const probedEnvironments: Array<NodeJS.ProcessEnv | undefined> = [];
1019​
1020 yield* withWindowsEnvironmentMocks(
1021 resolveWindowsEnvironment({ Path: "C:\\Stale", PATH: "C:\\Windows\\System32" }),
1022 () => ({ PATH: "C:\\Shell\\Bin" }),
1023 (_command, options) =>
1024 Effect.sync(() => {
1025 probedEnvironments.push(options?.env);
1026 return true;
1027 }),
1028 );
1029​
1030 const pathEntries = Object.entries(probedEnvironments[0] ?? {}).filter(
1031 ([key]) => key.toUpperCase() === "PATH",
1032 );
1033 expect(pathEntries).toEqual([["PATH", "C:\\Shell\\Bin;C:\\Windows\\System32"]]);
1034 }),
1035 );
1036​
1037 it.effect("loads the PowerShell profile when baseline env cannot resolve node", () =>
1038 Effect.gen(function* () {
1039 const readEnvironment = vi.fn(
1040 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
1041 options?.loadProfile
1042 ? {
1043 PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
1044 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
1045 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
1047 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
1048 );
1049 const commandAvailable = vi.fn(() => Effect.succeed(false));
1050​
1051 expect(
1052 yield* withWindowsEnvironmentMocks(
1053 resolveWindowsEnvironment({
1054 PATH: "C:\\Windows\\System32",
1055 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
1056 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
1057 USERPROFILE: "C:\\Users\\testuser",
1058 }),
1059 readEnvironment,
1060 commandAvailable,
1061 ),
1062 ).toEqual({
1063 PATH: [
1064 "C:\\Profile\\Node",
1065 "C:\\Windows\\System32",
1066 "C:\\Shell\\Bin",
1067 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
1068 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
1069 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
1070 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
1071 "C:\\Users\\testuser\\.local\\bin",
1072 "C:\\Users\\testuser\\.bun\\bin",
1073 "C:\\Users\\testuser\\scoop\\shims",
1074 ].join(";"),
1075 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
1076 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
1077 });
1078 expect(readEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
1079 expect(readEnvironment).toHaveBeenNthCalledWith(
1080 2,
1081 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
1083 loadProfile: true,
1084 },
1085 );
1086 expect(commandAvailable).toHaveBeenCalledTimes(1);
1087 }),
1088 );
1089​
1090 it.effect("keeps the baseline env when profiled probe still does not resolve node", () =>
1091 Effect.gen(function* () {
1092 const readEnvironment = vi.fn(
1093 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
1094 options?.loadProfile ? { FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm" } : {},
1095 );
1096 const commandAvailable = vi.fn(() => Effect.succeed(false));
1097​
1098 expect(
1099 yield* withWindowsEnvironmentMocks(
1100 resolveWindowsEnvironment({
1101 PATH: "C:\\Windows\\System32",
1102 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
1103 USERPROFILE: "C:\\Users\\testuser",
1104 }),
1105 readEnvironment,
1106 commandAvailable,
1107 ),
1108 ).toEqual({
1109 PATH: [
1110 "C:\\Windows\\System32",
1111 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
1112 "C:\\Users\\testuser\\.local\\bin",
1113 "C:\\Users\\testuser\\.bun\\bin",
1114 "C:\\Users\\testuser\\scoop\\shims",
1115 ].join(";"),
1116 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
1117 });
1118 expect(commandAvailable).toHaveBeenCalledTimes(1);
1119 }),
1120 );
1121});
1122​
1123describe("desktop shell environment updates", () => {
1124 it.each(["win32", "linux", "darwin"] as const)(
1125 "applies shell updates with %s PATH semantics",
1126 (platform) => {
1127 const message = decodeDesktopHostMessage({
1128 version: 1,
1129 type: "shellEnvironment",
1130 discovered: true,
1131 platform,
1132 environment: {
1133 PATH: "C:\\fresh",
1134 FNM_DIR: null,
1135 __MISE_DIFF: null,
1136 SSH_AUTH_SOCK: "/current.sock",
1137 NODE_OPTIONS: "--bad",
1138 },
1139 });
1140 expect(message.type).toBe("shellEnvironment");
1141 if (message.type !== "shellEnvironment") throw new Error("Expected shell environment update");
1142 const env: NodeJS.ProcessEnv = {
1143 Path: "C:\\stale",
1144 FNM_DIR: "stale",
1145 __MISE_DIFF: "stale",
1146 UNRELATED: "keep",
1147 };
1148 applyShellEnvironment(env, message.environment, platform);
1149 expect(env).toEqual({
1150 PATH: "C:\\fresh",
1151 ...(platform === "win32" ? {} : { Path: "C:\\stale" }),
1152 SSH_AUTH_SOCK: "/current.sock",
1153 UNRELATED: "keep",
1154 });
1155 env.Path = "C:\\stale";
1156 env.path = "C:\\other";
1157 applyShellEnvironment(env, { PATH: null, SSH_AUTH_SOCK: null }, platform);
1158 expect(env).toEqual({
1159 ...(platform === "win32" ? {} : { Path: "C:\\stale", path: "C:\\other" }),
1160 UNRELATED: "keep",
1161 });
1162 },
1163 );
1164});
1165​
1166describe("pathSetupCommand", () => {
1167 // Undefined where a pasted line could break things: Windows (it would flatten %VAR% entries in
1168 // the registry PATH), macOS bash (several startup files), other shells, and unsafe paths.
1169 it.each([
1171 "/home/theo/.local/bin",
1172 "/bin/bash",
1173 "linux",
1174 `printf '\\n%s\\n' 'export PATH="$PATH:/home/theo/.local/bin"' >> ~/.bashrc`,
1175 ],
1177 "/Users/theo/.local/bin",
1178 "/usr/bin/fish",
1179 "linux",
1180 `mkdir -p ~/.config/fish && printf '\\n%s\\n' 'fish_add_path --append --path $HOME/.local/bin' >> ~/.config/fish/config.fish`,
1181 ],
1183 "/opt/t3/bin",
1184 "/bin/zsh",
1185 "linux",
1186 `printf '\\n%s\\n' 'export PATH="$PATH:/opt/t3/bin"' >> ~/.zshrc`,
1187 ],
1188 ["/Users/theo/.local/bin", "/bin/tcsh", "darwin", undefined],
1189 ["/Users/theo/.local/bin", "/bin/bash", "darwin", undefined],
1190 ["C:\\Users\\theo\\.local\\bin", "pwsh", "win32", undefined],
1191 ["/Users/theo/it's here", "/bin/zsh", "darwin", undefined],
1192 ["/opt/a$PWD/bin", "/bin/zsh", "linux", undefined],
1193 // Relative: PATH would follow the working directory into any checkout's `bin`.
1194 ["bin", "/bin/zsh", "linux", undefined],
1195 ] as const)("%s with %s on %s", (directory, shell, platform, expected) => {
1196 expect(pathSetupCommand({ directory, home: "/Users/theo", shell, platform })).toBe(expected);
1197 });
1198​
1199 it("writes the startup file fish and zsh read, under XDG_CONFIG_HOME or ZDOTDIR", () => {
1200 const setup = { directory: "/opt/t3/bin", home: "/home/theo", shell: "/usr/bin/fish" } as const;
1201 expect(pathSetup({ ...setup, platform: "linux", configHome: "/home/theo/cfg" })?.file).toBe(
1202 "/home/theo/cfg/fish/config.fish",
1203 );
1204 expect(pathSetup({ ...setup, platform: "linux" })?.file).toBe("~/.config/fish/config.fish");
1205 // zsh reads .zshrc from ZDOTDIR when it is set.
1206 expect(
1207 pathSetup({ ...setup, shell: "/bin/zsh", platform: "darwin", zdotdir: "/Users/theo/.zsh" })
1208 ?.file,
1209 ).toBe("/Users/theo/.zsh/.zshrc");
1210 // A set folder that cannot be written safely means no setup, never the unread default.
1211 expect(
1212 pathSetup({ ...setup, shell: "/bin/zsh", platform: "darwin", zdotdir: "/Users/theo/my zsh" }),
1213 ).toBeUndefined();
1214 expect(
1215 pathSetup({ ...setup, platform: "linux", configHome: "/home/theo/my cfg" }),
1216 ).toBeUndefined();
1217 });
1218});