Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeOS from "node:os";
3import * as NodePath from "node:path";
4import * as NodeChildProcess from "node:child_process";
5import * as NodeFS from "node:fs";
6import * as Cache from "effect/Cache";
7import * as Clock from "effect/Clock";
8import * as Duration from "effect/Duration";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as FileSystem from "effect/FileSystem";
12import * as Option from "effect/Option";
13import * as Path from "effect/Path";
14
15import type { ShellEnvironmentPatch } from "@t3tools/contracts";
16import * as HostProcess from "./HostProcess.ts";
17import * as Context from "effect/Context";
18import { routineSpan } from "./observability.ts";
19const SHELL_ENV_NAME_PATTERN = /^[A-Z0-9_]+$/;
20const WINDOWS_PATH_DELIMITER = ";";
21const POSIX_PATH_DELIMITER = ":";
22const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
23const WINDOWS_SHELL_PROBE_TIMEOUT_MS = 5000;
24// A shell stuck in the kernel survives the kill and holds stdout, so execFile's callback never fires.
25const WINDOWS_SHELL_PROBE_DEADLINE = Duration.millis(WINDOWS_SHELL_PROBE_TIMEOUT_MS + 1000);
26
27type ExecFileSyncLike = (
28 file: string,
29 args: ReadonlyArray<string>,
30 options: {
31 encoding: "utf8";
32 timeout: number;
33 killSignal?: NodeJS.Signals | number;
34 detached?: true;
35 stdio?: ["ignore", "pipe", "ignore"];
36 },
37) => string;
38
39function canExecuteFile(filePath: string): boolean {
40 try {
41 NodeFS.accessSync(filePath, NodeFS.constants.X_OK);
42 return true;
43 } catch {
44 return false;
45 }
46}
47
48export interface CommandAvailabilityOptions {
49 readonly env?: NodeJS.ProcessEnv;
50 readonly extendEnv?: boolean;
51}
52
53export type CommandAvailabilityChecker = (
54 command: string,
55 options?: CommandAvailabilityOptions,
56) => Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path>;
57
58const WINDOWS_SHELL_META_CHARS = /([()\][%!^"`<>&|;, *?])/g;
59
60// Escape dynamic arguments for both cmd.exe and the target's CommandLineToArgvW parsing.
61function escapeWindowsShellArg(arg: string): string {
62 let escaped = arg.replace(/(\\*)"/g, '$1$1\\"');
63 // Double up trailing backslashes so the closing quote is not escaped away.
64 escaped = escaped.replace(/(\\*)$/, "$1$1");
65 escaped = `"${escaped}"`;
66 return escaped.replace(WINDOWS_SHELL_META_CHARS, "^$1");
67}
68
69export interface ResolvedSpawnCommand {
70 readonly command: string;
71 readonly args: ReadonlyArray<string>;
72 readonly shell: boolean;
73}
74
75export type SpawnExecutableResolver = (
76 command: string,
77 platform: NodeJS.Platform,
78 env: NodeJS.ProcessEnv,
79) => string | undefined | Promise<string | undefined>;
80
81function isExplicitCommandPath(command: string, platform: NodeJS.Platform): boolean {
82 return command.includes("/") || (platform === "win32" && command.includes("\\"));
83}
84
85async function resolveSpawnExecutableWithNode(
86 command: string,
87 platform: NodeJS.Platform,
88 env: NodeJS.ProcessEnv,
89): Promise<string | undefined> {
90 const path = platform === "win32" ? NodePath.win32 : NodePath.posix;
91 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
92 const candidates = resolveCommandCandidates(
93 command,
94 platform,
95 windowsPathExtensions,
96 path.extname,
97 );
98 const isExecutable = async (candidate: string) => {
99 try {
100 if (!(await NodeFS.promises.stat(candidate)).isFile()) return false;
101 if (platform === "win32") {
102 return windowsPathExtensions.includes(path.extname(candidate).toUpperCase());
103 }
104 await NodeFS.promises.access(candidate, NodeFS.constants.X_OK);
105 return true;
106 } catch {
107 return false;
108 }
109 };
110
111 if (isExplicitCommandPath(command, platform)) {
112 for (const candidate of candidates) {
113 if (await isExecutable(candidate)) return candidate;
114 }
115 return undefined;
116 }
117
118 const pathValue = readEnvPath(env) ?? "";
119 for (const pathEntry of pathValue.split(pathDelimiterForPlatform(platform))) {
120 // A raw empty component of a nonempty POSIX PATH is the current directory.
121 const emptyComponent = pathEntry === "" && pathValue !== "" && platform !== "win32";
122 const normalizedPathEntry = emptyComponent ? "." : normalizePathEntry(pathEntry, platform);
123 if (normalizedPathEntry.length === 0) continue;
124 const listing =
125 platform === "win32"
126 ? await listResolverPathDirectory(normalizedPathEntry, path.isAbsolute)
127 : undefined;
128 for (const candidate of candidates) {
129 if (isAbsentFromListing(listing?.names, candidate)) continue;
130 const candidatePath = path.join(normalizedPathEntry, candidate);
131 // Anchored before the probe: callers may launch it from another cwd or through a wrapper,
132 // and the cwd can change while the probe waits.
133 let probePath = candidatePath;
134 if (emptyComponent) {
135 try {
136 probePath = path.resolve(candidatePath);
137 } catch {
138 continue;
139 }
140 }
141 if (await isExecutable(probePath)) {
142 const cased = listedCandidateName(listing?.casedNames, candidate);
143 return cased === candidate ? probePath : path.join(normalizedPathEntry, cased);
144 }
145 }
146 }
147 return undefined;
148}
149
150export const SpawnExecutableResolution = Context.Reference<SpawnExecutableResolver>(
151 "@t3tools/shared/shell/SpawnExecutableResolution",
152 {
153 defaultValue: () => resolveSpawnExecutableWithNode,
154 },
155);
156
157export interface WindowsEnvironmentProbeOptions {
158 readonly loadProfile?: boolean;
159}
160
161function trimNonEmpty(value: string | null | undefined): string | undefined {
162 const trimmed = value?.trim();
163 return trimmed && trimmed.length > 0 ? trimmed : undefined;
164}
165
166export function readUserLoginShell(): string | undefined {
167 try {
168 return trimNonEmpty(NodeOS.userInfo().shell);
169 } catch {
170 return undefined;
171 }
172}
173
174export function listLoginShellCandidates(
175 platform: NodeJS.Platform,
176 shell: string | undefined,
177 userShell = readUserLoginShell(),
178): ReadonlyArray<string> {
179 const fallbackShell =
180 platform === "darwin" ? "/bin/zsh" : platform === "linux" ? "/bin/bash" : undefined;
181 const seen = new Set<string>();
182 const candidates: string[] = [];
183
184 for (const candidate of [trimNonEmpty(shell), trimNonEmpty(userShell), fallbackShell]) {
185 if (!candidate || seen.has(candidate)) {
186 continue;
187 }
188 seen.add(candidate);
189 candidates.push(candidate);
190 }
191
192 return candidates;
193}
194
195export function readPathFromLaunchctl(
196 execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,
197): string | undefined {
198 try {
199 return trimNonEmpty(
200 execFile("/bin/launchctl", ["getenv", "PATH"], {
201 encoding: "utf8",
202 timeout: 2000,
203 }),
204 );
205 } catch {
206 return undefined;
207 }
208}
209
210export function mergePathEntries(
211 preferredPath: string | undefined,
212 inheritedPath: string | undefined,
213 platform: NodeJS.Platform,
214): string | undefined {
215 const delimiter = platform === "win32" ? ";" : ":";
216 const merged: string[] = [];
217 const seen = new Set<string>();
218
219 for (const pathValue of [preferredPath, inheritedPath]) {
220 if (!pathValue) continue;
221 for (const entry of pathValue.split(delimiter)) {
222 const trimmedEntry = trimPathEntry(entry, platform);
223 if (!trimmedEntry || seen.has(trimmedEntry)) {
224 continue;
225 }
226 seen.add(trimmedEntry);
227 merged.push(trimmedEntry);
228 }
229 }
230
231 return merged.length > 0 ? merged.join(delimiter) : undefined;
232}
233
234function isDirectory(dirPath: string): boolean {
235 try {
236 return NodeFS.statSync(dirPath).isDirectory();
237 } catch {
238 return false;
239 }
240}
241
242// Last resort when no PATH probe answers: a slow profile trips the login-shell
243// timeout, and `launchctl getenv PATH` is unset on recent macOS, which leaves a
244// Finder launch on the bare `/usr/bin:/bin:/usr/sbin:/sbin` PATH. Callers append
245// these after the inherited PATH so a caller-chosen nvm/mise/fnm binary still wins.
246export function listExistingPosixCliDirs(
247 env: NodeJS.ProcessEnv,
248 platform: NodeJS.Platform,
249): ReadonlyArray<string> {
250 const home = trimNonEmpty(env.HOME);
251 return [
252 platform === "darwin" ? "/opt/homebrew/bin" : "/home/linuxbrew/.linuxbrew/bin",
253 "/usr/local/bin",
254 ...(home ? [`${home}/.local/bin`] : []),
255 ].filter(isDirectory);
256}
257
258function envCaptureStart(name: string): string {
259 return `__T3CODE_ENV_${name}_START__`;
260}
261
262function envCaptureEnd(name: string): string {
263 return `__T3CODE_ENV_${name}_END__`;
264}
265
266const DEBUG_TRAP_SHELLS = new Set(["bash", "zsh", "sh", "ksh", "ksh93"]);
267const POSIX_CAPTURE_SYNTAX = { assignment: "__T3CODE_PRINTENV=$(", orElse: " || " };
268const PRINTENV_CAPTURE_SYNTAX = new Map(
269 [...DEBUG_TRAP_SHELLS, "dash", "ash"].map((shell) => [shell, POSIX_CAPTURE_SYNTAX] as const),
270).set("fish", { assignment: "set -l __T3CODE_PRINTENV (", orElse: "; or " });
271// Network PATH entries must be probed inside the shell's deadline, away from the desktop thread.
272const PRINTENV_LOOKUP_COMMAND = `/bin/sh -c 'command -v printenv || { [ -n "$1" ] && PATH="$1" command -v printenv; } || printf %s /usr/bin/printenv' t3`;
273
274export function buildEnvironmentCaptureCommand(
275 shell: string,
276 names: ReadonlyArray<string>,
277): string {
278 const executableName = NodePath.basename(shell).toLowerCase();
279 const isNushell = executableName.startsWith("nu");
280 const syntax = PRINTENV_CAPTURE_SYNTAX.get(executableName);
281 const supportsFallback = syntax !== undefined;
282 const inheritedPath = resolvePathEnvironmentVariable(process.env)
283 .split(POSIX_PATH_DELIMITER)
284 .filter(Boolean)
285 .map((entry) => NodePath.posix.resolve(entry))
286 .join(POSIX_PATH_DELIMITER);
287 const escapedPath =
288 executableName === "fish"
289 ? inheritedPath.replaceAll("\\", "\\\\").replaceAll("'", "\\'")
290 : inheritedPath.replaceAll("'", "'\\''");
291 const lookupPrintenv = `${PRINTENV_LOOKUP_COMMAND} '${escapedPath}'`;
292 const { assignment, orElse } = syntax ?? POSIX_CAPTURE_SYNTAX;
293 const resolvePrintenv = `${assignment}${lookupPrintenv}); `;
294
295 const capture = names
296 .map((name) => {
297 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
298 throw new Error(`Unsupported environment variable name: ${name}`);
299 }
300
301 if (isNushell) {
302 // Without a configured conversion, Nu expands home paths only in a list PATH.
303 const defaultValue =
304 name === "PATH"
305 ? "if ($env.PATH? | describe | str starts-with 'list') { " +
306 "$env.PATH | each {|p| if ($p | str starts-with '~') { " +
307 "$p | path expand --no-symlink } else { $p } } | str join (char esep) " +
308 "} else { $env.PATH? | default '' }"
309 : `$env.${name}? | default ''`;
310 const value =
311 `if $env.${name}? == null { '' } else if ` +
312 `$env.ENV_CONVERSIONS?.${name}?.to_string? != null { ` +
313 `$env.${name} | do $env.ENV_CONVERSIONS.${name}.to_string $env.${name} ` +
314 `} else { ${defaultValue} }`;
315 return [
316 `print '${envCaptureStart(name)}'`,
317 `print (${value})`,
318 `print '${envCaptureEnd(name)}'`,
319 ].join("; ");
320 }
321
322 return [
323 `printf '%s\\n' '${envCaptureStart(name)}'`,
324 supportsFallback
325 ? `printenv ${name}${orElse}"$__T3CODE_PRINTENV" ${name}${orElse}true`
326 : `printenv ${name} || true`,
327 `printf '%s\\n' '${envCaptureEnd(name)}'`,
328 ].join("; ");
329 })
330 .join("; ");
331
332 // A DEBUG trap that echoes each command (e.g. into the terminal title) would print the markers.
333 // OpenBSD ksh (also its /bin/sh) exits on `trap - DEBUG`, so try it in a subshell first.
334 const command = supportsFallback ? resolvePrintenv + capture : capture;
335 return DEBUG_TRAP_SHELLS.has(executableName)
336 ? `(trap - DEBUG) 2>/dev/null && trap - DEBUG; ${command}`
337 : command;
338}
339
340// Process first so profile prepends win; User and Machine add dirs missing from the launch snapshot.
341export function windowsEnvironmentValueCommand(name: string): string {
342 if (name === "PATH") {
343 return (
344 "$value = (@(" +
345 "[Environment]::GetEnvironmentVariable('PATH','Process')," +
346 "[Environment]::GetEnvironmentVariable('PATH','Machine')," +
347 "[Environment]::GetEnvironmentVariable('PATH','User')" +
348 ") | Where-Object { $_ }) -join ';'"
349 );
350 }
351 // A variable saved after this process started is only in the User or Machine registry scope.
352 return (
353 "$value = @(" +
354 `[Environment]::GetEnvironmentVariable('${name}','Process'),` +
355 `[Environment]::GetEnvironmentVariable('${name}','User'),` +
356 `[Environment]::GetEnvironmentVariable('${name}','Machine')` +
357 ") | Where-Object { $_ } | Select-Object -First 1"
358 );
359}
360
361function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
362 return [
363 "$ErrorActionPreference = 'Stop'",
364 // Redirected PowerShell output uses the console code page, which mangles non-ASCII paths.
365 "try { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch {}",
366 ...names.flatMap((name) => {
367 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
368 throw new Error(`Unsupported environment variable name: ${name}`);
369 }
370
371 return [
372 `Write-Output '${envCaptureStart(name)}'`,
373 windowsEnvironmentValueCommand(name),
374 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
375 `Write-Output '${envCaptureEnd(name)}'`,
376 ];
377 }),
378 ].join("; ");
379}
380
381function extractEnvironmentValue(output: string, name: string): string | undefined {
382 const startMarker = envCaptureStart(name);
383 const endMarker = envCaptureEnd(name);
384 const startIndex = output.indexOf(startMarker);
385 if (startIndex === -1) return undefined;
386
387 const valueStartIndex = startIndex + startMarker.length;
388 // The end marker is only a framing line; the same text may appear inside the value.
389 const endLine = new RegExp(`\\r?\\n${endMarker}(?=\\r?\\n|$)`, "g");
390 endLine.lastIndex = valueStartIndex;
391 const endMatch = endLine.exec(output);
392 if (endMatch === null) return undefined;
393
394 const value = output.slice(valueStartIndex, endMatch.index).replace(/^\r?\n/, "");
395
396 return value.length > 0 ? value : undefined;
397}
398
399/** Reads the values `buildEnvironmentCaptureCommand` printed; unset or empty names are omitted. */
400export function extractEnvironmentValues(
401 output: string,
402 names: ReadonlyArray<string>,
403): Partial<Record<string, string>> {
404 const environment: Partial<Record<string, string>> = {};
405 for (const name of names) {
406 const value = extractEnvironmentValue(output, name);
407 if (value !== undefined) {
408 environment[name] = value;
409 }
410 }
411 return environment;
412}
413
414export type ShellEnvironmentReader = (
415 shell: string,
416 names: ReadonlyArray<string>,
417 execFile?: ExecFileSyncLike,
418) => Partial<Record<string, string>>;
419
420export const readEnvironmentFromLoginShell: ShellEnvironmentReader = (
421 shell,
422 names,
423 execFile = NodeChildProcess.execFileSync,
424) => {
425 if (names.length === 0) {
426 return {};
427 }
428
429 // Interactive startup loads PATH entries; detaching prevents job control on an
430 // inherited controlling TTY from stopping the probe while the parent waits.
431 const output = execFile(shell, ["-ilc", buildEnvironmentCaptureCommand(shell, names)], {
432 encoding: "utf8",
433 timeout: 5000,
434 killSignal: "SIGKILL",
435 detached: true,
436 stdio: ["ignore", "pipe", "ignore"],
437 });
438
439 return extractEnvironmentValues(output, names);
440};
441
442export type WindowsShellEnvironmentReader = (
443 names: ReadonlyArray<string>,
444 options?: WindowsEnvironmentProbeOptions,
445) => Effect.Effect<Partial<Record<string, string>>>;
446
447export const WindowsShellEnvironment = Context.Reference<WindowsShellEnvironmentReader>(
448 "@t3tools/shared/shell/WindowsShellEnvironment",
449 {
450 defaultValue: () => readEnvironmentFromWindowsShell,
451 },
452);
453
454export const CommandAvailability = Context.Reference<CommandAvailabilityChecker>(
455 "@t3tools/shared/shell/CommandAvailability",
456 {
457 defaultValue: () => isCommandAvailable,
458 },
459);
460
461const execWindowsEnvironmentProbe = (
462 file: string,
463 args: ReadonlyArray<string>,
464 options: { encoding: "utf8"; timeout: number },
465) =>
466 Effect.callback<Option.Option<string>>((resume) => {
467 let child: NodeChildProcess.ChildProcess;
468 try {
469 child = NodeChildProcess.execFile(
470 file,
471 args,
472 { ...options, windowsHide: true },
473 (error, stdout) => {
474 resume(Effect.succeed(error ? Option.none() : Option.some(stdout)));
475 },
476 );
477 } catch {
478 resume(Effect.succeedNone);
479 return;
480 }
481 return Effect.sync(() => {
482 child.kill();
483 child.stdout?.destroy();
484 child.stderr?.destroy();
485 child.unref();
486 });
487 });
488
489export const readEnvironmentFromWindowsShell = Effect.fn("shell.readEnvironmentFromWindowsShell")(
490 function* (
491 names: ReadonlyArray<string>,
492 options: WindowsEnvironmentProbeOptions = {},
493 execFile: typeof execWindowsEnvironmentProbe = execWindowsEnvironmentProbe,
494 ) {
495 if (names.length === 0) return {};
496
497 const command = buildWindowsEnvironmentCaptureCommand(names);
498 const args = [
499 "-NoLogo",
500 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
501 "-NonInteractive",
502 "-Command",
503 command,
504 ];
505 for (const shell of WINDOWS_SHELL_CANDIDATES) {
506 const output = yield* execFile(shell, args, {
507 encoding: "utf8",
508 timeout: WINDOWS_SHELL_PROBE_TIMEOUT_MS,
509 }).pipe(Effect.timeoutOption(WINDOWS_SHELL_PROBE_DEADLINE), Effect.map(Option.flatten));
510 if (Option.isNone(output)) continue;
511
512 const environment: Partial<Record<string, string>> = {};
513 for (const name of names) {
514 const value = extractEnvironmentValue(output.value, name);
515 if (value !== undefined) environment[name] = value;
516 }
517 return environment;
518 }
519
520 return {};
521 },
522);
523
524function trimPathEntry(entry: string, platform: NodeJS.Platform): string {
525 return platform === "win32" ? entry.trim() : entry;
526}
527
528// POSIX PATH entries are literal: whitespace and quotes are part of the directory name.
529function normalizePathEntry(entry: string, platform: NodeJS.Platform): string {
530 return platform === "win32" ? entry.trim().replace(/^"+|"+$/g, "") : entry;
531}
532
533function pathDelimiterForPlatform(platform: NodeJS.Platform): string {
534 return platform === "win32" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER;
535}
536
537function normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string {
538 const normalized = normalizePathEntry(entry, platform);
539 return platform === "win32" ? normalized.toLowerCase() : normalized;
540}
541
542function sanitizePathEntry(entry: string, platform: NodeJS.Platform): string {
543 return platform === "win32" ? entry.replaceAll('"', "") : entry;
544}
545
546export function mergePathValues(
547 preferredPath: string | undefined,
548 inheritedPath: string | undefined,
549 platform: NodeJS.Platform,
550): string | undefined {
551 const delimiter = pathDelimiterForPlatform(platform);
552 const merged: string[] = [];
553 const seen = new Set<string>();
554
555 for (const rawValue of [preferredPath, inheritedPath]) {
556 if (!rawValue) continue;
557
558 for (const entry of rawValue.split(delimiter)) {
559 const sanitized = sanitizePathEntry(trimPathEntry(entry, platform), platform);
560 if (sanitized.length === 0) continue;
561
562 const normalized = normalizePathEntryForComparison(sanitized, platform);
563 if (normalized.length === 0 || seen.has(normalized)) continue;
564
565 seen.add(normalized);
566 merged.push(sanitized);
567 }
568 }
569
570 return merged.length > 0 ? merged.join(delimiter) : undefined;
571}
572
573function readEnvPath(env: NodeJS.ProcessEnv): string | undefined {
574 return env.PATH ?? env.Path ?? env.path;
575}
576
577function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
578 return readEnvPath(env) ?? "";
579}
580
581function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
582 const rawValue =
583 env.PATHEXT ??
584 Object.entries(env).find(
585 ([key, value]) => key.toUpperCase() === "PATHEXT" && value !== undefined,
586 )?.[1];
587 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
588 if (!rawValue) return fallback;
589
590 const parsed: string[] = [];
591 for (const entry of rawValue.split(";")) {
592 const trimmed = entry.trim();
593 if (trimmed.length === 0) continue;
594 parsed.push(trimmed.startsWith(".") ? trimmed.toUpperCase() : `.${trimmed.toUpperCase()}`);
595 }
596 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
597}
598
599function resolveCommandCandidates(
600 command: string,
601 platform: NodeJS.Platform,
602 windowsPathExtensions: ReadonlyArray<string>,
603 extname: (path: string) => string,
604): ReadonlyArray<string> {
605 if (platform !== "win32") return [command];
606 const extension = extname(command);
607 const normalizedExtension = extension.toUpperCase();
608
609 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
610 const commandWithoutExtension = command.slice(0, -extension.length);
611 return Array.from(
612 new Set([
613 command,
614 `${commandWithoutExtension}${normalizedExtension}`,
615 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
616 ]),
617 );
618 }
619
620 const candidates: string[] = [];
621 for (const candidateExtension of windowsPathExtensions) {
622 candidates.push(`${command}${candidateExtension}`);
623 candidates.push(`${command}${candidateExtension.toLowerCase()}`);
624 }
625 return Array.from(new Set(candidates));
626}
627
628// Explicit paths bypass the cache for new installs; cached misses can otherwise hide binaries for 30 seconds.
629const COMMAND_RESOLUTION_CACHE_TTL_NANOS = 30_000_000_000n;
630const COMMAND_RESOLUTION_CACHE_MAX_ENTRIES = 512;
631const COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR = String.fromCharCode(0);
632
633interface CommandResolutionCacheEntry {
634 readonly resolvedPath: string | null;
635 readonly expiresAtNanos: bigint;
636}
637
638export const CommandResolutionCache = Context.Reference<Map<string, CommandResolutionCacheEntry>>(
639 "@t3tools/shared/shell/CommandResolutionCache",
640 {
641 defaultValue: () => new Map(),
642 },
643);
644
645interface PathDirectoryListing {
646 readonly modified: number | null | undefined;
647 /** Lowercased entry names; undefined when the directory cannot be listed. */
648 readonly names: ReadonlySet<string> | undefined;
649 /** Entry names as the directory spells them; undefined with `names`. */
650 readonly casedNames: ReadonlySet<string> | undefined;
651 readonly reusable: boolean;
652}
653
654const PATH_DIRECTORY_LISTINGS_MAX_ENTRIES = 1024;
655// A directory changed within a coarse filesystem's timestamp step (FAT: 2 s) can change again
656// without moving its mtime, so its listing serves the lookups waiting on it but is not kept.
657const PATH_DIRECTORY_SETTLE_MS = 2_000;
658const NO_DIRECTORY_NAMES: ReadonlySet<string> = new Set();
659
660// A listing only speaks for names Windows matches by ASCII case folding. It omits 8.3 aliases
661// (`~`), Windows trims a trailing dot, and other characters fold differently than in JS.
662const LISTED_NAME_PATTERN = /^[\w.+-]*[\w+-]$/;
663
664function isAbsentFromListing(names: ReadonlySet<string> | undefined, candidate: string): boolean {
665 return (
666 names !== undefined &&
667 LISTED_NAME_PATTERN.test(candidate) &&
668 !names.has(candidate.toLowerCase())
669 );
670}
671
672// A case-folded probe can succeed under a spelling the directory does not hold.
673function listedCandidateName(
674 casedNames: ReadonlySet<string> | undefined,
675 candidate: string,
676): string {
677 if (!casedNames || casedNames.has(candidate) || !LISTED_NAME_PATTERN.test(candidate)) {
678 return candidate;
679 }
680 for (const entry of casedNames) {
681 if (entry.toLowerCase() === candidate.toLowerCase()) return entry;
682 }
683 return candidate;
684}
685
686// The listing must start after the mtime's timestamp step has passed, and a relative entry
687// names another directory once the working directory changes.
688function isReusableListing(
689 directory: string,
690 modified: number,
691 listedAtMs: number,
692 isAbsolute: (path: string) => boolean,
693): boolean {
694 return isAbsolute(directory) && listedAtMs - modified >= PATH_DIRECTORY_SETTLE_MS;
695}
696
697const directoryMtime = (directory: string) =>
698 FileSystem.FileSystem.use((fileSystem) => fileSystem.stat(directory)).pipe(
699 Effect.map((info) =>
700 info.type === "Directory" ? Option.getOrUndefined(info.mtime)?.getTime() : undefined,
701 ),
702 Effect.catch((error) => Effect.succeed(error.reason._tag === "NotFound" ? null : undefined)),
703 );
704
705// Timestamp before reading so concurrent additions change the next mtime check; missing listings fall back to direct probes.
706const listPathDirectory = Effect.fnUntraced(function* (
707 directory: string,
708): Effect.fn.Return<PathDirectoryListing, never, FileSystem.FileSystem | Path.Path> {
709 const path = yield* Path.Path;
710 const modified = yield* directoryMtime(directory);
711 if (modified === null) {
712 return {
713 modified,
714 names: NO_DIRECTORY_NAMES,
715 casedNames: NO_DIRECTORY_NAMES,
716 reusable: path.isAbsolute(directory),
717 };
718 }
719 if (modified === undefined) {
720 return { modified, names: undefined, casedNames: undefined, reusable: false };
721 }
722 const listedAtMs = yield* Clock.currentTimeMillis;
723 const entries = yield* FileSystem.FileSystem.use((fileSystem) =>
724 fileSystem.readDirectory(directory),
725 ).pipe(Effect.orElseSucceed(() => undefined));
726 return {
727 modified,
728 names: entries && new Set(entries.map((entry) => entry.toLowerCase())),
729 casedNames: entries && new Set(entries),
730 reusable:
731 entries !== undefined && isReusableListing(directory, modified, listedAtMs, path.isAbsolute),
732 };
733});
734
735export const makePathDirectoryListings = Cache.makeWith(listPathDirectory, {
736 capacity: PATH_DIRECTORY_LISTINGS_MAX_ENTRIES,
737 timeToLive: (exit) =>
738 Exit.isSuccess(exit) && exit.value.reusable ? Duration.infinity : Duration.zero,
739 requireServicesAt: "lookup",
740});
741
742/** Windows PATH directory listings for the process; each use rechecks the directory's mtime. */
743export const PathDirectoryListings = Context.Reference(
744 "@t3tools/shared/shell/PathDirectoryListings",
745 { defaultValue: () => Effect.runSync(makePathDirectoryListings) },
746);
747
748interface ResolverPathDirectoryListing {
749 readonly names: ReadonlySet<string>;
750 readonly casedNames: ReadonlySet<string>;
751}
752
753const resolverPathDirectoryListings = new Map<
754 string,
755 { readonly modified: number; readonly listing: ResolverPathDirectoryListing }
756>();
757
758// The spawn resolver's counterpart of `PathDirectoryListings`, under the same rules.
759async function listResolverPathDirectory(
760 directory: string,
761 isAbsolute: (path: string) => boolean,
762): Promise<ResolverPathDirectoryListing | undefined> {
763 let modified: number;
764 try {
765 const stats = await NodeFS.promises.stat(directory);
766 if (!stats.isDirectory()) return undefined;
767 modified = stats.mtimeMs;
768 } catch (error) {
769 return (error as NodeJS.ErrnoException).code === "ENOENT"
770 ? { names: NO_DIRECTORY_NAMES, casedNames: NO_DIRECTORY_NAMES }
771 : undefined;
772 }
773 const cached = resolverPathDirectoryListings.get(directory);
774 if (cached?.modified === modified) return cached.listing;
775 resolverPathDirectoryListings.delete(directory);
776 // This resolver runs outside Effect, so it has no Clock to read.
777 // @effect-diagnostics-next-line globalDate:off
778 const listedAtMs = Date.now();
779 let listing: ResolverPathDirectoryListing;
780 try {
781 const entries = await NodeFS.promises.readdir(directory);
782 listing = {
783 names: new Set(entries.map((entry) => entry.toLowerCase())),
784 casedNames: new Set(entries),
785 };
786 } catch {
787 return undefined;
788 }
789 if (isReusableListing(directory, modified, listedAtMs, isAbsolute)) {
790 if (resolverPathDirectoryListings.size >= PATH_DIRECTORY_LISTINGS_MAX_ENTRIES) {
791 const oldest = resolverPathDirectoryListings.keys().next().value;
792 if (oldest !== undefined) resolverPathDirectoryListings.delete(oldest);
793 }
794 resolverPathDirectoryListings.set(directory, { modified, listing });
795 }
796 return listing;
797}
798
799// An injected resolver or locator may answer differently for the same search, so its
800// entries are kept apart from every other resolver's.
801let spawnResolverCacheIdCount = 0;
802const spawnResolverCacheIds = new WeakMap<SpawnExecutableResolver | XcodeGitLocator, number>();
803function spawnResolverCacheId(resolver: SpawnExecutableResolver | XcodeGitLocator): number {
804 const known = spawnResolverCacheIds.get(resolver);
805 if (known !== undefined) return known;
806 const id = spawnResolverCacheIdCount++;
807 spawnResolverCacheIds.set(resolver, id);
808 return id;
809}
810
811function cacheCommandResolution(
812 cache: Map<string, CommandResolutionCacheEntry>,
813 cacheKey: string,
814 resolvedPath: string | null,
815 nowNanos: bigint,
816): void {
817 if (cache.size >= COMMAND_RESOLUTION_CACHE_MAX_ENTRIES) {
818 const oldestKey = cache.keys().next().value;
819 if (oldestKey !== undefined) {
820 cache.delete(oldestKey);
821 }
822 }
823 cache.set(cacheKey, {
824 resolvedPath,
825 expiresAtNanos: nowNanos + COMMAND_RESOLUTION_CACHE_TTL_NANOS,
826 });
827}
828
829const isExecutableFile = Effect.fnUntraced(function* (
830 filePath: string,
831 platform: NodeJS.Platform,
832 windowsPathExtensions: ReadonlyArray<string>,
833): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
834 const fileSystem = yield* FileSystem.FileSystem;
835 const path = yield* Path.Path;
836 const stat = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
837 if (stat === null || stat.type !== "File") return false;
838
839 if (platform === "win32") {
840 const extension = path.extname(filePath);
841 if (extension.length === 0) return false;
842 return windowsPathExtensions.includes(extension.toUpperCase());
843 }
844
845 return canExecuteFile(filePath);
846});
847
848// Keep case variants: Windows can make PATH directories case-sensitive.
849function pathEntriesForPlatform(pathValue: string, platform: NodeJS.Platform): string[] {
850 const pathEntries: string[] = [];
851 const seenPathEntries = new Set<string>();
852 for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) {
853 // A raw empty component of a nonempty POSIX PATH is the current directory.
854 const pathEntry =
855 entry === "" && pathValue !== "" && platform !== "win32"
856 ? "."
857 : normalizePathEntry(entry, platform);
858 if (pathEntry.length === 0 || seenPathEntries.has(pathEntry)) continue;
859
860 seenPathEntries.add(pathEntry);
861 pathEntries.push(pathEntry);
862 }
863 return pathEntries;
864}
865
866// Relative POSIX PATH entries resolve against the working directory, so caches keyed by them include it.
867// null: a relative entry is present but the working directory cannot be read, so nothing is cached.
868function pathSearchCwd(pathValue: string, platform: NodeJS.Platform): string | null | undefined {
869 if (platform === "win32") return undefined;
870 if (
871 pathEntriesForPlatform(pathValue, platform).every((entry) => NodePath.posix.isAbsolute(entry))
872 ) {
873 return undefined;
874 }
875 try {
876 return process.cwd();
877 } catch {
878 return null;
879 }
880}
881
882// Called within the traced command resolvers.
883const findOnPath = Effect.fnUntraced(function* (
884 pathValue: string,
885 commandCandidates: ReadonlyArray<string>,
886 platform: NodeJS.Platform,
887 windowsPathExtensions: ReadonlyArray<string>,
888 isLast: (match: string) => boolean,
889 // The caller's snapshot, so a cache key and the search it stores agree on the directory.
890 cwd: string | null | undefined,
891): Effect.fn.Return<ReadonlyArray<string>, never, FileSystem.FileSystem | Path.Path> {
892 const path = yield* Path.Path;
893 const pathEntries = pathEntriesForPlatform(pathValue, platform);
894
895 // A match through an empty component is anchored: callers may launch it from another cwd or
896 // through a wrapper. A literal "." keeps its relative spelling; the first of the two wins, as
897 // in the deduplicated walk.
898 const anchorsCwd =
899 typeof cwd === "string" &&
900 pathValue
901 .split(pathDelimiterForPlatform(platform))
902 .find((entry) => entry === "" || entry === ".") === "";
903
904 // Only Windows multiplies the candidates per directory; elsewhere a listing saves no probe.
905 const listings = platform === "win32" ? yield* PathDirectoryListings : undefined;
906 const matches: string[] = [];
907 for (const pathEntry of pathEntries) {
908 let listing = listings && (yield* Cache.get(listings, pathEntry));
909 if (listings && listing?.names && listing.modified !== (yield* directoryMtime(pathEntry))) {
910 yield* Cache.invalidate(listings, pathEntry);
911 listing = yield* Cache.get(listings, pathEntry);
912 }
913 for (const candidate of commandCandidates) {
914 if (isAbsentFromListing(listing?.names, candidate)) continue;
915 // Probe what is returned: other relative entries stay relative, since the cached cwd
916 // spelling goes stale when the directory is renamed.
917 const match =
918 anchorsCwd && pathEntry === "."
919 ? path.join(cwd, candidate)
920 : path.join(pathEntry, candidate);
921 if (yield* isExecutableFile(match, platform, windowsPathExtensions)) {
922 const cased = listedCandidateName(listing?.casedNames, candidate);
923 const returned =
924 cased === candidate
925 ? match
926 : anchorsCwd && pathEntry === "."
927 ? path.join(cwd, cased)
928 : path.join(pathEntry, cased);
929 matches.push(returned);
930 if (isLast(returned)) return matches;
931 break;
932 }
933 }
934 }
935 return matches;
936});
937
938const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlatform", {
939 attributes: routineSpan,
940})(function* (
941 command: string,
942 options: CommandAvailabilityOptions & { readonly platform: NodeJS.Platform },
943): Effect.fn.Return<string | null, never, FileSystem.FileSystem | Path.Path> {
944 const path = yield* Path.Path;
945 const platform = options.platform;
946 const env = options.env ?? process.env;
947 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
948 const commandCandidates = resolveCommandCandidates(
949 command,
950 platform,
951 windowsPathExtensions,
952 path.extname,
953 );
954
955 if (isExplicitCommandPath(command, platform)) {
956 for (const candidate of commandCandidates) {
957 if (yield* isExecutableFile(candidate, platform, windowsPathExtensions)) {
958 return candidate;
959 }
960 }
961 return null;
962 }
963
964 const pathValue = resolvePathEnvironmentVariable(env);
965 if (pathValue.length === 0) {
966 return null;
967 }
968
969 const cwd = pathSearchCwd(pathValue, platform);
970 const cacheKey = [
971 platform,
972 pathValue,
973 windowsPathExtensions.join(";"),
974 command,
975 ...(cwd === undefined ? [] : [cwd]),
976 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
977 const cache = yield* CommandResolutionCache;
978 const nowNanos = yield* Clock.monotonicTimeNanos;
979 const cached = cwd === null ? undefined : cache.get(cacheKey);
980 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
981 return cached.resolvedPath;
982 }
983
984 const [resolvedPath = null] = yield* findOnPath(
985 pathValue,
986 commandCandidates,
987 platform,
988 windowsPathExtensions,
989 () => true,
990 cwd,
991 );
992 if (cwd !== null) cacheCommandResolution(cache, cacheKey, resolvedPath, nowNanos);
993 return resolvedPath;
994});
995
996export const resolveCommandPath = Effect.fn("shell.resolveCommandPath", {
997 attributes: routineSpan,
998})(function* (command: string, options: CommandAvailabilityOptions = {}) {
999 return yield* resolveCommandPathForPlatform(command, {
1000 env: options.env ?? (yield* HostProcess.Environment),
1001 platform: yield* HostProcess.Platform,
1002 });
1003});
1004
1005// Matches for a bare command in PATH order, up to the first one `until` accepts; not cached.
1006export const resolveCommandPaths = Effect.fn("shell.resolveCommandPaths", {
1007 attributes: routineSpan,
1008})(function* (
1009 command: string,
1010 options: CommandAvailabilityOptions & { readonly until: (match: string) => boolean },
1011) {
1012 const path = yield* Path.Path;
1013 const platform = yield* HostProcess.Platform;
1014 const env = options.env ?? (yield* HostProcess.Environment);
1015 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
1016 const pathValue = resolvePathEnvironmentVariable(env);
1017 return yield* findOnPath(
1018 pathValue,
1019 resolveCommandCandidates(command, platform, windowsPathExtensions, path.extname),
1020 platform,
1021 windowsPathExtensions,
1022 options.until,
1023 pathSearchCwd(pathValue, platform),
1024 );
1025});
1026
1027// Git 2.56 x64 uses ucrt64; ARM64 uses clangarm64; older x64/32-bit builds use mingw64/mingw32.
1028const GIT_FOR_WINDOWS_BUILDS = ["ucrt64", "clangarm64", "mingw64", "mingw32"] as const;
1029
1030function isFileSync(filePath: string): boolean {
1031 try {
1032 return NodeFS.statSync(filePath).isFile();
1033 } catch {
1034 return false;
1035 }
1036}
1037
1038/** Bypass the launcher's extra process and kernel-token leak. Retain it when MSYSTEM is set, or git.exe omits hook/helper PATH entries. */
1039export function preferGitForWindowsBinary(
1040 executable: string,
1041 env: NodeJS.ProcessEnv,
1042 isFile: (filePath: string) => boolean = isFileSync,
1043): string {
1044 if (env.MSYSTEM) return executable;
1045 const path = NodePath.win32;
1046 if (path.basename(executable).toLowerCase() !== "git.exe") return executable;
1047 const launcherDirectory = path.dirname(executable);
1048 const launcherFolder = path.basename(launcherDirectory).toLowerCase();
1049 if (launcherFolder !== "cmd" && launcherFolder !== "bin") return executable;
1050 const installRoot = path.dirname(launcherDirectory);
1051 for (const build of GIT_FOR_WINDOWS_BUILDS) {
1052 const candidate = path.join(installRoot, build, "bin", "git.exe");
1053 if (isFile(candidate)) return candidate;
1054 }
1055 return executable;
1056}
1057
1058/** Git for Windows' bash beside a git.exe from its install, never WSL's System32 bash.exe. */
1059export function gitForWindowsBash(
1060 gitExecutable: string,
1061 isFile: (filePath: string) => boolean = isFileSync,
1062): string | undefined {
1063 const path = NodePath.win32;
1064 if (path.basename(gitExecutable).toLowerCase() !== "git.exe") return undefined;
1065 // git.exe lives in <root>\cmd, <root>\bin, or <root>\<build>\bin.
1066 const launcherRoot = path.dirname(path.dirname(gitExecutable));
1067 return [launcherRoot, path.dirname(launcherRoot)]
1068 .map((root) => path.join(root, "bin", "bash.exe"))
1069 .find(isFile);
1070}
1071
1072// npm cmd-shim format for native executables.
1073const NPM_EXECUTABLE_SHIM_PREFIX = [
1074 "@ECHO off",
1075 "GOTO start",
1076 ":find_dp0",
1077 "SET dp0=%~dp0",
1078 "EXIT /b",
1079 ":start",
1080 "SETLOCAL",
1081 "CALL :find_dp0",
1082];
1083const NPM_EXECUTABLE_SHIM_RUN = /^"%dp0%\\([^"%]+\.exe)" +%\*$/;
1084
1085function readFileSyncOrUndefined(filePath: string): string | undefined {
1086 try {
1087 return NodeFS.readFileSync(filePath, "utf8");
1088 } catch {
1089 return undefined;
1090 }
1091}
1092
1093/** Resolve shims that only launch native executables so direct spawning keeps them in libuv's kill-on-close job. */
1094export function npmShimExecutable(
1095 shimPath: string,
1096 readFile: (filePath: string) => string | undefined = readFileSyncOrUndefined,
1097 isFile: (filePath: string) => boolean = isFileSync,
1098): string | undefined {
1099 const path = NodePath.win32;
1100 if (path.extname(shimPath).toLowerCase() !== ".cmd") return undefined;
1101 // Match exactly because preserved SET whitespace can select a different file.
1102 const lines = readFile(shimPath)
1103 ?.split(/\r?\n/)
1104 .filter((line) => line.length > 0);
1105 if (lines?.length !== NPM_EXECUTABLE_SHIM_PREFIX.length + 1) return undefined;
1106 if (NPM_EXECUTABLE_SHIM_PREFIX.some((expected, index) => lines[index] !== expected)) {
1107 return undefined;
1108 }
1109 const target = NPM_EXECUTABLE_SHIM_RUN.exec(lines.at(-1)!)?.[1];
1110 if (target === undefined) return undefined;
1111 const executable = path.join(path.dirname(shimPath), target);
1112 return isFile(executable) ? executable : undefined;
1113}
1114
1115export type XcodeGitLocator = (env: NodeJS.ProcessEnv) => string | undefined;
1116
1117// xcrun honors DEVELOPER_DIR and the `xcode-select` choice, as the shim does.
1118function locateXcodeGitWithXcrun(env: NodeJS.ProcessEnv): string | undefined {
1119 try {
1120 const located = NodeChildProcess.execFileSync("/usr/bin/xcrun", ["--find", "git"], {
1121 encoding: "utf8",
1122 env,
1123 timeout: 5_000,
1124 stdio: ["ignore", "pipe", "ignore"],
1125 }).trim();
1126 return NodePath.isAbsolute(located) ? located : undefined;
1127 } catch {
1128 return undefined;
1129 }
1130}
1131
1132export const XcodeGitLocation = Context.Reference<XcodeGitLocator>(
1133 "@t3tools/shared/shell/XcodeGitLocation",
1134 { defaultValue: () => locateXcodeGitWithXcrun },
1135);
1136
1137const MACOS_GIT_SHIM = "/usr/bin/git";
1138
1139/**
1140 * Skip the xcrun shim's per-spawn lookup only when git resolves to /usr/bin/git.
1141 * User-selected git on PATH still wins, children keep PATH, and lookup failures use `git`.
1142 */
1143const resolveMacosGit = Effect.fnUntraced(function* (
1144 env: NodeJS.ProcessEnv,
1145 resolveExecutable: SpawnExecutableResolver,
1146) {
1147 const locateXcodeGit = yield* XcodeGitLocation;
1148 const cache = yield* CommandResolutionCache;
1149 const pathValue = resolvePathEnvironmentVariable(env);
1150 const nowNanos = yield* Clock.currentTimeNanos;
1151 // Read after the clock, so the lookup below starts in the directory the key names.
1152 const cwd = pathSearchCwd(pathValue, "darwin");
1153 const cacheKey = [
1154 "xcode-git",
1155 String(spawnResolverCacheId(resolveExecutable)),
1156 String(spawnResolverCacheId(locateXcodeGit)),
1157 pathValue,
1158 env.DEVELOPER_DIR ?? "",
1159 ...(cwd === undefined ? [] : [cwd]),
1160 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
1161 const cached = cwd === null ? undefined : cache.get(cacheKey);
1162 // An Xcode update or removal deletes the binary; look again instead of failing the spawn.
1163 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
1164 const cachedPath = cached.resolvedPath;
1165 if (
1166 cachedPath === null ||
1167 (yield* Effect.promise(async () => resolveExecutable(cachedPath, "darwin", env))) !==
1168 undefined
1169 ) {
1170 return cachedPath ?? "git";
1171 }
1172 }
1173 const pathGit = yield* Effect.promise(async () => resolveExecutable("git", "darwin", env));
1174 const located = pathGit === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined;
1175 const realGit =
1176 located !== undefined &&
1177 (yield* Effect.promise(async () => resolveExecutable(located, "darwin", env))) !== undefined
1178 ? located
1179 : // A match anchored to the cwd came through an empty PATH entry, which a child would search
1180 // again from its own cwd; launch the file that was checked instead of bare `git`.
1181 typeof cwd === "string" && pathGit === NodePath.posix.join(cwd, "git")
1182 ? pathGit
1183 : null;
1184 // The lookups above await and the cwd can move meanwhile; cache only what the key's cwd found.
1185 if (cwd !== null && pathSearchCwd(pathValue, "darwin") === cwd) {
1186 cacheCommandResolution(cache, cacheKey, realGit, nowNanos);
1187 }
1188 return realGit ?? "git";
1189});
1190
1191export interface SpawnCommandOptions extends CommandAvailabilityOptions {
1192 /** Bypass npm cmd-shims; see npmShimExecutable for process-lifetime semantics. */
1193 readonly bypassNpmShim?: boolean;
1194}
1195
1196// `*` is one argument that is not an option. These forms read refs or config
1197// only, so git starts no hook, helper, pager, editor or lazy fetch for them.
1198const CONSOLE_FREE_GIT_READS = [
1199 "rev-parse --git-path index",
1200 "rev-parse --git-common-dir",
1201 "rev-parse --show-toplevel",
1202 "rev-parse --git-common-dir --show-toplevel",
1203 "rev-parse --path-format=absolute --git-path index --git-common-dir --show-toplevel",
1204 "rev-parse --symbolic-full-name HEAD",
1205 "rev-parse --abbrev-ref --symbolic-full-name @{upstream}",
1206 "symbolic-ref --quiet HEAD",
1207 "symbolic-ref *",
1208 "remote",
1209 "remote get-url *",
1210 "remote get-url -- *",
1211 "config --get *",
1212].map((form) => form.split(" "));
1213
1214export function runsGitWithoutConsole(
1215 platform: NodeJS.Platform,
1216 executable: string,
1217 args: ReadonlyArray<string>,
1218): boolean {
1219 if (platform !== "win32") return false;
1220 const { basename, dirname } = NodePath.win32;
1221 const bin = dirname(executable);
1222 const build = basename(dirname(bin)).toLowerCase();
1223 if (basename(executable).toLowerCase() !== "git.exe" || basename(bin).toLowerCase() !== "bin") {
1224 return false;
1225 }
1226 if (!GIT_FOR_WINDOWS_BUILDS.some((candidate) => candidate === build)) return false;
1227 const rest =
1228 args[0] === "--git-dir" && args[1] !== undefined && !args[1].startsWith("-")
1229 ? args.slice(2)
1230 : args;
1231 return CONSOLE_FREE_GIT_READS.some(
1232 (form) =>
1233 form.length === rest.length &&
1234 form.every((part, i) => part === rest[i] || (part === "*" && !rest[i]!.startsWith("-"))),
1235 );
1236}
1237
1238export const resolveSpawnCommand = Effect.fnUntraced(function* (
1239 command: string,
1240 args: ReadonlyArray<string>,
1241 options: SpawnCommandOptions = {},
1242): Effect.fn.Return<ResolvedSpawnCommand> {
1243 const platform = yield* HostProcess.Platform;
1244 const isMacosGit = platform === "darwin" && command === "git";
1245 if (platform !== "win32" && !isMacosGit) {
1246 return { command, args: [...args], shell: false };
1247 }
1248
1249 const hostEnvironment = yield* HostProcess.Environment;
1250 const env =
1251 options.env === undefined
1252 ? hostEnvironment
1253 : options.extendEnv
1254 ? { ...hostEnvironment, ...options.env }
1255 : options.env;
1256 const resolveExecutable = yield* SpawnExecutableResolution;
1257 if (isMacosGit) {
1258 return {
1259 command: yield* resolveMacosGit(env, resolveExecutable),
1260 args: [...args],
1261 shell: false,
1262 };
1263 }
1264 // Cache successful PATH lookups. Explicit paths and misses stay uncached so
1265 // newly installed executables are discoverable immediately.
1266 const explicitPath = isExplicitCommandPath(command, platform);
1267 const cache = yield* CommandResolutionCache;
1268 const cacheKey = [
1269 "spawn",
1270 String(spawnResolverCacheId(resolveExecutable)),
1271 platform,
1272 resolvePathEnvironmentVariable(env),
1273 resolveWindowsPathExtensions(env).join(";"),
1274 env.MSYSTEM ? "msystem" : "",
1275 command,
1276 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
1277 const nowNanos = yield* Clock.currentTimeNanos;
1278 const cached = explicitPath ? undefined : cache.get(cacheKey);
1279 let resolvedExecutable: string | null;
1280 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
1281 resolvedExecutable = cached.resolvedPath;
1282 } else {
1283 const found = yield* Effect.promise(async () => resolveExecutable(command, platform, env));
1284 resolvedExecutable = found === undefined ? null : preferGitForWindowsBinary(found, env);
1285 if (!explicitPath && resolvedExecutable !== null) {
1286 cacheCommandResolution(cache, cacheKey, resolvedExecutable, nowNanos);
1287 }
1288 }
1289 const resolvedCommand = resolvedExecutable ?? command;
1290 const extension = NodePath.win32.extname(resolvedCommand).toLowerCase();
1291 if (extension !== ".cmd" && extension !== ".bat") {
1292 return { command: resolvedCommand, args: [...args], shell: false };
1293 }
1294 const shimExecutable = options.bypassNpmShim ? npmShimExecutable(resolvedCommand) : undefined;
1295 if (shimExecutable !== undefined) {
1296 return { command: shimExecutable, args: [...args], shell: false };
1297 }
1298
1299 // Build the escaped command line without separate args to avoid Node DEP0190 with shell:true.
1300 return {
1301 command: [resolvedCommand, ...args].map(escapeWindowsShellArg).join(" "),
1302 args: [],
1303 shell: true,
1304 };
1305});
1306
1307export const isCommandAvailable = Effect.fn("shell.isCommandAvailable")(function* (
1308 command: string,
1309 options: CommandAvailabilityOptions = {},
1310) {
1311 return (yield* resolveCommandPath(command, options)) !== null;
1312});
1313
1314function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
1315 const appData = env.APPDATA?.trim();
1316 const localAppData = env.LOCALAPPDATA?.trim();
1317 const userProfile = env.USERPROFILE?.trim();
1318
1319 return [
1320 ...(appData ? [`${appData}\\npm`] : []),
1321 ...(localAppData ? [`${localAppData}\\Programs\\nodejs`, `${localAppData}\\Volta\\bin`] : []),
1322 ...(localAppData ? [`${localAppData}\\pnpm`] : []),
1323 ...(userProfile
1324 ? [`${userProfile}\\.local\\bin`, `${userProfile}\\.bun\\bin`, `${userProfile}\\scoop\\shims`]
1325 : []),
1326 ];
1327}
1328
1329/** Keep one PATH spelling in copied Windows environment records. */
1330export function setWindowsPath(env: NodeJS.ProcessEnv, value: string | null): void {
1331 for (const key of Object.keys(env)) {
1332 if (key.toUpperCase() === "PATH") {
1333 delete env[key];
1334 }
1335 }
1336 if (value !== null) env.PATH = value;
1337}
1338
1339function mergeWindowsEnv(
1340 currentEnv: NodeJS.ProcessEnv,
1341 patch: Partial<Record<string, string>>,
1342): NodeJS.ProcessEnv {
1343 const nextEnv: NodeJS.ProcessEnv = { ...currentEnv };
1344 for (const [key, value] of Object.entries(patch)) {
1345 if (value === undefined) continue;
1346 if (key === "PATH") {
1347 setWindowsPath(nextEnv, value);
1348 } else {
1349 nextEnv[key] = value;
1350 }
1351 }
1352 return nextEnv;
1353}
1354
1355export const resolveWindowsEnvironment = Effect.fn("shell.resolveWindowsEnvironment")(function* (
1356 env: NodeJS.ProcessEnv,
1357): Effect.fn.Return<Partial<NodeJS.ProcessEnv>, never, FileSystem.FileSystem | Path.Path> {
1358 const readEnvironment = yield* WindowsShellEnvironment;
1359 const commandAvailable = yield* CommandAvailability;
1360 const inheritedPath = readEnvPath(env);
1361 const shellPath = (yield* readEnvironment(["PATH"], { loadProfile: false })).PATH;
1362 const mergedPath = mergePathValues(shellPath, inheritedPath, "win32");
1363 const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);
1364 const baselinePath = mergePathValues(mergedPath, knownCliPath, "win32");
1365 const baselinePatch: Partial<NodeJS.ProcessEnv> = baselinePath ? { PATH: baselinePath } : {};
1366 const baselineEnv = mergeWindowsEnv(env, baselinePatch);
1367
1368 if (yield* commandAvailable("node", { env: baselineEnv })) {
1369 return baselinePatch;
1370 }
1371
1372 const profiledEnvironment = yield* readEnvironment(["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"], {
1373 loadProfile: true,
1374 });
1375 const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, "win32");
1376 const profiledPatch: Partial<NodeJS.ProcessEnv> = {
1377 ...(profiledPath ? { PATH: profiledPath } : {}),
1378 ...(profiledEnvironment.FNM_DIR ? { FNM_DIR: profiledEnvironment.FNM_DIR } : {}),
1379 ...(profiledEnvironment.FNM_MULTISHELL_PATH
1380 ? { FNM_MULTISHELL_PATH: profiledEnvironment.FNM_MULTISHELL_PATH }
1381 : {}),
1382 };
1383 return Object.keys(profiledPatch).length > 0
1384 ? { ...baselinePatch, ...profiledPatch }
1385 : baselinePatch;
1386});
1387
1388export function applyShellEnvironment(
1389 env: NodeJS.ProcessEnv,
1390 patch: ShellEnvironmentPatch,
1391 platform: NodeJS.Platform,
1392): void {
1393 for (const [key, value] of Object.entries(patch)) {
1394 if (key === "PATH" && platform === "win32") setWindowsPath(env, value);
1395 else if (value === null) delete env[key];
1396 else env[key] = value;
1397 }
1398}
1399
1400interface PathSetupInput {
1401 readonly directory: string;
1402 readonly home: string;
1403 readonly shell: string | undefined;
1404 readonly platform: NodeJS.Platform;
1405 /** `XDG_CONFIG_HOME`, where fish reads its startup file when set. */
1406 readonly configHome?: string | undefined;
1407 /** `ZDOTDIR`, where zsh reads `.zshrc` when set. */
1408 readonly zdotdir?: string | undefined;
1409}
1410
1411/**
1412 * The startup file (`~/...`, or absolute under `configHome`) and line that put `directory` last on
1413 * PATH for new zsh, bash, or fish terminals, so it never shadows another `t3`. Undefined on Windows (writing PATH there would flatten the registry's
1414 * `%VAR%` entries), for other shells, macOS bash, or unsafe paths.
1415 */
1416export function pathSetup(
1417 input: PathSetupInput,
1418): { readonly file: string; readonly line: string } | undefined {
1419 // A relative folder on PATH would follow the working directory into any checkout.
1420 if (input.platform === "win32" || !input.directory.startsWith("/")) return undefined;
1421 const underHome = input.directory.startsWith(`${input.home}/`);
1422 const rest = underHome ? input.directory.slice(input.home.length) : input.directory;
1423 if (!/^[\w./-]+$/.test(rest)) return undefined;
1424 const directory = underHome ? `$HOME${rest}` : rest;
1425 const shell = input.shell?.split("/").pop();
1426 // A set folder the shell reads from replaces the default; one unsafe to write means no setup,
1427 // since the default file would never be read.
1428 const readFrom = (value: string | undefined, fallback: string) =>
1429 !value ? fallback : value.startsWith("/") && /^[\w./-]+$/.test(value) ? value : undefined;
1430 if (shell === "fish") {
1431 const configHome = readFrom(input.configHome, "~/.config");
1432 if (configHome === undefined) return undefined;
1433 // --path changes $PATH itself; fish_user_paths would go ahead of the system folders.
1434 return {
1435 file: `${configHome}/fish/config.fish`,
1436 line: `fish_add_path --append --path ${directory}`,
1437 };
1438 }
1439 // macOS bash reads only the first of .bash_profile, .bash_login, and .profile; no file is safe.
1440 const zdotdir = readFrom(input.zdotdir, "~");
1441 const file =
1442 shell === "zsh"
1443 ? zdotdir && `${zdotdir}/.zshrc`
1444 : shell === "bash" && input.platform !== "darwin"
1445 ? "~/.bashrc"
1446 : undefined;
1447 return file === undefined ? undefined : { file, line: `export PATH="$PATH:${directory}"` };
1448}
1449
1450/** A command to paste that does what {@link pathSetup} describes. */
1451export function pathSetupCommand(input: PathSetupInput): string | undefined {
1452 const setup = pathSetup(input);
1453 if (!setup) return undefined;
1454 // The leading newline keeps the line out of a final comment with no newline after it.
1455 const append = `printf '\\n%s\\n' '${setup.line}' >> ${setup.file}`;
1456 // fish's config folder may not exist yet; `&&` works in fish 3 too.
1457 return setup.file.endsWith(".fish")
1458 ? `mkdir -p ${setup.file.slice(0, setup.file.lastIndexOf("/"))} && ${append}`
1459 : append;
1460}