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

shell.ts

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