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

shell.test.ts

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