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

shell.ts

1,006 lines33.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 Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12​
13import * as HostProcess from "./HostProcess.ts";
14import * as Context from "effect/Context";
15const SHELL_ENV_NAME_PATTERN = /^[A-Z0-9_]+$/;
16const WINDOWS_PATH_DELIMITER = ";";
17const POSIX_PATH_DELIMITER = ":";
18const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
19​
20type ExecFileSyncLike = (
21 file: string,
22 args: ReadonlyArray<string>,
23 options: {
24 encoding: "utf8";
25 timeout: number;
26 detached?: true;
27 stdio?: ["ignore", "pipe", "ignore"];
28 },
29) => string;
30​
31function canExecuteFile(filePath: string): boolean {
32 try {
33 NodeFS.accessSync(filePath, NodeFS.constants.X_OK);
34 return true;
35 } catch {
36 return false;
37 }
39​
40export interface CommandAvailabilityOptions {
41 readonly env?: NodeJS.ProcessEnv;
42 readonly extendEnv?: boolean;
44​
45export type CommandAvailabilityChecker = (
46 command: string,
47 options?: CommandAvailabilityOptions,
48) => Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path>;
49​
50const WINDOWS_SHELL_META_CHARS = /([()\][%!^"`<>&|;, *?])/g;
51​
52/**
53 * Node hands the command string to `cmd.exe /d /s /c "<command>"` without any
54 * quoting, so every dynamic argument must be escaped to survive both cmd.exe
55 * parsing and the target program's `CommandLineToArgvW` parsing.
56 */
57function escapeWindowsShellArg(arg: string): string {
58 let escaped = arg.replace(/(\\*)"/g, '$1$1\\"');
59 // Double up trailing backslashes so the closing quote is not escaped away.
60 escaped = escaped.replace(/(\\*)$/, "$1$1");
61 escaped = `"${escaped}"`;
62 return escaped.replace(WINDOWS_SHELL_META_CHARS, "^$1");
64​
65export interface ResolvedSpawnCommand {
66 readonly command: string;
67 readonly args: ReadonlyArray<string>;
68 readonly shell: boolean;
70​
71export type SpawnExecutableResolver = (
72 command: string,
73 platform: NodeJS.Platform,
74 env: NodeJS.ProcessEnv,
75) => string | undefined;
76​
77function resolveSpawnExecutableWithNode(
78 command: string,
79 platform: NodeJS.Platform,
80 env: NodeJS.ProcessEnv,
81): string | undefined {
82 const path = platform === "win32" ? NodePath.win32 : NodePath.posix;
83 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
84 const candidates = resolveCommandCandidates(
85 command,
86 platform,
87 windowsPathExtensions,
88 path.extname,
89 );
90 const isExecutable = (candidate: string) => {
91 try {
92 if (!NodeFS.statSync(candidate).isFile()) return false;
93 if (platform === "win32") {
94 return windowsPathExtensions.includes(path.extname(candidate).toUpperCase());
95 }
96 return canExecuteFile(candidate);
97 } catch {
98 return false;
99 }
100 };
101​
102 if (command.includes("/") || command.includes("\\")) {
103 return candidates.find(isExecutable);
104 }
105​
106 for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) {
107 const normalizedPathEntry = stripWrappingQuotes(pathEntry.trim());
108 if (normalizedPathEntry.length === 0) continue;
109 for (const candidate of candidates) {
110 const candidatePath = path.join(normalizedPathEntry, candidate);
111 if (isExecutable(candidatePath)) return candidatePath;
112 }
113 }
114 return undefined;
116​
117export const SpawnExecutableResolution = Context.Reference<SpawnExecutableResolver>(
118 "@t3tools/shared/shell/SpawnExecutableResolution",
119 {
120 defaultValue: () => resolveSpawnExecutableWithNode,
121 },
122);
123​
124export interface WindowsEnvironmentProbeOptions {
125 readonly loadProfile?: boolean;
127​
128function trimNonEmpty(value: string | null | undefined): string | undefined {
129 const trimmed = value?.trim();
130 return trimmed && trimmed.length > 0 ? trimmed : undefined;
132​
133function readUserLoginShell(): string | undefined {
134 try {
135 return trimNonEmpty(NodeOS.userInfo().shell);
136 } catch {
137 return undefined;
138 }
140​
141export function listLoginShellCandidates(
142 platform: NodeJS.Platform,
143 shell: string | undefined,
144 userShell = readUserLoginShell(),
145): ReadonlyArray<string> {
146 const fallbackShell =
147 platform === "darwin" ? "/bin/zsh" : platform === "linux" ? "/bin/bash" : undefined;
148 const seen = new Set<string>();
149 const candidates: string[] = [];
150​
151 for (const candidate of [trimNonEmpty(shell), trimNonEmpty(userShell), fallbackShell]) {
152 if (!candidate || seen.has(candidate)) {
153 continue;
154 }
155 seen.add(candidate);
156 candidates.push(candidate);
157 }
158​
159 return candidates;
161​
162export function readPathFromLaunchctl(
163 execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,
164): string | undefined {
165 try {
166 return trimNonEmpty(
167 execFile("/bin/launchctl", ["getenv", "PATH"], {
168 encoding: "utf8",
169 timeout: 2000,
170 }),
171 );
172 } catch {
173 return undefined;
174 }
176​
177export function mergePathEntries(
178 preferredPath: string | undefined,
179 inheritedPath: string | undefined,
180 platform: NodeJS.Platform,
181): string | undefined {
182 const delimiter = platform === "win32" ? ";" : ":";
183 const merged: string[] = [];
184 const seen = new Set<string>();
185​
186 for (const pathValue of [preferredPath, inheritedPath]) {
187 if (!pathValue) continue;
188 for (const entry of pathValue.split(delimiter)) {
189 const trimmedEntry = entry.trim();
190 if (!trimmedEntry || seen.has(trimmedEntry)) {
191 continue;
192 }
193 seen.add(trimmedEntry);
194 merged.push(trimmedEntry);
195 }
196 }
197​
198 return merged.length > 0 ? merged.join(delimiter) : undefined;
200​
201function envCaptureStart(name: string): string {
202 return `__T3CODE_ENV_${name}_START__`;
204​
205function envCaptureEnd(name: string): string {
206 return `__T3CODE_ENV_${name}_END__`;
208​
209export function buildEnvironmentCaptureCommand(
210 shell: string,
211 names: ReadonlyArray<string>,
212): string {
213 const executableName = NodePath.basename(shell).toLowerCase();
214 const isNushell = executableName.startsWith("nu");
215​
216 return names
217 .map((name) => {
218 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
219 throw new Error(`Unsupported environment variable name: ${name}`);
220 }
221​
222 if (isNushell) {
223 // Without a configured conversion, Nu expands home paths only in a list PATH.
224 const defaultValue =
225 name === "PATH"
226 ? "if ($env.PATH? | describe | str starts-with 'list') { " +
227 "$env.PATH | each {|p| if ($p | str starts-with '~') { " +
228 "$p | path expand --no-symlink } else { $p } } | str join (char esep) " +
229 "} else { $env.PATH? | default '' }"
230 : `$env.${name}? | default ''`;
231 const value =
232 `if $env.${name}? == null { '' } else if ` +
233 `$env.ENV_CONVERSIONS?.${name}?.to_string? != null { ` +
234 `$env.${name} | do $env.ENV_CONVERSIONS.${name}.to_string $env.${name} ` +
235 `} else { ${defaultValue} }`;
236 return [
237 `print '${envCaptureStart(name)}'`,
238 `print (${value})`,
239 `print '${envCaptureEnd(name)}'`,
240 ].join("; ");
241 }
242​
243 return [
244 `printf '%s\\n' '${envCaptureStart(name)}'`,
245 `printenv ${name} || true`,
246 `printf '%s\\n' '${envCaptureEnd(name)}'`,
247 ].join("; ");
248 })
249 .join("; ");
251​
252function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
253 return [
254 "$ErrorActionPreference = 'Stop'",
255 ...names.flatMap((name) => {
256 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
257 throw new Error(`Unsupported environment variable name: ${name}`);
258 }
259​
260 return [
261 `Write-Output '${envCaptureStart(name)}'`,
262 `$value = [Environment]::GetEnvironmentVariable('${name}')`,
263 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
264 `Write-Output '${envCaptureEnd(name)}'`,
265 ];
266 }),
267 ].join("; ");
269​
270function extractEnvironmentValue(output: string, name: string): string | undefined {
271 const startMarker = envCaptureStart(name);
272 const endMarker = envCaptureEnd(name);
273 const startIndex = output.indexOf(startMarker);
274 if (startIndex === -1) return undefined;
275​
276 const valueStartIndex = startIndex + startMarker.length;
277 const endIndex = output.indexOf(endMarker, valueStartIndex);
278 if (endIndex === -1) return undefined;
279​
280 const value = output
281 .slice(valueStartIndex, endIndex)
282 .replace(/^\r?\n/, "")
283 .replace(/\r?\n$/, "");
284​
285 return value.length > 0 ? value : undefined;
287​
288export type ShellEnvironmentReader = (
289 shell: string,
290 names: ReadonlyArray<string>,
291 execFile?: ExecFileSyncLike,
292) => Partial<Record<string, string>>;
293​
294export const readEnvironmentFromLoginShell: ShellEnvironmentReader = (
295 shell,
296 names,
297 execFile = NodeChildProcess.execFileSync,
298) => {
299 if (names.length === 0) {
300 return {};
301 }
302​
303 // Interactive startup loads PATH entries; detaching prevents job control on an
304 // inherited controlling TTY from stopping the probe while the parent waits.
305 const output = execFile(shell, ["-ilc", buildEnvironmentCaptureCommand(shell, names)], {
306 encoding: "utf8",
307 timeout: 5000,
308 detached: true,
309 stdio: ["ignore", "pipe", "ignore"],
310 });
311​
312 const environment: Partial<Record<string, string>> = {};
313 for (const name of names) {
314 const value = extractEnvironmentValue(output, name);
315 if (value !== undefined) {
316 environment[name] = value;
317 }
318 }
319​
320 return environment;
321};
322​
323export type WindowsShellEnvironmentReader = (
324 names: ReadonlyArray<string>,
325 options?: WindowsEnvironmentProbeOptions,
326) => Partial<Record<string, string>>;
327​
328export const WindowsShellEnvironment = Context.Reference<WindowsShellEnvironmentReader>(
329 "@t3tools/shared/shell/WindowsShellEnvironment",
330 {
331 defaultValue: () => readEnvironmentFromWindowsShell,
332 },
333);
334​
335export const CommandAvailability = Context.Reference<CommandAvailabilityChecker>(
336 "@t3tools/shared/shell/CommandAvailability",
337 {
338 defaultValue: () => isCommandAvailable,
339 },
340);
341​
342export function readEnvironmentFromWindowsShell(
343 names: ReadonlyArray<string>,
344 execFile?: ExecFileSyncLike,
345): Partial<Record<string, string>>;
346export function readEnvironmentFromWindowsShell(
347 names: ReadonlyArray<string>,
348 options?: WindowsEnvironmentProbeOptions,
349 execFile?: ExecFileSyncLike,
350): Partial<Record<string, string>>;
351export function readEnvironmentFromWindowsShell(
352 names: ReadonlyArray<string>,
353 optionsOrExecFile?: WindowsEnvironmentProbeOptions | ExecFileSyncLike,
354 maybeExecFile?: ExecFileSyncLike,
355): Partial<Record<string, string>> {
356 if (names.length === 0) {
357 return {};
358 }
359​
360 const options =
361 typeof optionsOrExecFile === "function"
362 ? ({} satisfies WindowsEnvironmentProbeOptions)
363 : (optionsOrExecFile ?? {});
364 const execFile: ExecFileSyncLike =
365 typeof optionsOrExecFile === "function"
366 ? optionsOrExecFile
367 : (maybeExecFile ?? (NodeChildProcess.execFileSync as ExecFileSyncLike));
368 const command = buildWindowsEnvironmentCaptureCommand(names);
369 const args = [
370 "-NoLogo",
371 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
372 "-NonInteractive",
373 "-Command",
374 command,
375 ];
376 for (const shell of WINDOWS_SHELL_CANDIDATES) {
377 try {
378 const output = execFile(shell, args, { encoding: "utf8", timeout: 5000 });
379​
380 const environment: Partial<Record<string, string>> = {};
381 for (const name of names) {
382 const value = extractEnvironmentValue(output, name);
383 if (value !== undefined) {
384 environment[name] = value;
385 }
386 }
387 return environment;
388 } catch {
389 continue;
390 }
391 }
392​
393 return {};
395​
396function stripWrappingQuotes(value: string): string {
397 return value.replace(/^"+|"+$/g, "");
399​
400function pathDelimiterForPlatform(platform: NodeJS.Platform): string {
401 return platform === "win32" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER;
403​
404function normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string {
405 const normalized = stripWrappingQuotes(entry.trim());
406 return platform === "win32" ? normalized.toLowerCase() : normalized;
408​
409function sanitizePathEntry(entry: string, platform: NodeJS.Platform): string {
410 return platform === "win32" ? entry.replaceAll('"', "") : entry;
412​
413export function mergePathValues(
414 preferredPath: string | undefined,
415 inheritedPath: string | undefined,
416 platform: NodeJS.Platform,
417): string | undefined {
418 const delimiter = pathDelimiterForPlatform(platform);
419 const merged: string[] = [];
420 const seen = new Set<string>();
421​
422 for (const rawValue of [preferredPath, inheritedPath]) {
423 if (!rawValue) continue;
424​
425 for (const entry of rawValue.split(delimiter)) {
426 const sanitized = sanitizePathEntry(entry.trim(), platform);
427 if (sanitized.length === 0) continue;
428​
429 const normalized = normalizePathEntryForComparison(sanitized, platform);
430 if (normalized.length === 0 || seen.has(normalized)) continue;
431​
432 seen.add(normalized);
433 merged.push(sanitized);
434 }
435 }
436​
437 return merged.length > 0 ? merged.join(delimiter) : undefined;
439​
440function readEnvPath(env: NodeJS.ProcessEnv): string | undefined {
441 return env.PATH ?? env.Path ?? env.path;
443​
444function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
445 return readEnvPath(env) ?? "";
447​
448function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
449 const rawValue = env.PATHEXT;
450 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
451 if (!rawValue) return fallback;
452​
453 const parsed: string[] = [];
454 for (const entry of rawValue.split(";")) {
455 const trimmed = entry.trim();
456 if (trimmed.length === 0) continue;
457 parsed.push(trimmed.startsWith(".") ? trimmed.toUpperCase() : `.${trimmed.toUpperCase()}`);
458 }
459 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
461​
462function resolveCommandCandidates(
463 command: string,
464 platform: NodeJS.Platform,
465 windowsPathExtensions: ReadonlyArray<string>,
466 extname: (path: string) => string,
467): ReadonlyArray<string> {
468 if (platform !== "win32") return [command];
469 const extension = extname(command);
470 const normalizedExtension = extension.toUpperCase();
471​
472 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
473 const commandWithoutExtension = command.slice(0, -extension.length);
474 return Array.from(
475 new Set([
476 command,
477 `${commandWithoutExtension}${normalizedExtension}`,
478 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
479 ]),
480 );
481 }
482​
483 const candidates: string[] = [];
484 for (const candidateExtension of windowsPathExtensions) {
485 candidates.push(`${command}${candidateExtension}`);
486 candidates.push(`${command}${candidateExtension.toLowerCase()}`);
487 }
488 return Array.from(new Set(candidates));
490​
491// Explicit-path resolution is never cached - callers probe paths they have
492// just written (e.g. managed binary installs). A "not-found" outcome is also
493// cached for the TTL, so a just-installed binary can stay invisible for up to
494// 30s unless resolved by explicit path.
495const COMMAND_RESOLUTION_CACHE_TTL_NANOS = 30_000_000_000n;
496const COMMAND_RESOLUTION_CACHE_MAX_ENTRIES = 512;
497const COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR = String.fromCharCode(0);
498​
499interface CommandResolutionCacheEntry {
500 readonly resolvedPath: string | null;
501 readonly expiresAtNanos: bigint;
503​
504export const CommandResolutionCache = Context.Reference<Map<string, CommandResolutionCacheEntry>>(
505 "@t3tools/shared/shell/CommandResolutionCache",
506 {
507 defaultValue: () => new Map(),
508 },
509);
510​
511interface PathDirectoryListing {
512 readonly modified: number | null | undefined;
513 readonly names: ReadonlySet<string> | undefined;
515​
516const directoryMtime = (directory: string) =>
517 FileSystem.FileSystem.use((fileSystem) => fileSystem.stat(directory)).pipe(
518 Effect.map((info) =>
519 info.type === "Directory" ? Option.getOrUndefined(info.mtime)?.getTime() : undefined,
520 ),
521 Effect.catch((error) => Effect.succeed(error.reason._tag === "NotFound" ? null : undefined)),
522 );
523​
524// Dated before it is read, so an entry added in between changes the mtime seen
525// on the next check. Without names, lookups probe candidates directly.
526const listPathDirectory = Effect.fnUntraced(function* (
527 directory: string,
528): Effect.fn.Return<PathDirectoryListing, never, FileSystem.FileSystem> {
529 const modified = yield* directoryMtime(directory);
530 if (modified == null) return { modified, names: modified === null ? new Set() : undefined };
531 const entries = yield* FileSystem.FileSystem.use((fileSystem) =>
532 fileSystem.readDirectory(directory),
533 ).pipe(Effect.orElseSucceed(() => undefined));
534 return { modified, names: entries && new Set(entries.map((entry) => entry.toLowerCase())) };
535});
536​
537const PathDirectoryListings = Context.Reference<
538 Cache.Cache<string, PathDirectoryListing, never, FileSystem.FileSystem> | undefined
539>("@t3tools/shared/shell/PathDirectoryListings", { defaultValue: () => undefined });
540​
541export const withPathDirectoryListings =
542 /* Directory reads are cached inside one shell operation; a span for each lookup adds noise. */
543 Effect.fnUntraced(function* <A, E, R>(effect: Effect.Effect<A, E, R>) {
544 const listings = yield* Cache.make({
545 capacity: 1024,
546 lookup: listPathDirectory,
547 requireServicesAt: "lookup",
548 });
549 return yield* effect.pipe(Effect.provideService(PathDirectoryListings, listings));
550 });
551​
552// An injected resolver or locator may answer differently for the same search, so its
553// entries are kept apart from every other resolver's.
554let spawnResolverCacheIdCount = 0;
555const spawnResolverCacheIds = new WeakMap<SpawnExecutableResolver | XcodeGitLocator, number>();
556function spawnResolverCacheId(resolver: SpawnExecutableResolver | XcodeGitLocator): number {
557 const known = spawnResolverCacheIds.get(resolver);
558 if (known !== undefined) return known;
559 const id = spawnResolverCacheIdCount++;
560 spawnResolverCacheIds.set(resolver, id);
561 return id;
563​
564function cacheCommandResolution(
565 cache: Map<string, CommandResolutionCacheEntry>,
566 cacheKey: string,
567 resolvedPath: string | null,
568 nowNanos: bigint,
569): void {
570 if (cache.size >= COMMAND_RESOLUTION_CACHE_MAX_ENTRIES) {
571 const oldestKey = cache.keys().next().value;
572 if (oldestKey !== undefined) {
573 cache.delete(oldestKey);
574 }
575 }
576 cache.set(cacheKey, {
577 resolvedPath,
578 expiresAtNanos: nowNanos + COMMAND_RESOLUTION_CACHE_TTL_NANOS,
579 });
581​
582const isExecutableFile = Effect.fnUntraced(function* (
583 filePath: string,
584 platform: NodeJS.Platform,
585 windowsPathExtensions: ReadonlyArray<string>,
586): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
587 const fileSystem = yield* FileSystem.FileSystem;
588 const path = yield* Path.Path;
589 const stat = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
590 if (stat === null || stat.type !== "File") return false;
591​
592 if (platform === "win32") {
593 const extension = path.extname(filePath);
594 if (extension.length === 0) return false;
595 return windowsPathExtensions.includes(extension.toUpperCase());
596 }
597​
598 return canExecuteFile(filePath);
599});
600​
601const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlatform")(function* (
602 command: string,
603 options: CommandAvailabilityOptions & { readonly platform: NodeJS.Platform },
604): Effect.fn.Return<string | null, never, FileSystem.FileSystem | Path.Path> {
605 const path = yield* Path.Path;
606 const platform = options.platform;
607 const env = options.env ?? process.env;
608 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
609 const commandCandidates = resolveCommandCandidates(
610 command,
611 platform,
612 windowsPathExtensions,
613 path.extname,
614 );
615​
616 if (command.includes("/") || command.includes("\\")) {
617 for (const candidate of commandCandidates) {
618 if (yield* isExecutableFile(candidate, platform, windowsPathExtensions)) {
619 return candidate;
620 }
621 }
622 return null;
623 }
624​
625 const pathValue = resolvePathEnvironmentVariable(env);
626 if (pathValue.length === 0) {
627 return null;
628 }
629​
630 const cacheKey = [platform, pathValue, windowsPathExtensions.join(";"), command].join(
631 COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR,
632 );
633 const cache = yield* CommandResolutionCache;
634 const nowNanos = yield* Clock.monotonicTimeNanos;
635 const cached = cache.get(cacheKey);
636 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
637 return cached.resolvedPath;
638 }
639​
640 // Keep case variants: Windows can make PATH directories case-sensitive.
641 const pathEntries: string[] = [];
642 const seenPathEntries = new Set<string>();
643 for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) {
644 const pathEntry = stripWrappingQuotes(entry.trim());
645 if (pathEntry.length === 0 || seenPathEntries.has(pathEntry)) continue;
646​
647 seenPathEntries.add(pathEntry);
648 pathEntries.push(pathEntry);
649 }
650​
651 const listings = yield* PathDirectoryListings;
652 for (const pathEntry of pathEntries) {
653 let listing = listings && (yield* Cache.get(listings, pathEntry));
654 if (listings && listing?.names && listing.modified !== (yield* directoryMtime(pathEntry))) {
655 yield* Cache.invalidate(listings, pathEntry);
656 listing = yield* Cache.get(listings, pathEntry);
657 }
658 for (const candidate of commandCandidates) {
659 if (listing?.names && !listing.names.has(candidate.toLowerCase())) continue;
660 const candidatePath = path.join(pathEntry, candidate);
661 if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) {
662 cacheCommandResolution(cache, cacheKey, candidatePath, nowNanos);
663 return candidatePath;
664 }
665 }
666 }
667 cacheCommandResolution(cache, cacheKey, null, nowNanos);
668 return null;
669});
670​
671export const resolveCommandPath = Effect.fn("shell.resolveCommandPath")(function* (
672 command: string,
673 options: CommandAvailabilityOptions = {},
674) {
675 return yield* resolveCommandPathForPlatform(command, {
676 env: options.env ?? (yield* HostProcess.Environment),
677 platform: yield* HostProcess.Platform,
678 });
679});
680​
681// Git for Windows 2.56 moved x64 builds from mingw64 to ucrt64; ARM64 builds
682// live in clangarm64 and 32-bit ones in mingw32.
683const GIT_FOR_WINDOWS_BUILDS = ["ucrt64", "clangarm64", "mingw64", "mingw32"] as const;
684​
685function isFileSync(filePath: string): boolean {
686 try {
687 return NodeFS.statSync(filePath).isFile();
688 } catch {
689 return false;
690 }
692​
693/**
694 * The launcher costs a second process on every git command, and each launch
695 * leaks a kernel token reference that slows process creation machine-wide until
696 * reboot. The real binary sets HOME itself, but adds its own folders to PATH
697 * for hooks, ssh and credential helpers only when MSYSTEM is unset, so the
698 * launcher stays when MSYSTEM is set.
699 */
700export function preferGitForWindowsBinary(
701 executable: string,
702 env: NodeJS.ProcessEnv,
703 isFile: (filePath: string) => boolean = isFileSync,
704): string {
705 if (env.MSYSTEM) return executable;
706 const path = NodePath.win32;
707 if (path.basename(executable).toLowerCase() !== "git.exe") return executable;
708 const launcherDirectory = path.dirname(executable);
709 const launcherFolder = path.basename(launcherDirectory).toLowerCase();
710 if (launcherFolder !== "cmd" && launcherFolder !== "bin") return executable;
711 const installRoot = path.dirname(launcherDirectory);
712 for (const build of GIT_FOR_WINDOWS_BUILDS) {
713 const candidate = path.join(installRoot, build, "bin", "git.exe");
714 if (isFile(candidate)) return candidate;
715 }
716 return executable;
718​
719// What npm's cmd-shim writes for a package whose bin is a native executable.
720const NPM_EXECUTABLE_SHIM_PREFIX = [
721 "@ECHO off",
722 "GOTO start",
723 ":find_dp0",
724 "SET dp0=%~dp0",
725 "EXIT /b",
726 ":start",
727 "SETLOCAL",
728 "CALL :find_dp0",
729];
730const NPM_EXECUTABLE_SHIM_RUN = /^"%dp0%\\([^"%]+\.exe)" +%\*$/;
731​
732function readFileSyncOrUndefined(filePath: string): string | undefined {
733 try {
734 return NodeFS.readFileSync(filePath, "utf8");
735 } catch {
736 return undefined;
737 }
739​
740/**
741 * The executable an npm cmd-shim runs, when the shim does nothing else.
742 * Started through the shim, the executable is a child of `cmd.exe` and so
743 * escapes the kill-on-close job libuv puts every child in: it keeps running
744 * after this process is killed. Started directly it is in the job.
745 */
746export function npmShimExecutable(
747 shimPath: string,
748 readFile: (filePath: string) => string | undefined = readFileSyncOrUndefined,
749 isFile: (filePath: string) => boolean = isFileSync,
750): string | undefined {
751 const path = NodePath.win32;
752 if (path.extname(shimPath).toLowerCase() !== ".cmd") return undefined;
753 // Compared exactly: whitespace CMD keeps, such as after `SET dp0=`, would
754 // make it run a different file than the one found here.
755 const lines = readFile(shimPath)
756 ?.split(/\r?\n/)
757 .filter((line) => line.length > 0);
758 if (lines?.length !== NPM_EXECUTABLE_SHIM_PREFIX.length + 1) return undefined;
759 if (NPM_EXECUTABLE_SHIM_PREFIX.some((expected, index) => lines[index] !== expected)) {
760 return undefined;
761 }
762 const target = NPM_EXECUTABLE_SHIM_RUN.exec(lines.at(-1)!)?.[1];
763 if (target === undefined) return undefined;
764 const executable = path.join(path.dirname(shimPath), target);
765 return isFile(executable) ? executable : undefined;
767​
768export type XcodeGitLocator = (env: NodeJS.ProcessEnv) => string | undefined;
769​
770// xcrun honors DEVELOPER_DIR and the `xcode-select` choice, as the shim does.
771function locateXcodeGitWithXcrun(env: NodeJS.ProcessEnv): string | undefined {
772 try {
773 const located = NodeChildProcess.execFileSync("/usr/bin/xcrun", ["--find", "git"], {
774 encoding: "utf8",
775 env,
776 timeout: 5_000,
777 stdio: ["ignore", "pipe", "ignore"],
778 }).trim();
779 return NodePath.isAbsolute(located) ? located : undefined;
780 } catch {
781 return undefined;
782 }
784​
785export const XcodeGitLocation = Context.Reference<XcodeGitLocator>(
786 "@t3tools/shared/shell/XcodeGitLocation",
787 { defaultValue: () => locateXcodeGitWithXcrun },
788);
789​
790const MACOS_GIT_SHIM = "/usr/bin/git";
791​
792/**
793 * /usr/bin/git is an xcrun shim that finds the active developer directory on
794 * every run: about 8 ms per spawn, against under 3 ms for the git behind it.
795 * Only the shim is replaced, so a git the user put first on PATH (Homebrew,
796 * Nix) still wins, and git's own children keep the same PATH. Any lookup
797 * failure keeps plain `git`.
798 */
799const resolveMacosGit = Effect.fnUntraced(function* (
800 env: NodeJS.ProcessEnv,
801 resolveExecutable: SpawnExecutableResolver,
802) {
803 const locateXcodeGit = yield* XcodeGitLocation;
804 const cache = yield* CommandResolutionCache;
805 const cacheKey = [
806 "xcode-git",
807 String(spawnResolverCacheId(resolveExecutable)),
808 String(spawnResolverCacheId(locateXcodeGit)),
809 resolvePathEnvironmentVariable(env),
810 env.DEVELOPER_DIR ?? "",
811 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
812 const nowNanos = yield* Clock.currentTimeNanos;
813 const cached = cache.get(cacheKey);
814 // An Xcode update or removal deletes the binary; look again instead of failing the spawn.
815 if (
816 cached !== undefined &&
817 cached.expiresAtNanos > nowNanos &&
818 (cached.resolvedPath === null ||
819 resolveExecutable(cached.resolvedPath, "darwin", env) !== undefined)
820 ) {
821 return cached.resolvedPath ?? "git";
822 }
823 const located =
824 resolveExecutable("git", "darwin", env) === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined;
825 const realGit =
826 located !== undefined && resolveExecutable(located, "darwin", env) !== undefined
827 ? located
828 : null;
829 cacheCommandResolution(cache, cacheKey, realGit, nowNanos);
830 return realGit ?? "git";
831});
832​
833export interface SpawnCommandOptions extends CommandAvailabilityOptions {
834 /** Run the executable behind an npm cmd-shim directly (see `npmShimExecutable`). */
835 readonly bypassNpmShim?: boolean;
837​
838export const resolveSpawnCommand = Effect.fnUntraced(function* (
839 command: string,
840 args: ReadonlyArray<string>,
841 options: SpawnCommandOptions = {},
842): Effect.fn.Return<ResolvedSpawnCommand> {
843 const platform = yield* HostProcess.Platform;
844 const isMacosGit = platform === "darwin" && command === "git";
845 if (platform !== "win32" && !isMacosGit) {
846 return { command, args: [...args], shell: false };
847 }
848​
849 const hostEnvironment = yield* HostProcess.Environment;
850 const env =
851 options.env === undefined
852 ? hostEnvironment
853 : options.extendEnv
854 ? { ...hostEnvironment, ...options.env }
855 : options.env;
856 const resolveExecutable = yield* SpawnExecutableResolution;
857 if (isMacosGit) {
858 return {
859 command: yield* resolveMacosGit(env, resolveExecutable),
860 args: [...args],
861 shell: false,
862 };
863 }
864 // The scan is synchronous and runs before every child process, so it shares
865 // the PATH scan cache above. Explicit paths stay uncached for the same reason,
866 // and so do misses: a failed spawn is how providers report "not installed",
867 // and that has to clear the moment the binary appears.
868 const explicitPath = command.includes("/") || command.includes("\\");
869 const cache = yield* CommandResolutionCache;
870 const cacheKey = [
871 "spawn",
872 String(spawnResolverCacheId(resolveExecutable)),
873 platform,
874 resolvePathEnvironmentVariable(env),
875 resolveWindowsPathExtensions(env).join(";"),
876 env.MSYSTEM ? "msystem" : "",
877 command,
878 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
879 const nowNanos = yield* Clock.currentTimeNanos;
880 const cached = explicitPath ? undefined : cache.get(cacheKey);
881 let resolvedExecutable: string | null;
882 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
883 resolvedExecutable = cached.resolvedPath;
884 } else {
885 const found = resolveExecutable(command, platform, env);
886 resolvedExecutable = found === undefined ? null : preferGitForWindowsBinary(found, env);
887 if (!explicitPath && resolvedExecutable !== null) {
888 cacheCommandResolution(cache, cacheKey, resolvedExecutable, nowNanos);
889 }
890 }
891 const resolvedCommand = resolvedExecutable ?? command;
892 const extension = NodePath.win32.extname(resolvedCommand).toLowerCase();
893 if (extension !== ".cmd" && extension !== ".bat") {
894 return { command: resolvedCommand, args: [...args], shell: false };
895 }
896 const shimExecutable = options.bypassNpmShim ? npmShimExecutable(resolvedCommand) : undefined;
897 if (shimExecutable !== undefined) {
898 return { command: shimExecutable, args: [...args], shell: false };
899 }
900​
901 // Node runs a shell spawn as `cmd.exe /d /s /c "<command> <args...>"`, but
902 // passing args with `shell: true` prints DEP0190. Build the same escaped line
903 // here and pass no args.
904 return {
905 command: [resolvedCommand, ...args].map(escapeWindowsShellArg).join(" "),
906 args: [],
907 shell: true,
908 };
909});
910​
911export const isCommandAvailable = Effect.fn("shell.isCommandAvailable")(function* (
912 command: string,
913 options: CommandAvailabilityOptions = {},
914) {
915 return (yield* resolveCommandPath(command, options)) !== null;
916});
917​
918function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
919 const appData = env.APPDATA?.trim();
920 const localAppData = env.LOCALAPPDATA?.trim();
921 const userProfile = env.USERPROFILE?.trim();
922​
923 return [
924 ...(appData ? [`${appData}\\npm`] : []),
925 ...(localAppData ? [`${localAppData}\\Programs\\nodejs`, `${localAppData}\\Volta\\bin`] : []),
926 ...(localAppData ? [`${localAppData}\\pnpm`] : []),
927 ...(userProfile
928 ? [`${userProfile}\\.local\\bin`, `${userProfile}\\.bun\\bin`, `${userProfile}\\scoop\\shims`]
929 : []),
930 ];
932​
933function readWindowsEnvironmentSafely(
934 readEnvironment: WindowsShellEnvironmentReader,
935 names: ReadonlyArray<string>,
936 options?: WindowsEnvironmentProbeOptions,
937): Partial<Record<string, string>> {
938 try {
939 return readEnvironment(names, options);
940 } catch {
941 return {};
942 }
944​
945/** Keep one PATH spelling in copied Windows environment records. */
946export function setWindowsPath(env: NodeJS.ProcessEnv, value: string): void {
947 for (const key of Object.keys(env)) {
948 if (key.toUpperCase() === "PATH") {
949 delete env[key];
950 }
951 }
952 env.PATH = value;
954​
955function mergeWindowsEnv(
956 currentEnv: NodeJS.ProcessEnv,
957 patch: Partial<Record<string, string>>,
958): NodeJS.ProcessEnv {
959 const nextEnv: NodeJS.ProcessEnv = { ...currentEnv };
960 for (const [key, value] of Object.entries(patch)) {
961 if (value === undefined) continue;
962 if (key === "PATH") {
963 setWindowsPath(nextEnv, value);
964 } else {
965 nextEnv[key] = value;
966 }
967 }
968 return nextEnv;
970​
971export const resolveWindowsEnvironment = Effect.fn("shell.resolveWindowsEnvironment")(function* (
972 env: NodeJS.ProcessEnv,
973): Effect.fn.Return<Partial<NodeJS.ProcessEnv>, never, FileSystem.FileSystem | Path.Path> {
974 const readEnvironment = yield* WindowsShellEnvironment;
975 const commandAvailable = yield* CommandAvailability;
976 const inheritedPath = readEnvPath(env);
977 const shellPath = readWindowsEnvironmentSafely(readEnvironment, ["PATH"], {
978 loadProfile: false,
979 }).PATH;
980 const mergedPath = mergePathValues(shellPath, inheritedPath, "win32");
981 const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);
982 const baselinePath = mergePathValues(mergedPath, knownCliPath, "win32");
983 const baselinePatch: Partial<NodeJS.ProcessEnv> = baselinePath ? { PATH: baselinePath } : {};
984 const baselineEnv = mergeWindowsEnv(env, baselinePatch);
985​
986 if (yield* commandAvailable("node", { env: baselineEnv })) {
987 return baselinePatch;
988 }
989​
990 const profiledEnvironment = readWindowsEnvironmentSafely(
991 readEnvironment,
992 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
993 { loadProfile: true },
994 );
995 const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, "win32");
996 const profiledPatch: Partial<NodeJS.ProcessEnv> = {
997 ...(profiledPath ? { PATH: profiledPath } : {}),
998 ...(profiledEnvironment.FNM_DIR ? { FNM_DIR: profiledEnvironment.FNM_DIR } : {}),
999 ...(profiledEnvironment.FNM_MULTISHELL_PATH
1000 ? { FNM_MULTISHELL_PATH: profiledEnvironment.FNM_MULTISHELL_PATH }
1001 : {}),
1002 };
1003 return Object.keys(profiledPatch).length > 0
1004 ? { ...baselinePatch, ...profiledPatch }
1005 : baselinePatch;
1006});