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

shell.ts

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