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

shell.ts

1,411 lines50.9 KB

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