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

shell.test.ts

1,254 lines44.3 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 resolved = yield* resolveCommandPath(command, {
562 env: { PATH: cwd, PATHEXT: ".CMD" },
563 }).pipe(
564 Effect.provideService(HostProcess.Platform, "win32"),
565 Effect.provideService(CommandResolutionCache, new Map()),
566 Effect.provideService(FileSystem.FileSystem, {
567 ...fs,
568 stat: (filePath) =>
569 fs.stat(filePath === executable ? filePath : path.join(cwd, "missing")),
570 }),
571 );
572​
573 expect(resolved).toBe(executable);
574 }),
575 );
576​
577 it.effect("probes only listed PATH names and relists a directory that changes", () =>
578 Effect.gen(function* () {
579 const fs = yield* FileSystem.FileSystem;
580 const path = yield* Path.Path;
581 const first = yield* fs.makeTempDirectoryScoped();
582 const second = yield* fs.makeTempDirectoryScoped();
583 yield* fs.writeFileString(path.join(first, "cursor.CMD"), "");
584 yield* fs.writeFileString(path.join(second, "cursor.EXE"), "");
585 const env = { PATH: `${first};${second}`, PATHEXT: ".EXE;.CMD" };
586 const probed: Array<string> = [];
587 yield* Effect.gen(function* () {
588 expect(yield* resolveCommandPath("cursor", { env })).toBe(path.join(first, "cursor.CMD"));
589 expect(yield* isCommandAvailable("absent", { env })).toBe(false);
590 yield* fs.writeFileString(path.join(second, "late.EXE"), "");
591 yield* fs.utimes(second, 4_102_444_800, 4_102_444_800);
592 expect(yield* resolveCommandPath("late", { env })).toBe(path.join(second, "late.EXE"));
593 }).pipe(
594 withPathDirectoryListings,
595 Effect.provideService(FileSystem.FileSystem, {
596 ...fs,
597 stat: (file) => {
598 if (file !== first && file !== second) probed.push(file);
599 return fs.stat(file);
600 },
601 }),
602 );
603 expect(probed).toEqual([path.join(first, "cursor.CMD"), path.join(second, "late.EXE")]);
604 }).pipe(
605 Effect.provideService(HostProcess.Platform, "win32"),
606 Effect.provideService(CommandResolutionCache, new Map()),
607 ),
608 );
609});
610​
611describe("runsGitWithoutConsole", () => {
612 const git = "C:\\Program Files\\Git\\ucrt64\\bin\\git.exe";
613​
614 it.each([
615 [["rev-parse", "--git-path", "index"], true],
616 [["--git-dir", "C:\\repo\\.git", "symbolic-ref", "refs/remotes/origin/HEAD"], true],
617 [["remote", "get-url", "--", "origin"], true],
618 [["config", "--get", "branch.main.pushRemote"], true],
619 [["symbolic-ref", "--quiet", "HEAD"], true],
620 [["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], true],
621 [["rev-parse", "HEAD"], false],
622 [["symbolic-ref", "HEAD", "refs/heads/x"], false],
623 [["symbolic-ref", "-qd", "refs/remotes/origin/HEAD"], false],
624 [["config", "--get", "--edit"], false],
625 [["-c", "core.pager=x", "config", "--get", "user.name"], false],
626 ])("Git for Windows %j without a console: %s", (args, expected) => {
627 expect(runsGitWithoutConsole("win32", git, args)).toBe(expected);
628 });
629​
630 it.each([
631 ["win32", "C:\\Program Files\\Git\\cmd\\git.exe"],
632 ["win32", "C:\\Users\\x\\scoop\\shims\\git.exe"],
633 ["linux", git],
634 ] as const)("keeps the console on %s for %s", (platform, executable) => {
635 expect(runsGitWithoutConsole(platform, executable, ["rev-parse", "--show-toplevel"])).toBe(
636 false,
637 );
638 });
639});
640​
641describe("preferGitForWindowsBinary", () => {
642 const files =
643 (...paths: Array<string>) =>
644 (filePath: string) =>
645 paths.includes(filePath);
646​
647 it("runs the git.exe Git for Windows' launcher would start", () => {
648 expect(
649 preferGitForWindowsBinary(
650 "C:\\Program Files\\Git\\cmd\\git.EXE",
651 {},
652 files(
653 "C:\\Program Files\\Git\\ucrt64\\bin\\git.exe",
654 "C:\\Program Files\\Git\\mingw64\\bin\\git.exe",
655 ),
656 ),
657 ).toBe("C:\\Program Files\\Git\\ucrt64\\bin\\git.exe");
658 expect(
659 preferGitForWindowsBinary(
660 "D:\\PortableGit\\bin\\git.exe",
661 {},
662 files("D:\\PortableGit\\mingw64\\bin\\git.exe"),
663 ),
664 ).toBe("D:\\PortableGit\\mingw64\\bin\\git.exe");
665 expect(
666 preferGitForWindowsBinary(
667 "C:\\Program Files\\Git\\cmd\\git.exe",
668 {},
669 files("C:\\Program Files\\Git\\clangarm64\\bin\\git.exe"),
670 ),
671 ).toBe("C:\\Program Files\\Git\\clangarm64\\bin\\git.exe");
672 });
673​
674 it("keeps the launcher when MSYSTEM is set", () => {
675 // git.exe adds hook dependencies to PATH only when MSYSTEM is unset.
676 expect(
677 preferGitForWindowsBinary(
678 "C:\\Program Files\\Git\\cmd\\git.exe",
679 { MSYSTEM: "MINGW64" },
680 files("C:\\Program Files\\Git\\mingw64\\bin\\git.exe"),
681 ),
682 ).toBe("C:\\Program Files\\Git\\cmd\\git.exe");
683 });
684​
685 it("leaves other gits and other launchers alone", () => {
686 const everything = () => true;
687 expect(preferGitForWindowsBinary("C:\\Users\\me\\scoop\\shims\\git.exe", {}, everything)).toBe(
688 "C:\\Users\\me\\scoop\\shims\\git.exe",
689 );
690 expect(preferGitForWindowsBinary("C:\\Program Files\\Git\\cmd\\gitk.exe", {}, everything)).toBe(
691 "C:\\Program Files\\Git\\cmd\\gitk.exe",
692 );
693 });
694});
695​
696// Byte for byte what `npm install -g opencode-ai` writes as `opencode.cmd`.
697const NPM_OPENCODE_SHIM = [
698 "@ECHO off",
699 "GOTO start",
700 ":find_dp0",
701 "SET dp0=%~dp0",
702 "EXIT /b",
703 ":start",
704 "SETLOCAL",
705 "CALL :find_dp0",
706 '"%dp0%\\node_modules\\opencode-ai\\bin\\opencode.exe" %*',
707 "",
708].join("\r\n");
709​
710describe("npmShimExecutable", () => {
711 const shimPath = "C:\\Users\\me\\AppData\\Roaming\\npm\\opencode.cmd";
712 const executable =
713 "C:\\Users\\me\\AppData\\Roaming\\npm\\node_modules\\opencode-ai\\bin\\opencode.exe";
714 const exists = (filePath: string) => filePath === executable;
715​
716 it("finds the executable npm's shim runs", () => {
717 expect(npmShimExecutable(shimPath, () => NPM_OPENCODE_SHIM, exists)).toBe(executable);
718 expect(
719 npmShimExecutable(shimPath.replace(".cmd", ".CMD"), () => NPM_OPENCODE_SHIM, exists),
720 ).toBe(executable);
721 });
722​
723 it("keeps a shim that does more than run the executable", () => {
724 const withSetting = NPM_OPENCODE_SHIM.replace(
725 "SETLOCAL",
726 "SETLOCAL\r\nSET OPENCODE_CONFIG=C:\\x",
727 );
728 expect(npmShimExecutable(shimPath, () => withSetting, exists)).toBeUndefined();
729 const nodeScript = NPM_OPENCODE_SHIM.replace(
730 '"%dp0%\\node_modules\\opencode-ai\\bin\\opencode.exe" %*',
731 '"%_prog%" "%dp0%\\node_modules\\opencode-ai\\bin\\opencode.js" %*',
732 );
733 expect(
734 npmShimExecutable(
735 shimPath,
736 () => nodeScript,
737 () => true,
738 ),
739 ).toBeUndefined();
740 });
741​
742 it("keeps a shim CMD would read differently", () => {
743 // CMD preserves trailing SET whitespace, changing the executable path.
744 for (const suffix of ["\u00a0", "\t", " "]) {
745 const altered = NPM_OPENCODE_SHIM.replace("SET dp0=%~dp0", `SET dp0=%~dp0${suffix}`);
746 expect(
747 npmShimExecutable(
748 shimPath,
749 () => altered,
750 () => true,
751 ),
752 ).toBeUndefined();
753 }
754 const nonBreakingSeparator = NPM_OPENCODE_SHIM.replace(
755 'opencode.exe" %*',
756 'opencode.exe"\u00a0%*',
757 );
758 expect(
759 npmShimExecutable(
760 shimPath,
761 () => nonBreakingSeparator,
762 () => true,
763 ),
764 ).toBeUndefined();
765 const indented = NPM_OPENCODE_SHIM.replace("SETLOCAL", " SETLOCAL");
766 expect(
767 npmShimExecutable(
768 shimPath,
769 () => indented,
770 () => true,
771 ),
772 ).toBeUndefined();
773 });
774​
775 it("keeps the shim when its executable is missing or it is not a .cmd", () => {
776 expect(
777 npmShimExecutable(
778 shimPath,
779 () => NPM_OPENCODE_SHIM,
780 () => false,
781 ),
782 ).toBeUndefined();
783 expect(
784 npmShimExecutable(
785 shimPath,
786 () => undefined,
787 () => true,
788 ),
789 ).toBeUndefined();
790 expect(
791 npmShimExecutable(
792 shimPath.replace(".cmd", ".bat"),
793 () => NPM_OPENCODE_SHIM,
794 () => true,
795 ),
796 ).toBeUndefined();
797 });
798});
799​
800effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => {
801 it.effect("runs Windows executables directly without a shell", () =>
802 Effect.gen(function* () {
803 const command = yield* resolveSpawnCommand("node.exe", ["script.js", "hello & goodbye"], {
804 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
805 }).pipe(
806 Effect.provideService(HostProcess.Platform, "win32"),
807 Effect.provideService(CommandResolutionCache, new Map()),
808 );
809​
810 expect(command).toEqual({
811 command: "node.exe",
812 args: ["script.js", "hello & goodbye"],
813 shell: false,
814 });
815 }),
816 );
817​
818 it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")(
819 "runs the executable behind an npm shim directly when asked",
820 () =>
821 Effect.gen(function* () {
822 const fs = yield* FileSystem.FileSystem;
823 const path = yield* Path.Path;
824 const prefix = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-shim-" });
825 const shim = path.join(prefix, "opencode.cmd");
826 const executable = path.join(prefix, "node_modules", "opencode-ai", "bin", "opencode.exe");
827 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
828 yield* fs.writeFileString(executable, "");
829 yield* fs.writeFileString(shim, NPM_OPENCODE_SHIM);
830 const resolve = (bypassNpmShim: boolean) =>
831 resolveSpawnCommand("opencode", ["serve", "--port=4096"], {
832 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
833 bypassNpmShim,
834 }).pipe(
835 Effect.provideService(HostProcess.Platform, "win32"),
836 Effect.provideService(CommandResolutionCache, new Map()),
837 Effect.provideService(SpawnExecutableResolution, () => shim),
838 );
839​
840 expect(yield* resolve(true)).toEqual({
841 command: executable,
842 args: ["serve", "--port=4096"],
843 shell: false,
844 });
845 expect((yield* resolve(false)).shell).toBe(true);
846 }),
847 );
848​
849 it.effect("builds one escaped cmd.exe line for Windows command shims", () =>
850 Effect.gen(function* () {
851 const command = yield* resolveSpawnCommand(
852 "vp",
853 [
854 "run",
855 "value & calc",
856 "%PATH%",
857 'quote"value',
858 "C:\\dir with space\\",
859 'slash\\"quote',
860 "x|y<z>^",
861 ],
862 { env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" } },
863 ).pipe(
864 Effect.provideService(HostProcess.Platform, "win32"),
865 Effect.provideService(CommandResolutionCache, new Map()),
866 Effect.provideService(
867 SpawnExecutableResolution,
868 () => "C:\\Program Files\\npm & tools\\vp.cmd",
869 ),
870 );
871​
872 // No args alongside `shell: true`: Node prints DEP0190 for that pairing.
873 expect(command).toEqual({
874 command: [
875 String.raw`^"C:\Program^ Files\npm^ ^&^ tools\vp.cmd^"`,
876 String.raw`^"run^"`,
877 String.raw`^"value^ ^&^ calc^"`,
878 String.raw`^"^%PATH^%^"`,
879 String.raw`^"quote\^"value^"`,
880 String.raw`^"C:\dir^ with^ space\\^"`,
881 String.raw`^"slash\\\^"quote^"`,
882 String.raw`^"x^|y^<z^>^^^"`,
883 ].join(" "),
884 args: [],
885 shell: true,
886 });
887 }),
888 );
889​
890 it.effect("resolves against the effective environment when extending host env", () =>
891 Effect.gen(function* () {
892 let resolvedEnvironment: NodeJS.ProcessEnv | undefined;
893 yield* resolveSpawnCommand("codex", ["app-server"], {
894 env: { CODEX_HOME: "C:\\Users\\tester\\.codex" },
895 extendEnv: true,
896 }).pipe(
897 Effect.provideService(HostProcess.Platform, "win32"),
898 Effect.provideService(CommandResolutionCache, new Map()),
899 Effect.provideService(HostProcess.Environment, {
900 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
901 PATHEXT: ".COM;.EXE;.BAT;.CMD",
902 }),
903 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) => {
904 resolvedEnvironment = env;
905 return "C:\\Users\\tester\\AppData\\Roaming\\npm\\codex.cmd";
906 }),
907 );
908​
909 expect(resolvedEnvironment).toEqual({
910 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
911 PATHEXT: ".COM;.EXE;.BAT;.CMD",
912 CODEX_HOME: "C:\\Users\\tester\\.codex",
913 });
914 }),
915 );
916​
917 describe("macOS git", () => {
918 // Files that exist, the git first on PATH, and what `xcrun --find git` prints.
919 const setup = (options: {
920 readonly platform?: NodeJS.Platform;
921 readonly gitOnPath: string;
922 readonly xcrunGit: string | undefined;
923 }) => {
924 const files = new Set([options.gitOnPath, ...(options.xcrunGit ? [options.xcrunGit] : [])]);
925 const host = { xcrunGit: options.xcrunGit, xcrunCalls: 0 };
926 const resolve = resolveSpawnCommand("git", ["status"], { env: { PATH: "/fake/bin" } }).pipe(
927 Effect.map((resolved) => resolved.command),
928 Effect.provideService(HostProcess.Platform, options.platform ?? "darwin"),
929 Effect.provideService(SpawnExecutableResolution, (command) =>
930 command === "git" ? options.gitOnPath : files.has(command) ? command : undefined,
931 ),
932 Effect.provideService(XcodeGitLocation, () => {
933 host.xcrunCalls += 1;
934 return host.xcrunGit;
935 }),
936 );
937 return { files, host, resolve };
938 };
939​
940 const XCODE_GIT = "/Applications/Xcode.app/Contents/Developer/usr/bin/git";
941​
942 it.effect("runs the git behind the xcrun shim and looks it up once", () =>
943 Effect.gen(function* () {
944 const { host, resolve } = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
945 expect(yield* resolve).toBe(XCODE_GIT);
946 expect(yield* resolve).toBe(XCODE_GIT);
947 expect(host.xcrunCalls).toBe(1);
948 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
949 );
950​
951 it.effect("keeps git when PATH has another git or the host is not macOS", () =>
952 Effect.gen(function* () {
953 const homebrew = setup({ gitOnPath: "/opt/homebrew/bin/git", xcrunGit: XCODE_GIT });
954 expect(yield* homebrew.resolve).toBe("git");
955 expect(homebrew.host.xcrunCalls).toBe(0);
956​
957 const linux = setup({ platform: "linux", gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
958 expect(yield* linux.resolve).toBe("git");
959 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
960 );
961​
962 it.effect("keeps git when xcrun fails or names a missing file", () =>
963 Effect.gen(function* () {
964 const failed = setup({ gitOnPath: "/usr/bin/git", xcrunGit: undefined });
965 expect(yield* failed.resolve).toBe("git");
966​
967 const missing = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
968 missing.files.delete(XCODE_GIT);
969 expect(yield* missing.resolve).toBe("git");
970 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
971 );
972​
973 it.effect("looks again when the resolved git disappears", () =>
974 Effect.gen(function* () {
975 const betaGit = "/Applications/Xcode-beta.app/Contents/Developer/usr/bin/git";
976 const { files, host, resolve } = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
977 expect(yield* resolve).toBe(XCODE_GIT);
978​
979 files.delete(XCODE_GIT);
980 files.add(betaGit);
981 host.xcrunGit = betaGit;
982 expect(yield* resolve).toBe(betaGit);
983 expect(host.xcrunCalls).toBe(2);
984 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
985 );
986 });
987​
988 it.effect("does not fall back to a shell for unresolved Windows commands", () =>
989 Effect.gen(function* () {
990 const command = yield* resolveSpawnCommand("missing & calc", ["unsafe & value"], {
991 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
992 }).pipe(
993 Effect.provideService(HostProcess.Platform, "win32"),
994 Effect.provideService(CommandResolutionCache, new Map()),
995 );
996​
997 expect(command).toEqual({
998 command: "missing & calc",
999 args: ["unsafe & value"],
1000 shell: false,
1001 });
1002 }),
1003 );
1004});
1005​
1006effectIt.layer(NodeServices.layer)("resolveWindowsEnvironment", (it) => {
1007 it.effect("uses known CLI directories as a fallback without changing shell PATH priority", () =>
1008 Effect.gen(function* () {
1009 const readEnvironment = vi.fn(
1010 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
1011 options?.loadProfile
1012 ? { PATH: "C:\\Profile\\Bin" }
1013 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
1014 );
1015 const commandAvailable = vi.fn(() => Effect.succeed(true));
1016​
1017 expect(
1018 yield* withWindowsEnvironmentMocks(
1019 resolveWindowsEnvironment({
1020 PATH: "C:\\Windows\\System32",
1021 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
1022 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
1023 USERPROFILE: "C:\\Users\\testuser",
1024 }),
1025 readEnvironment,
1026 commandAvailable,
1027 ),
1028 ).toEqual({
1029 PATH: [
1030 "C:\\Shell\\Bin",
1031 "C:\\Windows\\System32",
1032 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
1033 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
1034 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
1035 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
1036 "C:\\Users\\testuser\\.local\\bin",
1037 "C:\\Users\\testuser\\.bun\\bin",
1038 "C:\\Users\\testuser\\scoop\\shims",
1039 ].join(";"),
1040 });
1041 expect(readEnvironment).toHaveBeenCalledTimes(1);
1042 expect(readEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
1043 expect(commandAvailable).toHaveBeenCalledWith(
1044 "node",
1045 expect.objectContaining({ env: expect.any(Object) }),
1046 );
1047 }),
1048 );
1049​
1050 it.effect(
1051 "probes node with one PATH key when inherited environment records have mixed casing",
1052 () =>
1053 Effect.gen(function* () {
1054 const probedEnvironments: Array<NodeJS.ProcessEnv | undefined> = [];
1055​
1056 yield* withWindowsEnvironmentMocks(
1057 resolveWindowsEnvironment({ Path: "C:\\Stale", PATH: "C:\\Windows\\System32" }),
1058 () => ({ PATH: "C:\\Shell\\Bin" }),
1059 (_command, options) =>
1060 Effect.sync(() => {
1061 probedEnvironments.push(options?.env);
1062 return true;
1063 }),
1064 );
1065​
1066 const pathEntries = Object.entries(probedEnvironments[0] ?? {}).filter(
1067 ([key]) => key.toUpperCase() === "PATH",
1068 );
1069 expect(pathEntries).toEqual([["PATH", "C:\\Shell\\Bin;C:\\Windows\\System32"]]);
1070 }),
1071 );
1072​
1073 it.effect("loads the PowerShell profile when baseline env cannot resolve node", () =>
1074 Effect.gen(function* () {
1075 const readEnvironment = vi.fn(
1076 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
1077 options?.loadProfile
1078 ? {
1079 PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
1080 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
1081 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
1083 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
1084 );
1085 const commandAvailable = vi.fn(() => Effect.succeed(false));
1086​
1087 expect(
1088 yield* withWindowsEnvironmentMocks(
1089 resolveWindowsEnvironment({
1090 PATH: "C:\\Windows\\System32",
1091 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
1092 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
1093 USERPROFILE: "C:\\Users\\testuser",
1094 }),
1095 readEnvironment,
1096 commandAvailable,
1097 ),
1098 ).toEqual({
1099 PATH: [
1100 "C:\\Profile\\Node",
1101 "C:\\Windows\\System32",
1102 "C:\\Shell\\Bin",
1103 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
1104 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
1105 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
1106 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
1107 "C:\\Users\\testuser\\.local\\bin",
1108 "C:\\Users\\testuser\\.bun\\bin",
1109 "C:\\Users\\testuser\\scoop\\shims",
1110 ].join(";"),
1111 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
1112 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
1113 });
1114 expect(readEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
1115 expect(readEnvironment).toHaveBeenNthCalledWith(
1116 2,
1117 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
1119 loadProfile: true,
1120 },
1121 );
1122 expect(commandAvailable).toHaveBeenCalledTimes(1);
1123 }),
1124 );
1125​
1126 it.effect("keeps the baseline env when profiled probe still does not resolve node", () =>
1127 Effect.gen(function* () {
1128 const readEnvironment = vi.fn(
1129 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
1130 options?.loadProfile ? { FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm" } : {},
1131 );
1132 const commandAvailable = vi.fn(() => Effect.succeed(false));
1133​
1134 expect(
1135 yield* withWindowsEnvironmentMocks(
1136 resolveWindowsEnvironment({
1137 PATH: "C:\\Windows\\System32",
1138 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
1139 USERPROFILE: "C:\\Users\\testuser",
1140 }),
1141 readEnvironment,
1142 commandAvailable,
1143 ),
1144 ).toEqual({
1145 PATH: [
1146 "C:\\Windows\\System32",
1147 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
1148 "C:\\Users\\testuser\\.local\\bin",
1149 "C:\\Users\\testuser\\.bun\\bin",
1150 "C:\\Users\\testuser\\scoop\\shims",
1151 ].join(";"),
1152 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
1153 });
1154 expect(commandAvailable).toHaveBeenCalledTimes(1);
1155 }),
1156 );
1157});
1158​
1159describe("desktop shell environment updates", () => {
1160 it.each(["win32", "linux", "darwin"] as const)(
1161 "applies shell updates with %s PATH semantics",
1162 (platform) => {
1163 const message = decodeDesktopHostMessage({
1164 version: 1,
1165 type: "shellEnvironment",
1166 discovered: true,
1167 platform,
1168 environment: {
1169 PATH: "C:\\fresh",
1170 FNM_DIR: null,
1171 __MISE_DIFF: null,
1172 SSH_AUTH_SOCK: "/current.sock",
1173 NODE_OPTIONS: "--bad",
1174 },
1175 });
1176 expect(message.type).toBe("shellEnvironment");
1177 if (message.type !== "shellEnvironment") throw new Error("Expected shell environment update");
1178 const env: NodeJS.ProcessEnv = {
1179 Path: "C:\\stale",
1180 FNM_DIR: "stale",
1181 __MISE_DIFF: "stale",
1182 UNRELATED: "keep",
1183 };
1184 applyShellEnvironment(env, message.environment, platform);
1185 expect(env).toEqual({
1186 PATH: "C:\\fresh",
1187 ...(platform === "win32" ? {} : { Path: "C:\\stale" }),
1188 SSH_AUTH_SOCK: "/current.sock",
1189 UNRELATED: "keep",
1190 });
1191 env.Path = "C:\\stale";
1192 env.path = "C:\\other";
1193 applyShellEnvironment(env, { PATH: null, SSH_AUTH_SOCK: null }, platform);
1194 expect(env).toEqual({
1195 ...(platform === "win32" ? {} : { Path: "C:\\stale", path: "C:\\other" }),
1196 UNRELATED: "keep",
1197 });
1198 },
1199 );
1200});
1201​
1202describe("pathSetupCommand", () => {
1203 // Undefined where a pasted line could break things: Windows (it would flatten %VAR% entries in
1204 // the registry PATH), macOS bash (several startup files), other shells, and unsafe paths.
1205 it.each([
1207 "/home/theo/.local/bin",
1208 "/bin/bash",
1209 "linux",
1210 `printf '\\n%s\\n' 'export PATH="$PATH:/home/theo/.local/bin"' >> ~/.bashrc`,
1211 ],
1213 "/Users/theo/.local/bin",
1214 "/usr/bin/fish",
1215 "linux",
1216 `mkdir -p ~/.config/fish && printf '\\n%s\\n' 'fish_add_path --append --path $HOME/.local/bin' >> ~/.config/fish/config.fish`,
1217 ],
1219 "/opt/t3/bin",
1220 "/bin/zsh",
1221 "linux",
1222 `printf '\\n%s\\n' 'export PATH="$PATH:/opt/t3/bin"' >> ~/.zshrc`,
1223 ],
1224 ["/Users/theo/.local/bin", "/bin/tcsh", "darwin", undefined],
1225 ["/Users/theo/.local/bin", "/bin/bash", "darwin", undefined],
1226 ["C:\\Users\\theo\\.local\\bin", "pwsh", "win32", undefined],
1227 ["/Users/theo/it's here", "/bin/zsh", "darwin", undefined],
1228 ["/opt/a$PWD/bin", "/bin/zsh", "linux", undefined],
1229 // Relative: PATH would follow the working directory into any checkout's `bin`.
1230 ["bin", "/bin/zsh", "linux", undefined],
1231 ] as const)("%s with %s on %s", (directory, shell, platform, expected) => {
1232 expect(pathSetupCommand({ directory, home: "/Users/theo", shell, platform })).toBe(expected);
1233 });
1234​
1235 it("writes the startup file fish and zsh read, under XDG_CONFIG_HOME or ZDOTDIR", () => {
1236 const setup = { directory: "/opt/t3/bin", home: "/home/theo", shell: "/usr/bin/fish" } as const;
1237 expect(pathSetup({ ...setup, platform: "linux", configHome: "/home/theo/cfg" })?.file).toBe(
1238 "/home/theo/cfg/fish/config.fish",
1239 );
1240 expect(pathSetup({ ...setup, platform: "linux" })?.file).toBe("~/.config/fish/config.fish");
1241 // zsh reads .zshrc from ZDOTDIR when it is set.
1242 expect(
1243 pathSetup({ ...setup, shell: "/bin/zsh", platform: "darwin", zdotdir: "/Users/theo/.zsh" })
1244 ?.file,
1245 ).toBe("/Users/theo/.zsh/.zshrc");
1246 // A set folder that cannot be written safely means no setup, never the unread default.
1247 expect(
1248 pathSetup({ ...setup, shell: "/bin/zsh", platform: "darwin", zdotdir: "/Users/theo/my zsh" }),
1249 ).toBeUndefined();
1250 expect(
1251 pathSetup({ ...setup, platform: "linux", configHome: "/home/theo/my cfg" }),
1252 ).toBeUndefined();
1253 });
1254});