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

shell.ts

993 lines33.4 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) => Effect.Effect<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​
342const execWindowsEnvironmentProbe = (
343 file: string,
344 args: ReadonlyArray<string>,
345 options: { encoding: "utf8"; timeout: number },
346) =>
347 Effect.callback<Option.Option<string>>((resume) => {
348 let child: NodeChildProcess.ChildProcess;
349 try {
350 child = NodeChildProcess.execFile(
351 file,
352 args,
353 { ...options, windowsHide: true },
354 (error, stdout) => {
355 resume(Effect.succeed(error ? Option.none() : Option.some(stdout)));
356 },
357 );
358 } catch {
359 resume(Effect.succeedNone);
360 return;
361 }
362 return Effect.sync(() => {
363 child.kill();
364 });
365 });
366​
367export const readEnvironmentFromWindowsShell = Effect.fn("shell.readEnvironmentFromWindowsShell")(
368 function* (
369 names: ReadonlyArray<string>,
370 options: WindowsEnvironmentProbeOptions = {},
371 execFile: typeof execWindowsEnvironmentProbe = execWindowsEnvironmentProbe,
372 ) {
373 if (names.length === 0) return {};
374​
375 const command = buildWindowsEnvironmentCaptureCommand(names);
376 const args = [
377 "-NoLogo",
378 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
379 "-NonInteractive",
380 "-Command",
381 command,
382 ];
383 for (const shell of WINDOWS_SHELL_CANDIDATES) {
384 const output = yield* execFile(shell, args, { encoding: "utf8", timeout: 5000 });
385 if (Option.isNone(output)) continue;
386​
387 const environment: Partial<Record<string, string>> = {};
388 for (const name of names) {
389 const value = extractEnvironmentValue(output.value, name);
390 if (value !== undefined) environment[name] = value;
391 }
392 return environment;
393 }
394​
395 return {};
396 },
397);
398​
399function stripWrappingQuotes(value: string): string {
400 return value.replace(/^"+|"+$/g, "");
402​
403function pathDelimiterForPlatform(platform: NodeJS.Platform): string {
404 return platform === "win32" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER;
406​
407function normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string {
408 const normalized = stripWrappingQuotes(entry.trim());
409 return platform === "win32" ? normalized.toLowerCase() : normalized;
411​
412function sanitizePathEntry(entry: string, platform: NodeJS.Platform): string {
413 return platform === "win32" ? entry.replaceAll('"', "") : entry;
415​
416export function mergePathValues(
417 preferredPath: string | undefined,
418 inheritedPath: string | undefined,
419 platform: NodeJS.Platform,
420): string | undefined {
421 const delimiter = pathDelimiterForPlatform(platform);
422 const merged: string[] = [];
423 const seen = new Set<string>();
424​
425 for (const rawValue of [preferredPath, inheritedPath]) {
426 if (!rawValue) continue;
427​
428 for (const entry of rawValue.split(delimiter)) {
429 const sanitized = sanitizePathEntry(entry.trim(), platform);
430 if (sanitized.length === 0) continue;
431​
432 const normalized = normalizePathEntryForComparison(sanitized, platform);
433 if (normalized.length === 0 || seen.has(normalized)) continue;
434​
435 seen.add(normalized);
436 merged.push(sanitized);
437 }
438 }
439​
440 return merged.length > 0 ? merged.join(delimiter) : undefined;
442​
443function readEnvPath(env: NodeJS.ProcessEnv): string | undefined {
444 return env.PATH ?? env.Path ?? env.path;
446​
447function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
448 return readEnvPath(env) ?? "";
450​
451function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
452 const rawValue = env.PATHEXT;
453 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
454 if (!rawValue) return fallback;
455​
456 const parsed: string[] = [];
457 for (const entry of rawValue.split(";")) {
458 const trimmed = entry.trim();
459 if (trimmed.length === 0) continue;
460 parsed.push(trimmed.startsWith(".") ? trimmed.toUpperCase() : `.${trimmed.toUpperCase()}`);
461 }
462 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
464​
465function resolveCommandCandidates(
466 command: string,
467 platform: NodeJS.Platform,
468 windowsPathExtensions: ReadonlyArray<string>,
469 extname: (path: string) => string,
470): ReadonlyArray<string> {
471 if (platform !== "win32") return [command];
472 const extension = extname(command);
473 const normalizedExtension = extension.toUpperCase();
474​
475 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
476 const commandWithoutExtension = command.slice(0, -extension.length);
477 return Array.from(
478 new Set([
479 command,
480 `${commandWithoutExtension}${normalizedExtension}`,
481 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
482 ]),
483 );
484 }
485​
486 const candidates: string[] = [];
487 for (const candidateExtension of windowsPathExtensions) {
488 candidates.push(`${command}${candidateExtension}`);
489 candidates.push(`${command}${candidateExtension.toLowerCase()}`);
490 }
491 return Array.from(new Set(candidates));
493​
494// Explicit-path resolution is never cached - callers probe paths they have
495// just written (e.g. managed binary installs). A "not-found" outcome is also
496// cached for the TTL, so a just-installed binary can stay invisible for up to
497// 30s unless resolved by explicit path.
498const COMMAND_RESOLUTION_CACHE_TTL_NANOS = 30_000_000_000n;
499const COMMAND_RESOLUTION_CACHE_MAX_ENTRIES = 512;
500const COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR = String.fromCharCode(0);
501​
502interface CommandResolutionCacheEntry {
503 readonly resolvedPath: string | null;
504 readonly expiresAtNanos: bigint;
506​
507export const CommandResolutionCache = Context.Reference<Map<string, CommandResolutionCacheEntry>>(
508 "@t3tools/shared/shell/CommandResolutionCache",
509 {
510 defaultValue: () => new Map(),
511 },
512);
513​
514interface PathDirectoryListing {
515 readonly modified: number | null | undefined;
516 readonly names: ReadonlySet<string> | undefined;
518​
519const directoryMtime = (directory: string) =>
520 FileSystem.FileSystem.use((fileSystem) => fileSystem.stat(directory)).pipe(
521 Effect.map((info) =>
522 info.type === "Directory" ? Option.getOrUndefined(info.mtime)?.getTime() : undefined,
523 ),
524 Effect.catch((error) => Effect.succeed(error.reason._tag === "NotFound" ? null : undefined)),
525 );
526​
527// Dated before it is read, so an entry added in between changes the mtime seen
528// on the next check. Without names, lookups probe candidates directly.
529const listPathDirectory = Effect.fnUntraced(function* (
530 directory: string,
531): Effect.fn.Return<PathDirectoryListing, never, FileSystem.FileSystem> {
532 const modified = yield* directoryMtime(directory);
533 if (modified == null) return { modified, names: modified === null ? new Set() : undefined };
534 const entries = yield* FileSystem.FileSystem.use((fileSystem) =>
535 fileSystem.readDirectory(directory),
536 ).pipe(Effect.orElseSucceed(() => undefined));
537 return { modified, names: entries && new Set(entries.map((entry) => entry.toLowerCase())) };
538});
539​
540const PathDirectoryListings = Context.Reference<
541 Cache.Cache<string, PathDirectoryListing, never, FileSystem.FileSystem> | undefined
542>("@t3tools/shared/shell/PathDirectoryListings", { defaultValue: () => undefined });
543​
544export const withPathDirectoryListings =
545 /* Directory reads are cached inside one shell operation; a span for each lookup adds noise. */
546 Effect.fnUntraced(function* <A, E, R>(effect: Effect.Effect<A, E, R>) {
547 const listings = yield* Cache.make({
548 capacity: 1024,
549 lookup: listPathDirectory,
550 requireServicesAt: "lookup",
551 });
552 return yield* effect.pipe(Effect.provideService(PathDirectoryListings, listings));
553 });
554​
555// An injected resolver or locator may answer differently for the same search, so its
556// entries are kept apart from every other resolver's.
557let spawnResolverCacheIdCount = 0;
558const spawnResolverCacheIds = new WeakMap<SpawnExecutableResolver | XcodeGitLocator, number>();
559function spawnResolverCacheId(resolver: SpawnExecutableResolver | XcodeGitLocator): number {
560 const known = spawnResolverCacheIds.get(resolver);
561 if (known !== undefined) return known;
562 const id = spawnResolverCacheIdCount++;
563 spawnResolverCacheIds.set(resolver, id);
564 return id;
566​
567function cacheCommandResolution(
568 cache: Map<string, CommandResolutionCacheEntry>,
569 cacheKey: string,
570 resolvedPath: string | null,
571 nowNanos: bigint,
572): void {
573 if (cache.size >= COMMAND_RESOLUTION_CACHE_MAX_ENTRIES) {
574 const oldestKey = cache.keys().next().value;
575 if (oldestKey !== undefined) {
576 cache.delete(oldestKey);
577 }
578 }
579 cache.set(cacheKey, {
580 resolvedPath,
581 expiresAtNanos: nowNanos + COMMAND_RESOLUTION_CACHE_TTL_NANOS,
582 });
584​
585const isExecutableFile = Effect.fnUntraced(function* (
586 filePath: string,
587 platform: NodeJS.Platform,
588 windowsPathExtensions: ReadonlyArray<string>,
589): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
590 const fileSystem = yield* FileSystem.FileSystem;
591 const path = yield* Path.Path;
592 const stat = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
593 if (stat === null || stat.type !== "File") return false;
594​
595 if (platform === "win32") {
596 const extension = path.extname(filePath);
597 if (extension.length === 0) return false;
598 return windowsPathExtensions.includes(extension.toUpperCase());
599 }
600​
601 return canExecuteFile(filePath);
602});
603​
604const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlatform")(function* (
605 command: string,
606 options: CommandAvailabilityOptions & { readonly platform: NodeJS.Platform },
607): Effect.fn.Return<string | null, never, FileSystem.FileSystem | Path.Path> {
608 const path = yield* Path.Path;
609 const platform = options.platform;
610 const env = options.env ?? process.env;
611 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
612 const commandCandidates = resolveCommandCandidates(
613 command,
614 platform,
615 windowsPathExtensions,
616 path.extname,
617 );
618​
619 if (command.includes("/") || command.includes("\\")) {
620 for (const candidate of commandCandidates) {
621 if (yield* isExecutableFile(candidate, platform, windowsPathExtensions)) {
622 return candidate;
623 }
624 }
625 return null;
626 }
627​
628 const pathValue = resolvePathEnvironmentVariable(env);
629 if (pathValue.length === 0) {
630 return null;
631 }
632​
633 const cacheKey = [platform, pathValue, windowsPathExtensions.join(";"), command].join(
634 COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR,
635 );
636 const cache = yield* CommandResolutionCache;
637 const nowNanos = yield* Clock.monotonicTimeNanos;
638 const cached = cache.get(cacheKey);
639 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
640 return cached.resolvedPath;
641 }
642​
643 // Keep case variants: Windows can make PATH directories case-sensitive.
644 const pathEntries: string[] = [];
645 const seenPathEntries = new Set<string>();
646 for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) {
647 const pathEntry = stripWrappingQuotes(entry.trim());
648 if (pathEntry.length === 0 || seenPathEntries.has(pathEntry)) continue;
649​
650 seenPathEntries.add(pathEntry);
651 pathEntries.push(pathEntry);
652 }
653​
654 const listings = yield* PathDirectoryListings;
655 for (const pathEntry of pathEntries) {
656 let listing = listings && (yield* Cache.get(listings, pathEntry));
657 if (listings && listing?.names && listing.modified !== (yield* directoryMtime(pathEntry))) {
658 yield* Cache.invalidate(listings, pathEntry);
659 listing = yield* Cache.get(listings, pathEntry);
660 }
661 for (const candidate of commandCandidates) {
662 if (listing?.names && !listing.names.has(candidate.toLowerCase())) continue;
663 const candidatePath = path.join(pathEntry, candidate);
664 if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) {
665 cacheCommandResolution(cache, cacheKey, candidatePath, nowNanos);
666 return candidatePath;
667 }
668 }
669 }
670 cacheCommandResolution(cache, cacheKey, null, nowNanos);
671 return null;
672});
673​
674export const resolveCommandPath = Effect.fn("shell.resolveCommandPath")(function* (
675 command: string,
676 options: CommandAvailabilityOptions = {},
677) {
678 return yield* resolveCommandPathForPlatform(command, {
679 env: options.env ?? (yield* HostProcess.Environment),
680 platform: yield* HostProcess.Platform,
681 });
682});
683​
684// Git for Windows 2.56 moved x64 builds from mingw64 to ucrt64; ARM64 builds
685// live in clangarm64 and 32-bit ones in mingw32.
686const GIT_FOR_WINDOWS_BUILDS = ["ucrt64", "clangarm64", "mingw64", "mingw32"] as const;
687​
688function isFileSync(filePath: string): boolean {
689 try {
690 return NodeFS.statSync(filePath).isFile();
691 } catch {
692 return false;
693 }
695​
696/**
697 * The launcher costs a second process on every git command, and each launch
698 * leaks a kernel token reference that slows process creation machine-wide until
699 * reboot. The real binary sets HOME itself, but adds its own folders to PATH
700 * for hooks, ssh and credential helpers only when MSYSTEM is unset, so the
701 * launcher stays when MSYSTEM is set.
702 */
703export function preferGitForWindowsBinary(
704 executable: string,
705 env: NodeJS.ProcessEnv,
706 isFile: (filePath: string) => boolean = isFileSync,
707): string {
708 if (env.MSYSTEM) return executable;
709 const path = NodePath.win32;
710 if (path.basename(executable).toLowerCase() !== "git.exe") return executable;
711 const launcherDirectory = path.dirname(executable);
712 const launcherFolder = path.basename(launcherDirectory).toLowerCase();
713 if (launcherFolder !== "cmd" && launcherFolder !== "bin") return executable;
714 const installRoot = path.dirname(launcherDirectory);
715 for (const build of GIT_FOR_WINDOWS_BUILDS) {
716 const candidate = path.join(installRoot, build, "bin", "git.exe");
717 if (isFile(candidate)) return candidate;
718 }
719 return executable;
721​
722// What npm's cmd-shim writes for a package whose bin is a native executable.
723const NPM_EXECUTABLE_SHIM_PREFIX = [
724 "@ECHO off",
725 "GOTO start",
726 ":find_dp0",
727 "SET dp0=%~dp0",
728 "EXIT /b",
729 ":start",
730 "SETLOCAL",
731 "CALL :find_dp0",
732];
733const NPM_EXECUTABLE_SHIM_RUN = /^"%dp0%\\([^"%]+\.exe)" +%\*$/;
734​
735function readFileSyncOrUndefined(filePath: string): string | undefined {
736 try {
737 return NodeFS.readFileSync(filePath, "utf8");
738 } catch {
739 return undefined;
740 }
742​
743/**
744 * The executable an npm cmd-shim runs, when the shim does nothing else.
745 * Started through the shim, the executable is a child of `cmd.exe` and so
746 * escapes the kill-on-close job libuv puts every child in: it keeps running
747 * after this process is killed. Started directly it is in the job.
748 */
749export function npmShimExecutable(
750 shimPath: string,
751 readFile: (filePath: string) => string | undefined = readFileSyncOrUndefined,
752 isFile: (filePath: string) => boolean = isFileSync,
753): string | undefined {
754 const path = NodePath.win32;
755 if (path.extname(shimPath).toLowerCase() !== ".cmd") return undefined;
756 // Compared exactly: whitespace CMD keeps, such as after `SET dp0=`, would
757 // make it run a different file than the one found here.
758 const lines = readFile(shimPath)
759 ?.split(/\r?\n/)
760 .filter((line) => line.length > 0);
761 if (lines?.length !== NPM_EXECUTABLE_SHIM_PREFIX.length + 1) return undefined;
762 if (NPM_EXECUTABLE_SHIM_PREFIX.some((expected, index) => lines[index] !== expected)) {
763 return undefined;
764 }
765 const target = NPM_EXECUTABLE_SHIM_RUN.exec(lines.at(-1)!)?.[1];
766 if (target === undefined) return undefined;
767 const executable = path.join(path.dirname(shimPath), target);
768 return isFile(executable) ? executable : undefined;
770​
771export type XcodeGitLocator = (env: NodeJS.ProcessEnv) => string | undefined;
772​
773// xcrun honors DEVELOPER_DIR and the `xcode-select` choice, as the shim does.
774function locateXcodeGitWithXcrun(env: NodeJS.ProcessEnv): string | undefined {
775 try {
776 const located = NodeChildProcess.execFileSync("/usr/bin/xcrun", ["--find", "git"], {
777 encoding: "utf8",
778 env,
779 timeout: 5_000,
780 stdio: ["ignore", "pipe", "ignore"],
781 }).trim();
782 return NodePath.isAbsolute(located) ? located : undefined;
783 } catch {
784 return undefined;
785 }
787​
788export const XcodeGitLocation = Context.Reference<XcodeGitLocator>(
789 "@t3tools/shared/shell/XcodeGitLocation",
790 { defaultValue: () => locateXcodeGitWithXcrun },
791);
792​
793const MACOS_GIT_SHIM = "/usr/bin/git";
794​
795/**
796 * /usr/bin/git is an xcrun shim that finds the active developer directory on
797 * every run: about 8 ms per spawn, against under 3 ms for the git behind it.
798 * Only the shim is replaced, so a git the user put first on PATH (Homebrew,
799 * Nix) still wins, and git's own children keep the same PATH. Any lookup
800 * failure keeps plain `git`.
801 */
802const resolveMacosGit = Effect.fnUntraced(function* (
803 env: NodeJS.ProcessEnv,
804 resolveExecutable: SpawnExecutableResolver,
805) {
806 const locateXcodeGit = yield* XcodeGitLocation;
807 const cache = yield* CommandResolutionCache;
808 const cacheKey = [
809 "xcode-git",
810 String(spawnResolverCacheId(resolveExecutable)),
811 String(spawnResolverCacheId(locateXcodeGit)),
812 resolvePathEnvironmentVariable(env),
813 env.DEVELOPER_DIR ?? "",
814 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
815 const nowNanos = yield* Clock.currentTimeNanos;
816 const cached = cache.get(cacheKey);
817 // An Xcode update or removal deletes the binary; look again instead of failing the spawn.
818 if (
819 cached !== undefined &&
820 cached.expiresAtNanos > nowNanos &&
821 (cached.resolvedPath === null ||
822 resolveExecutable(cached.resolvedPath, "darwin", env) !== undefined)
823 ) {
824 return cached.resolvedPath ?? "git";
825 }
826 const located =
827 resolveExecutable("git", "darwin", env) === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined;
828 const realGit =
829 located !== undefined && resolveExecutable(located, "darwin", env) !== undefined
830 ? located
831 : null;
832 cacheCommandResolution(cache, cacheKey, realGit, nowNanos);
833 return realGit ?? "git";
834});
835​
836export interface SpawnCommandOptions extends CommandAvailabilityOptions {
837 /** Run the executable behind an npm cmd-shim directly (see `npmShimExecutable`). */
838 readonly bypassNpmShim?: boolean;
840​
841export const resolveSpawnCommand = Effect.fnUntraced(function* (
842 command: string,
843 args: ReadonlyArray<string>,
844 options: SpawnCommandOptions = {},
845): Effect.fn.Return<ResolvedSpawnCommand> {
846 const platform = yield* HostProcess.Platform;
847 const isMacosGit = platform === "darwin" && command === "git";
848 if (platform !== "win32" && !isMacosGit) {
849 return { command, args: [...args], shell: false };
850 }
851​
852 const hostEnvironment = yield* HostProcess.Environment;
853 const env =
854 options.env === undefined
855 ? hostEnvironment
856 : options.extendEnv
857 ? { ...hostEnvironment, ...options.env }
858 : options.env;
859 const resolveExecutable = yield* SpawnExecutableResolution;
860 if (isMacosGit) {
861 return {
862 command: yield* resolveMacosGit(env, resolveExecutable),
863 args: [...args],
864 shell: false,
865 };
866 }
867 // The scan is synchronous and runs before every child process, so it shares
868 // the PATH scan cache above. Explicit paths stay uncached for the same reason,
869 // and so do misses: a failed spawn is how providers report "not installed",
870 // and that has to clear the moment the binary appears.
871 const explicitPath = command.includes("/") || command.includes("\\");
872 const cache = yield* CommandResolutionCache;
873 const cacheKey = [
874 "spawn",
875 String(spawnResolverCacheId(resolveExecutable)),
876 platform,
877 resolvePathEnvironmentVariable(env),
878 resolveWindowsPathExtensions(env).join(";"),
879 env.MSYSTEM ? "msystem" : "",
880 command,
881 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
882 const nowNanos = yield* Clock.currentTimeNanos;
883 const cached = explicitPath ? undefined : cache.get(cacheKey);
884 let resolvedExecutable: string | null;
885 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
886 resolvedExecutable = cached.resolvedPath;
887 } else {
888 const found = resolveExecutable(command, platform, env);
889 resolvedExecutable = found === undefined ? null : preferGitForWindowsBinary(found, env);
890 if (!explicitPath && resolvedExecutable !== null) {
891 cacheCommandResolution(cache, cacheKey, resolvedExecutable, nowNanos);
892 }
893 }
894 const resolvedCommand = resolvedExecutable ?? command;
895 const extension = NodePath.win32.extname(resolvedCommand).toLowerCase();
896 if (extension !== ".cmd" && extension !== ".bat") {
897 return { command: resolvedCommand, args: [...args], shell: false };
898 }
899 const shimExecutable = options.bypassNpmShim ? npmShimExecutable(resolvedCommand) : undefined;
900 if (shimExecutable !== undefined) {
901 return { command: shimExecutable, args: [...args], shell: false };
902 }
903​
904 // Node runs a shell spawn as `cmd.exe /d /s /c "<command> <args...>"`, but
905 // passing args with `shell: true` prints DEP0190. Build the same escaped line
906 // here and pass no args.
907 return {
908 command: [resolvedCommand, ...args].map(escapeWindowsShellArg).join(" "),
909 args: [],
910 shell: true,
911 };
912});
913​
914export const isCommandAvailable = Effect.fn("shell.isCommandAvailable")(function* (
915 command: string,
916 options: CommandAvailabilityOptions = {},
917) {
918 return (yield* resolveCommandPath(command, options)) !== null;
919});
920​
921function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
922 const appData = env.APPDATA?.trim();
923 const localAppData = env.LOCALAPPDATA?.trim();
924 const userProfile = env.USERPROFILE?.trim();
925​
926 return [
927 ...(appData ? [`${appData}\\npm`] : []),
928 ...(localAppData ? [`${localAppData}\\Programs\\nodejs`, `${localAppData}\\Volta\\bin`] : []),
929 ...(localAppData ? [`${localAppData}\\pnpm`] : []),
930 ...(userProfile
931 ? [`${userProfile}\\.local\\bin`, `${userProfile}\\.bun\\bin`, `${userProfile}\\scoop\\shims`]
932 : []),
933 ];
935​
936/** Keep one PATH spelling in copied Windows environment records. */
937export function setWindowsPath(env: NodeJS.ProcessEnv, value: string): void {
938 for (const key of Object.keys(env)) {
939 if (key.toUpperCase() === "PATH") {
940 delete env[key];
941 }
942 }
943 env.PATH = value;
945​
946function mergeWindowsEnv(
947 currentEnv: NodeJS.ProcessEnv,
948 patch: Partial<Record<string, string>>,
949): NodeJS.ProcessEnv {
950 const nextEnv: NodeJS.ProcessEnv = { ...currentEnv };
951 for (const [key, value] of Object.entries(patch)) {
952 if (value === undefined) continue;
953 if (key === "PATH") {
954 setWindowsPath(nextEnv, value);
955 } else {
956 nextEnv[key] = value;
957 }
958 }
959 return nextEnv;
961​
962export const resolveWindowsEnvironment = Effect.fn("shell.resolveWindowsEnvironment")(function* (
963 env: NodeJS.ProcessEnv,
964): Effect.fn.Return<Partial<NodeJS.ProcessEnv>, never, FileSystem.FileSystem | Path.Path> {
965 const readEnvironment = yield* WindowsShellEnvironment;
966 const commandAvailable = yield* CommandAvailability;
967 const inheritedPath = readEnvPath(env);
968 const shellPath = (yield* readEnvironment(["PATH"], { loadProfile: false })).PATH;
969 const mergedPath = mergePathValues(shellPath, inheritedPath, "win32");
970 const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);
971 const baselinePath = mergePathValues(mergedPath, knownCliPath, "win32");
972 const baselinePatch: Partial<NodeJS.ProcessEnv> = baselinePath ? { PATH: baselinePath } : {};
973 const baselineEnv = mergeWindowsEnv(env, baselinePatch);
974​
975 if (yield* commandAvailable("node", { env: baselineEnv })) {
976 return baselinePatch;
977 }
978​
979 const profiledEnvironment = yield* readEnvironment(["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"], {
980 loadProfile: true,
981 });
982 const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, "win32");
983 const profiledPatch: Partial<NodeJS.ProcessEnv> = {
984 ...(profiledPath ? { PATH: profiledPath } : {}),
985 ...(profiledEnvironment.FNM_DIR ? { FNM_DIR: profiledEnvironment.FNM_DIR } : {}),
986 ...(profiledEnvironment.FNM_MULTISHELL_PATH
987 ? { FNM_MULTISHELL_PATH: profiledEnvironment.FNM_MULTISHELL_PATH }
988 : {}),
989 };
990 return Object.keys(profiledPatch).length > 0
991 ? { ...baselinePatch, ...profiledPatch }
992 : baselinePatch;
993});