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

shell.ts

1,189 lines41.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(trimPathEntry(pathEntry, platform));
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​
135export function 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 = trimPathEntry(entry, platform);
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​
211const DEBUG_TRAP_SHELLS = new Set(["bash", "zsh", "sh", "ksh", "ksh93"]);
212const POSIX_CAPTURE_SYNTAX = { assignment: "__T3CODE_PRINTENV=$(", orElse: " || " };
213const PRINTENV_CAPTURE_SYNTAX = new Map(
214 [...DEBUG_TRAP_SHELLS, "dash", "ash"].map((shell) => [shell, POSIX_CAPTURE_SYNTAX] as const),
215).set("fish", { assignment: "set -l __T3CODE_PRINTENV (", orElse: "; or " });
216// Network PATH entries must be probed inside the shell's deadline, away from the desktop thread.
217const PRINTENV_LOOKUP_COMMAND = `/bin/sh -c 'command -v printenv || { [ -n "$1" ] && PATH="$1" command -v printenv; } || printf %s /usr/bin/printenv' t3`;
218​
219export function buildEnvironmentCaptureCommand(
220 shell: string,
221 names: ReadonlyArray<string>,
222): string {
223 const executableName = NodePath.basename(shell).toLowerCase();
224 const isNushell = executableName.startsWith("nu");
225 const syntax = PRINTENV_CAPTURE_SYNTAX.get(executableName);
226 const supportsFallback = syntax !== undefined;
227 const inheritedPath = resolvePathEnvironmentVariable(process.env)
228 .split(POSIX_PATH_DELIMITER)
229 .filter(Boolean)
230 .map((entry) => NodePath.posix.resolve(entry))
231 .join(POSIX_PATH_DELIMITER);
232 const lookupPrintenv = `${PRINTENV_LOOKUP_COMMAND} '${inheritedPath.replaceAll("'", "'\\''")}'`;
233 const { assignment, orElse } = syntax ?? POSIX_CAPTURE_SYNTAX;
234 const resolvePrintenv = `${assignment}${lookupPrintenv}); `;
235​
236 const capture = names
237 .map((name) => {
238 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
239 throw new Error(`Unsupported environment variable name: ${name}`);
240 }
241​
242 if (isNushell) {
243 // Without a configured conversion, Nu expands home paths only in a list PATH.
244 const defaultValue =
245 name === "PATH"
246 ? "if ($env.PATH? | describe | str starts-with 'list') { " +
247 "$env.PATH | each {|p| if ($p | str starts-with '~') { " +
248 "$p | path expand --no-symlink } else { $p } } | str join (char esep) " +
249 "} else { $env.PATH? | default '' }"
250 : `$env.${name}? | default ''`;
251 const value =
252 `if $env.${name}? == null { '' } else if ` +
253 `$env.ENV_CONVERSIONS?.${name}?.to_string? != null { ` +
254 `$env.${name} | do $env.ENV_CONVERSIONS.${name}.to_string $env.${name} ` +
255 `} else { ${defaultValue} }`;
256 return [
257 `print '${envCaptureStart(name)}'`,
258 `print (${value})`,
259 `print '${envCaptureEnd(name)}'`,
260 ].join("; ");
261 }
262​
263 return [
264 `printf '%s\\n' '${envCaptureStart(name)}'`,
265 supportsFallback
266 ? `printenv ${name}${orElse}"$__T3CODE_PRINTENV" ${name}${orElse}true`
267 : `printenv ${name} || true`,
268 `printf '%s\\n' '${envCaptureEnd(name)}'`,
269 ].join("; ");
270 })
271 .join("; ");
272​
273 // A DEBUG trap that echoes each command (e.g. into the terminal title) would print the markers.
274 // OpenBSD ksh (also its /bin/sh) exits on `trap - DEBUG`, so try it in a subshell first.
275 const command = supportsFallback ? resolvePrintenv + capture : capture;
276 return DEBUG_TRAP_SHELLS.has(executableName)
277 ? `(trap - DEBUG) 2>/dev/null && trap - DEBUG; ${command}`
278 : command;
280​
281// Process first so profile prepends win; User and Machine add dirs missing from the launch snapshot.
282export function windowsEnvironmentValueCommand(name: string): string {
283 if (name === "PATH") {
284 return (
285 "$value = (@(" +
286 "[Environment]::GetEnvironmentVariable('PATH','Process')," +
287 "[Environment]::GetEnvironmentVariable('PATH','Machine')," +
288 "[Environment]::GetEnvironmentVariable('PATH','User')" +
289 ") | Where-Object { $_ }) -join ';'"
290 );
291 }
292 return `$value = [Environment]::GetEnvironmentVariable('${name}')`;
294​
295function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
296 return [
297 "$ErrorActionPreference = 'Stop'",
298 ...names.flatMap((name) => {
299 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
300 throw new Error(`Unsupported environment variable name: ${name}`);
301 }
302​
303 return [
304 `Write-Output '${envCaptureStart(name)}'`,
305 windowsEnvironmentValueCommand(name),
306 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
307 `Write-Output '${envCaptureEnd(name)}'`,
308 ];
309 }),
310 ].join("; ");
312​
313function extractEnvironmentValue(output: string, name: string): string | undefined {
314 const startMarker = envCaptureStart(name);
315 const endMarker = envCaptureEnd(name);
316 const startIndex = output.indexOf(startMarker);
317 if (startIndex === -1) return undefined;
318​
319 const valueStartIndex = startIndex + startMarker.length;
320 const endIndex = output.indexOf(endMarker, valueStartIndex);
321 if (endIndex === -1) return undefined;
322​
323 const value = output
324 .slice(valueStartIndex, endIndex)
325 .replace(/^\r?\n/, "")
326 .replace(/\r?\n$/, "");
327​
328 return value.length > 0 ? value : undefined;
330​
331/** Reads the values `buildEnvironmentCaptureCommand` printed; unset or empty names are omitted. */
332export function extractEnvironmentValues(
333 output: string,
334 names: ReadonlyArray<string>,
335): Partial<Record<string, string>> {
336 const environment: Partial<Record<string, string>> = {};
337 for (const name of names) {
338 const value = extractEnvironmentValue(output, name);
339 if (value !== undefined) {
340 environment[name] = value;
341 }
342 }
343 return environment;
345​
346export type ShellEnvironmentReader = (
347 shell: string,
348 names: ReadonlyArray<string>,
349 execFile?: ExecFileSyncLike,
350) => Partial<Record<string, string>>;
351​
352export const readEnvironmentFromLoginShell: ShellEnvironmentReader = (
353 shell,
354 names,
355 execFile = NodeChildProcess.execFileSync,
356) => {
357 if (names.length === 0) {
358 return {};
359 }
360​
361 // Interactive startup loads PATH entries; detaching prevents job control on an
362 // inherited controlling TTY from stopping the probe while the parent waits.
363 const output = execFile(shell, ["-ilc", buildEnvironmentCaptureCommand(shell, names)], {
364 encoding: "utf8",
365 timeout: 5000,
366 killSignal: "SIGKILL",
367 detached: true,
368 stdio: ["ignore", "pipe", "ignore"],
369 });
370​
371 return extractEnvironmentValues(output, names);
372};
373​
374export type WindowsShellEnvironmentReader = (
375 names: ReadonlyArray<string>,
376 options?: WindowsEnvironmentProbeOptions,
377) => Effect.Effect<Partial<Record<string, string>>>;
378​
379export const WindowsShellEnvironment = Context.Reference<WindowsShellEnvironmentReader>(
380 "@t3tools/shared/shell/WindowsShellEnvironment",
381 {
382 defaultValue: () => readEnvironmentFromWindowsShell,
383 },
384);
385​
386export const CommandAvailability = Context.Reference<CommandAvailabilityChecker>(
387 "@t3tools/shared/shell/CommandAvailability",
388 {
389 defaultValue: () => isCommandAvailable,
390 },
391);
392​
393const execWindowsEnvironmentProbe = (
394 file: string,
395 args: ReadonlyArray<string>,
396 options: { encoding: "utf8"; timeout: number },
397) =>
398 Effect.callback<Option.Option<string>>((resume) => {
399 let child: NodeChildProcess.ChildProcess;
400 try {
401 child = NodeChildProcess.execFile(
402 file,
403 args,
404 { ...options, windowsHide: true },
405 (error, stdout) => {
406 resume(Effect.succeed(error ? Option.none() : Option.some(stdout)));
407 },
408 );
409 } catch {
410 resume(Effect.succeedNone);
411 return;
412 }
413 return Effect.sync(() => {
414 child.kill();
415 child.stdout?.destroy();
416 child.stderr?.destroy();
417 child.unref();
418 });
419 });
420​
421export const readEnvironmentFromWindowsShell = Effect.fn("shell.readEnvironmentFromWindowsShell")(
422 function* (
423 names: ReadonlyArray<string>,
424 options: WindowsEnvironmentProbeOptions = {},
425 execFile: typeof execWindowsEnvironmentProbe = execWindowsEnvironmentProbe,
426 ) {
427 if (names.length === 0) return {};
428​
429 const command = buildWindowsEnvironmentCaptureCommand(names);
430 const args = [
431 "-NoLogo",
432 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
433 "-NonInteractive",
434 "-Command",
435 command,
436 ];
437 for (const shell of WINDOWS_SHELL_CANDIDATES) {
438 const output = yield* execFile(shell, args, {
439 encoding: "utf8",
440 timeout: WINDOWS_SHELL_PROBE_TIMEOUT_MS,
441 }).pipe(Effect.timeoutOption(WINDOWS_SHELL_PROBE_DEADLINE), Effect.map(Option.flatten));
442 if (Option.isNone(output)) continue;
443​
444 const environment: Partial<Record<string, string>> = {};
445 for (const name of names) {
446 const value = extractEnvironmentValue(output.value, name);
447 if (value !== undefined) environment[name] = value;
448 }
449 return environment;
450 }
451​
452 return {};
453 },
454);
455​
456function stripWrappingQuotes(value: string): string {
457 return value.replace(/^"+|"+$/g, "");
459​
460function trimPathEntry(entry: string, platform: NodeJS.Platform): string {
461 return platform === "win32" ? entry.trim() : entry;
463​
464function pathDelimiterForPlatform(platform: NodeJS.Platform): string {
465 return platform === "win32" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER;
467​
468function normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string {
469 const normalized = stripWrappingQuotes(trimPathEntry(entry, platform));
470 return platform === "win32" ? normalized.toLowerCase() : normalized;
472​
473function sanitizePathEntry(entry: string, platform: NodeJS.Platform): string {
474 return platform === "win32" ? entry.replaceAll('"', "") : entry;
476​
477export function mergePathValues(
478 preferredPath: string | undefined,
479 inheritedPath: string | undefined,
480 platform: NodeJS.Platform,
481): string | undefined {
482 const delimiter = pathDelimiterForPlatform(platform);
483 const merged: string[] = [];
484 const seen = new Set<string>();
485​
486 for (const rawValue of [preferredPath, inheritedPath]) {
487 if (!rawValue) continue;
488​
489 for (const entry of rawValue.split(delimiter)) {
490 const sanitized = sanitizePathEntry(trimPathEntry(entry, platform), platform);
491 if (sanitized.length === 0) continue;
492​
493 const normalized = normalizePathEntryForComparison(sanitized, platform);
494 if (normalized.length === 0 || seen.has(normalized)) continue;
495​
496 seen.add(normalized);
497 merged.push(sanitized);
498 }
499 }
500​
501 return merged.length > 0 ? merged.join(delimiter) : undefined;
503​
504function readEnvPath(env: NodeJS.ProcessEnv): string | undefined {
505 return env.PATH ?? env.Path ?? env.path;
507​
508function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
509 return readEnvPath(env) ?? "";
511​
512function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
513 const rawValue =
514 env.PATHEXT ??
515 Object.entries(env).find(
516 ([key, value]) => key.toUpperCase() === "PATHEXT" && value !== undefined,
517 )?.[1];
518 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
519 if (!rawValue) return fallback;
520​
521 const parsed: string[] = [];
522 for (const entry of rawValue.split(";")) {
523 const trimmed = entry.trim();
524 if (trimmed.length === 0) continue;
525 parsed.push(trimmed.startsWith(".") ? trimmed.toUpperCase() : `.${trimmed.toUpperCase()}`);
526 }
527 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
529​
530function resolveCommandCandidates(
531 command: string,
532 platform: NodeJS.Platform,
533 windowsPathExtensions: ReadonlyArray<string>,
534 extname: (path: string) => string,
535): ReadonlyArray<string> {
536 if (platform !== "win32") return [command];
537 const extension = extname(command);
538 const normalizedExtension = extension.toUpperCase();
539​
540 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
541 const commandWithoutExtension = command.slice(0, -extension.length);
542 return Array.from(
543 new Set([
544 command,
545 `${commandWithoutExtension}${normalizedExtension}`,
546 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
547 ]),
548 );
549 }
550​
551 const candidates: string[] = [];
552 for (const candidateExtension of windowsPathExtensions) {
553 candidates.push(`${command}${candidateExtension}`);
554 candidates.push(`${command}${candidateExtension.toLowerCase()}`);
555 }
556 return Array.from(new Set(candidates));
558​
559// Explicit paths bypass the cache for new installs; cached misses can otherwise hide binaries for 30 seconds.
560const COMMAND_RESOLUTION_CACHE_TTL_NANOS = 30_000_000_000n;
561const COMMAND_RESOLUTION_CACHE_MAX_ENTRIES = 512;
562const COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR = String.fromCharCode(0);
563​
564interface CommandResolutionCacheEntry {
565 readonly resolvedPath: string | null;
566 readonly expiresAtNanos: bigint;
568​
569export const CommandResolutionCache = Context.Reference<Map<string, CommandResolutionCacheEntry>>(
570 "@t3tools/shared/shell/CommandResolutionCache",
571 {
572 defaultValue: () => new Map(),
573 },
574);
575​
576interface PathDirectoryListing {
577 readonly modified: number | null | undefined;
578 readonly names: ReadonlySet<string> | undefined;
580​
581const directoryMtime = (directory: string) =>
582 FileSystem.FileSystem.use((fileSystem) => fileSystem.stat(directory)).pipe(
583 Effect.map((info) =>
584 info.type === "Directory" ? Option.getOrUndefined(info.mtime)?.getTime() : undefined,
585 ),
586 Effect.catch((error) => Effect.succeed(error.reason._tag === "NotFound" ? null : undefined)),
587 );
588​
589// Timestamp before reading so concurrent additions change the next mtime check; missing listings fall back to direct probes.
590const listPathDirectory = Effect.fnUntraced(function* (
591 directory: string,
592): Effect.fn.Return<PathDirectoryListing, never, FileSystem.FileSystem> {
593 const modified = yield* directoryMtime(directory);
594 if (modified == null) return { modified, names: modified === null ? new Set() : undefined };
595 const entries = yield* FileSystem.FileSystem.use((fileSystem) =>
596 fileSystem.readDirectory(directory),
597 ).pipe(Effect.orElseSucceed(() => undefined));
598 return { modified, names: entries && new Set(entries.map((entry) => entry.toLowerCase())) };
599});
600​
601const PathDirectoryListings = Context.Reference<
602 Cache.Cache<string, PathDirectoryListing, never, FileSystem.FileSystem> | undefined
603>("@t3tools/shared/shell/PathDirectoryListings", { defaultValue: () => undefined });
604​
605export const withPathDirectoryListings =
606 /* Directory reads are cached inside one shell operation; a span for each lookup adds noise. */
607 Effect.fnUntraced(function* <A, E, R>(effect: Effect.Effect<A, E, R>) {
608 const listings = yield* Cache.make({
609 capacity: 1024,
610 lookup: listPathDirectory,
611 requireServicesAt: "lookup",
612 });
613 return yield* effect.pipe(Effect.provideService(PathDirectoryListings, listings));
614 });
615​
616// An injected resolver or locator may answer differently for the same search, so its
617// entries are kept apart from every other resolver's.
618let spawnResolverCacheIdCount = 0;
619const spawnResolverCacheIds = new WeakMap<SpawnExecutableResolver | XcodeGitLocator, number>();
620function spawnResolverCacheId(resolver: SpawnExecutableResolver | XcodeGitLocator): number {
621 const known = spawnResolverCacheIds.get(resolver);
622 if (known !== undefined) return known;
623 const id = spawnResolverCacheIdCount++;
624 spawnResolverCacheIds.set(resolver, id);
625 return id;
627​
628function cacheCommandResolution(
629 cache: Map<string, CommandResolutionCacheEntry>,
630 cacheKey: string,
631 resolvedPath: string | null,
632 nowNanos: bigint,
633): void {
634 if (cache.size >= COMMAND_RESOLUTION_CACHE_MAX_ENTRIES) {
635 const oldestKey = cache.keys().next().value;
636 if (oldestKey !== undefined) {
637 cache.delete(oldestKey);
638 }
639 }
640 cache.set(cacheKey, {
641 resolvedPath,
642 expiresAtNanos: nowNanos + COMMAND_RESOLUTION_CACHE_TTL_NANOS,
643 });
645​
646const isExecutableFile = Effect.fnUntraced(function* (
647 filePath: string,
648 platform: NodeJS.Platform,
649 windowsPathExtensions: ReadonlyArray<string>,
650): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
651 const fileSystem = yield* FileSystem.FileSystem;
652 const path = yield* Path.Path;
653 const stat = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
654 if (stat === null || stat.type !== "File") return false;
655​
656 if (platform === "win32") {
657 const extension = path.extname(filePath);
658 if (extension.length === 0) return false;
659 return windowsPathExtensions.includes(extension.toUpperCase());
660 }
661​
662 return canExecuteFile(filePath);
663});
664​
665// Called within the traced command resolvers.
666const findOnPath = Effect.fnUntraced(function* (
667 pathValue: string,
668 commandCandidates: ReadonlyArray<string>,
669 platform: NodeJS.Platform,
670 windowsPathExtensions: ReadonlyArray<string>,
671 isLast: (match: string) => boolean,
672): Effect.fn.Return<ReadonlyArray<string>, never, FileSystem.FileSystem | Path.Path> {
673 const path = yield* Path.Path;
674 // Keep case variants: Windows can make PATH directories case-sensitive.
675 const pathEntries: string[] = [];
676 const seenPathEntries = new Set<string>();
677 for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) {
678 const pathEntry = stripWrappingQuotes(trimPathEntry(entry, platform));
679 if (pathEntry.length === 0 || seenPathEntries.has(pathEntry)) continue;
680​
681 seenPathEntries.add(pathEntry);
682 pathEntries.push(pathEntry);
683 }
684​
685 const listings = yield* PathDirectoryListings;
686 const matches: string[] = [];
687 for (const pathEntry of pathEntries) {
688 let listing = listings && (yield* Cache.get(listings, pathEntry));
689 if (listings && listing?.names && listing.modified !== (yield* directoryMtime(pathEntry))) {
690 yield* Cache.invalidate(listings, pathEntry);
691 listing = yield* Cache.get(listings, pathEntry);
692 }
693 for (const candidate of commandCandidates) {
694 if (listing?.names && !listing.names.has(candidate.toLowerCase())) continue;
695 const candidatePath = path.join(pathEntry, candidate);
696 if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) {
697 matches.push(candidatePath);
698 if (isLast(candidatePath)) return matches;
699 break;
700 }
701 }
702 }
703 return matches;
704});
705​
706const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlatform")(function* (
707 command: string,
708 options: CommandAvailabilityOptions & { readonly platform: NodeJS.Platform },
709): Effect.fn.Return<string | null, never, FileSystem.FileSystem | Path.Path> {
710 const path = yield* Path.Path;
711 const platform = options.platform;
712 const env = options.env ?? process.env;
713 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
714 const commandCandidates = resolveCommandCandidates(
715 command,
716 platform,
717 windowsPathExtensions,
718 path.extname,
719 );
720​
721 if (command.includes("/") || command.includes("\\")) {
722 for (const candidate of commandCandidates) {
723 if (yield* isExecutableFile(candidate, platform, windowsPathExtensions)) {
724 return candidate;
725 }
726 }
727 return null;
728 }
729​
730 const pathValue = resolvePathEnvironmentVariable(env);
731 if (pathValue.length === 0) {
732 return null;
733 }
734​
735 const cacheKey = [platform, pathValue, windowsPathExtensions.join(";"), command].join(
736 COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR,
737 );
738 const cache = yield* CommandResolutionCache;
739 const nowNanos = yield* Clock.monotonicTimeNanos;
740 const cached = cache.get(cacheKey);
741 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
742 return cached.resolvedPath;
743 }
744​
745 const [resolvedPath = null] = yield* findOnPath(
746 pathValue,
747 commandCandidates,
748 platform,
749 windowsPathExtensions,
750 () => true,
751 );
752 cacheCommandResolution(cache, cacheKey, resolvedPath, nowNanos);
753 return resolvedPath;
754});
755​
756export const resolveCommandPath = Effect.fn("shell.resolveCommandPath")(function* (
757 command: string,
758 options: CommandAvailabilityOptions = {},
759) {
760 return yield* resolveCommandPathForPlatform(command, {
761 env: options.env ?? (yield* HostProcess.Environment),
762 platform: yield* HostProcess.Platform,
763 });
764});
765​
766// Matches for a bare command in PATH order, up to the first one `until` accepts; not cached.
767export const resolveCommandPaths = Effect.fn("shell.resolveCommandPaths")(function* (
768 command: string,
769 options: CommandAvailabilityOptions & { readonly until: (match: string) => boolean },
770) {
771 const path = yield* Path.Path;
772 const platform = yield* HostProcess.Platform;
773 const env = options.env ?? (yield* HostProcess.Environment);
774 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
775 return yield* findOnPath(
776 resolvePathEnvironmentVariable(env),
777 resolveCommandCandidates(command, platform, windowsPathExtensions, path.extname),
778 platform,
779 windowsPathExtensions,
780 options.until,
781 );
782});
783​
784// Git 2.56 x64 uses ucrt64; ARM64 uses clangarm64; older x64/32-bit builds use mingw64/mingw32.
785const GIT_FOR_WINDOWS_BUILDS = ["ucrt64", "clangarm64", "mingw64", "mingw32"] as const;
786​
787function isFileSync(filePath: string): boolean {
788 try {
789 return NodeFS.statSync(filePath).isFile();
790 } catch {
791 return false;
792 }
794​
795/** Bypass the launcher's extra process and kernel-token leak. Retain it when MSYSTEM is set, or git.exe omits hook/helper PATH entries. */
796export function preferGitForWindowsBinary(
797 executable: string,
798 env: NodeJS.ProcessEnv,
799 isFile: (filePath: string) => boolean = isFileSync,
800): string {
801 if (env.MSYSTEM) return executable;
802 const path = NodePath.win32;
803 if (path.basename(executable).toLowerCase() !== "git.exe") return executable;
804 const launcherDirectory = path.dirname(executable);
805 const launcherFolder = path.basename(launcherDirectory).toLowerCase();
806 if (launcherFolder !== "cmd" && launcherFolder !== "bin") return executable;
807 const installRoot = path.dirname(launcherDirectory);
808 for (const build of GIT_FOR_WINDOWS_BUILDS) {
809 const candidate = path.join(installRoot, build, "bin", "git.exe");
810 if (isFile(candidate)) return candidate;
811 }
812 return executable;
814​
815// npm cmd-shim format for native executables.
816const NPM_EXECUTABLE_SHIM_PREFIX = [
817 "@ECHO off",
818 "GOTO start",
819 ":find_dp0",
820 "SET dp0=%~dp0",
821 "EXIT /b",
822 ":start",
823 "SETLOCAL",
824 "CALL :find_dp0",
825];
826const NPM_EXECUTABLE_SHIM_RUN = /^"%dp0%\\([^"%]+\.exe)" +%\*$/;
827​
828function readFileSyncOrUndefined(filePath: string): string | undefined {
829 try {
830 return NodeFS.readFileSync(filePath, "utf8");
831 } catch {
832 return undefined;
833 }
835​
836/** Resolve shims that only launch native executables so direct spawning keeps them in libuv's kill-on-close job. */
837export function npmShimExecutable(
838 shimPath: string,
839 readFile: (filePath: string) => string | undefined = readFileSyncOrUndefined,
840 isFile: (filePath: string) => boolean = isFileSync,
841): string | undefined {
842 const path = NodePath.win32;
843 if (path.extname(shimPath).toLowerCase() !== ".cmd") return undefined;
844 // Match exactly because preserved SET whitespace can select a different file.
845 const lines = readFile(shimPath)
846 ?.split(/\r?\n/)
847 .filter((line) => line.length > 0);
848 if (lines?.length !== NPM_EXECUTABLE_SHIM_PREFIX.length + 1) return undefined;
849 if (NPM_EXECUTABLE_SHIM_PREFIX.some((expected, index) => lines[index] !== expected)) {
850 return undefined;
851 }
852 const target = NPM_EXECUTABLE_SHIM_RUN.exec(lines.at(-1)!)?.[1];
853 if (target === undefined) return undefined;
854 const executable = path.join(path.dirname(shimPath), target);
855 return isFile(executable) ? executable : undefined;
857​
858export type XcodeGitLocator = (env: NodeJS.ProcessEnv) => string | undefined;
859​
860// xcrun honors DEVELOPER_DIR and the `xcode-select` choice, as the shim does.
861function locateXcodeGitWithXcrun(env: NodeJS.ProcessEnv): string | undefined {
862 try {
863 const located = NodeChildProcess.execFileSync("/usr/bin/xcrun", ["--find", "git"], {
864 encoding: "utf8",
865 env,
866 timeout: 5_000,
867 stdio: ["ignore", "pipe", "ignore"],
868 }).trim();
869 return NodePath.isAbsolute(located) ? located : undefined;
870 } catch {
871 return undefined;
872 }
874​
875export const XcodeGitLocation = Context.Reference<XcodeGitLocator>(
876 "@t3tools/shared/shell/XcodeGitLocation",
877 { defaultValue: () => locateXcodeGitWithXcrun },
878);
879​
880const MACOS_GIT_SHIM = "/usr/bin/git";
881​
882/**
883 * Skip the xcrun shim's per-spawn lookup only when git resolves to /usr/bin/git.
884 * User-selected git on PATH still wins, children keep PATH, and lookup failures use `git`.
885 */
886const resolveMacosGit = Effect.fnUntraced(function* (
887 env: NodeJS.ProcessEnv,
888 resolveExecutable: SpawnExecutableResolver,
889) {
890 const locateXcodeGit = yield* XcodeGitLocation;
891 const cache = yield* CommandResolutionCache;
892 const cacheKey = [
893 "xcode-git",
894 String(spawnResolverCacheId(resolveExecutable)),
895 String(spawnResolverCacheId(locateXcodeGit)),
896 resolvePathEnvironmentVariable(env),
897 env.DEVELOPER_DIR ?? "",
898 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
899 const nowNanos = yield* Clock.currentTimeNanos;
900 const cached = cache.get(cacheKey);
901 // An Xcode update or removal deletes the binary; look again instead of failing the spawn.
902 if (
903 cached !== undefined &&
904 cached.expiresAtNanos > nowNanos &&
905 (cached.resolvedPath === null ||
906 resolveExecutable(cached.resolvedPath, "darwin", env) !== undefined)
907 ) {
908 return cached.resolvedPath ?? "git";
909 }
910 const located =
911 resolveExecutable("git", "darwin", env) === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined;
912 const realGit =
913 located !== undefined && resolveExecutable(located, "darwin", env) !== undefined
914 ? located
915 : null;
916 cacheCommandResolution(cache, cacheKey, realGit, nowNanos);
917 return realGit ?? "git";
918});
919​
920export interface SpawnCommandOptions extends CommandAvailabilityOptions {
921 /** Bypass npm cmd-shims; see npmShimExecutable for process-lifetime semantics. */
922 readonly bypassNpmShim?: boolean;
924​
925// `*` is one argument that is not an option. These forms read refs or config
926// only, so git starts no hook, helper, pager, editor or lazy fetch for them.
927const CONSOLE_FREE_GIT_READS = [
928 "rev-parse --git-path index",
929 "rev-parse --git-common-dir",
930 "rev-parse --show-toplevel",
931 "rev-parse --symbolic-full-name HEAD",
932 "rev-parse --abbrev-ref --symbolic-full-name @{upstream}",
933 "symbolic-ref --quiet HEAD",
934 "symbolic-ref *",
935 "remote",
936 "remote get-url *",
937 "remote get-url -- *",
938 "config --get *",
939].map((form) => form.split(" "));
940​
941export function runsGitWithoutConsole(
942 platform: NodeJS.Platform,
943 executable: string,
944 args: ReadonlyArray<string>,
945): boolean {
946 if (platform !== "win32") return false;
947 const { basename, dirname } = NodePath.win32;
948 const bin = dirname(executable);
949 const build = basename(dirname(bin)).toLowerCase();
950 if (basename(executable).toLowerCase() !== "git.exe" || basename(bin).toLowerCase() !== "bin") {
951 return false;
952 }
953 if (!GIT_FOR_WINDOWS_BUILDS.some((candidate) => candidate === build)) return false;
954 const rest =
955 args[0] === "--git-dir" && args[1] !== undefined && !args[1].startsWith("-")
956 ? args.slice(2)
957 : args;
958 return CONSOLE_FREE_GIT_READS.some(
959 (form) =>
960 form.length === rest.length &&
961 form.every((part, i) => part === rest[i] || (part === "*" && !rest[i]!.startsWith("-"))),
962 );
964​
965export const resolveSpawnCommand = Effect.fnUntraced(function* (
966 command: string,
967 args: ReadonlyArray<string>,
968 options: SpawnCommandOptions = {},
969): Effect.fn.Return<ResolvedSpawnCommand> {
970 const platform = yield* HostProcess.Platform;
971 const isMacosGit = platform === "darwin" && command === "git";
972 if (platform !== "win32" && !isMacosGit) {
973 return { command, args: [...args], shell: false };
974 }
975​
976 const hostEnvironment = yield* HostProcess.Environment;
977 const env =
978 options.env === undefined
979 ? hostEnvironment
980 : options.extendEnv
981 ? { ...hostEnvironment, ...options.env }
982 : options.env;
983 const resolveExecutable = yield* SpawnExecutableResolution;
984 if (isMacosGit) {
985 return {
986 command: yield* resolveMacosGit(env, resolveExecutable),
987 args: [...args],
988 shell: false,
989 };
990 }
991 // The scan is synchronous and runs before every child process, so it shares
992 // the PATH scan cache above. Explicit paths stay uncached for the same reason,
993 // and so do misses: a failed spawn is how providers report "not installed",
994 // and that has to clear the moment the binary appears.
995 const explicitPath = command.includes("/") || command.includes("\\");
996 const cache = yield* CommandResolutionCache;
997 const cacheKey = [
998 "spawn",
999 String(spawnResolverCacheId(resolveExecutable)),
1000 platform,
1001 resolvePathEnvironmentVariable(env),
1002 resolveWindowsPathExtensions(env).join(";"),
1003 env.MSYSTEM ? "msystem" : "",
1004 command,
1005 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
1006 const nowNanos = yield* Clock.currentTimeNanos;
1007 const cached = explicitPath ? undefined : cache.get(cacheKey);
1008 let resolvedExecutable: string | null;
1009 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
1010 resolvedExecutable = cached.resolvedPath;
1011 } else {
1012 const found = resolveExecutable(command, platform, env);
1013 resolvedExecutable = found === undefined ? null : preferGitForWindowsBinary(found, env);
1014 if (!explicitPath && resolvedExecutable !== null) {
1015 cacheCommandResolution(cache, cacheKey, resolvedExecutable, nowNanos);
1018 const resolvedCommand = resolvedExecutable ?? command;
1019 const extension = NodePath.win32.extname(resolvedCommand).toLowerCase();
1020 if (extension !== ".cmd" && extension !== ".bat") {
1021 return { command: resolvedCommand, args: [...args], shell: false };
1023 const shimExecutable = options.bypassNpmShim ? npmShimExecutable(resolvedCommand) : undefined;
1024 if (shimExecutable !== undefined) {
1025 return { command: shimExecutable, args: [...args], shell: false };
1027​
1028 // Build the escaped command line without separate args to avoid Node DEP0190 with shell:true.
1029 return {
1030 command: [resolvedCommand, ...args].map(escapeWindowsShellArg).join(" "),
1031 args: [],
1032 shell: true,
1033 };
1034});
1035​
1036export const isCommandAvailable = Effect.fn("shell.isCommandAvailable")(function* (
1037 command: string,
1038 options: CommandAvailabilityOptions = {},
1039) {
1040 return (yield* resolveCommandPath(command, options)) !== null;
1041});
1042​
1043function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
1044 const appData = env.APPDATA?.trim();
1045 const localAppData = env.LOCALAPPDATA?.trim();
1046 const userProfile = env.USERPROFILE?.trim();
1047​
1048 return [
1049 ...(appData ? [`${appData}\\npm`] : []),
1050 ...(localAppData ? [`${localAppData}\\Programs\\nodejs`, `${localAppData}\\Volta\\bin`] : []),
1051 ...(localAppData ? [`${localAppData}\\pnpm`] : []),
1052 ...(userProfile
1053 ? [`${userProfile}\\.local\\bin`, `${userProfile}\\.bun\\bin`, `${userProfile}\\scoop\\shims`]
1054 : []),
1055 ];
1057​
1058/** Keep one PATH spelling in copied Windows environment records. */
1059export function setWindowsPath(env: NodeJS.ProcessEnv, value: string | null): void {
1060 for (const key of Object.keys(env)) {
1061 if (key.toUpperCase() === "PATH") {
1062 delete env[key];
1065 if (value !== null) env.PATH = value;
1067​
1068function mergeWindowsEnv(
1069 currentEnv: NodeJS.ProcessEnv,
1070 patch: Partial<Record<string, string>>,
1071): NodeJS.ProcessEnv {
1072 const nextEnv: NodeJS.ProcessEnv = { ...currentEnv };
1073 for (const [key, value] of Object.entries(patch)) {
1074 if (value === undefined) continue;
1075 if (key === "PATH") {
1076 setWindowsPath(nextEnv, value);
1077 } else {
1078 nextEnv[key] = value;
1081 return nextEnv;
1083​
1084export const resolveWindowsEnvironment = Effect.fn("shell.resolveWindowsEnvironment")(function* (
1085 env: NodeJS.ProcessEnv,
1086): Effect.fn.Return<Partial<NodeJS.ProcessEnv>, never, FileSystem.FileSystem | Path.Path> {
1087 const readEnvironment = yield* WindowsShellEnvironment;
1088 const commandAvailable = yield* CommandAvailability;
1089 const inheritedPath = readEnvPath(env);
1090 const shellPath = (yield* readEnvironment(["PATH"], { loadProfile: false })).PATH;
1091 const mergedPath = mergePathValues(shellPath, inheritedPath, "win32");
1092 const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);
1093 const baselinePath = mergePathValues(mergedPath, knownCliPath, "win32");
1094 const baselinePatch: Partial<NodeJS.ProcessEnv> = baselinePath ? { PATH: baselinePath } : {};
1095 const baselineEnv = mergeWindowsEnv(env, baselinePatch);
1096​
1097 if (yield* commandAvailable("node", { env: baselineEnv })) {
1098 return baselinePatch;
1100​
1101 const profiledEnvironment = yield* readEnvironment(["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"], {
1102 loadProfile: true,
1103 });
1104 const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, "win32");
1105 const profiledPatch: Partial<NodeJS.ProcessEnv> = {
1106 ...(profiledPath ? { PATH: profiledPath } : {}),
1107 ...(profiledEnvironment.FNM_DIR ? { FNM_DIR: profiledEnvironment.FNM_DIR } : {}),
1108 ...(profiledEnvironment.FNM_MULTISHELL_PATH
1109 ? { FNM_MULTISHELL_PATH: profiledEnvironment.FNM_MULTISHELL_PATH }
1110 : {}),
1111 };
1112 return Object.keys(profiledPatch).length > 0
1113 ? { ...baselinePatch, ...profiledPatch }
1114 : baselinePatch;
1115});
1116​
1117export function applyShellEnvironment(
1118 env: NodeJS.ProcessEnv,
1119 patch: ShellEnvironmentPatch,
1120 platform: NodeJS.Platform,
1121): void {
1122 for (const [key, value] of Object.entries(patch)) {
1123 if (key === "PATH" && platform === "win32") setWindowsPath(env, value);
1124 else if (value === null) delete env[key];
1125 else env[key] = value;
1128​
1129interface PathSetupInput {
1130 readonly directory: string;
1131 readonly home: string;
1132 readonly shell: string | undefined;
1133 readonly platform: NodeJS.Platform;
1134 /** `XDG_CONFIG_HOME`, where fish reads its startup file when set. */
1135 readonly configHome?: string | undefined;
1136 /** `ZDOTDIR`, where zsh reads `.zshrc` when set. */
1137 readonly zdotdir?: string | undefined;
1139​
1140/**
1141 * The startup file (`~/...`, or absolute under `configHome`) and line that put `directory` last on
1142 * PATH for new zsh, bash, or fish terminals, so it never shadows another `t3`. Undefined on Windows (writing PATH there would flatten the registry's
1143 * `%VAR%` entries), for other shells, macOS bash, or unsafe paths.
1144 */
1145export function pathSetup(
1146 input: PathSetupInput,
1147): { readonly file: string; readonly line: string } | undefined {
1148 // A relative folder on PATH would follow the working directory into any checkout.
1149 if (input.platform === "win32" || !input.directory.startsWith("/")) return undefined;
1150 const underHome = input.directory.startsWith(`${input.home}/`);
1151 const rest = underHome ? input.directory.slice(input.home.length) : input.directory;
1152 if (!/^[\w./-]+$/.test(rest)) return undefined;
1153 const directory = underHome ? `$HOME${rest}` : rest;
1154 const shell = input.shell?.split("/").pop();
1155 // A set folder the shell reads from replaces the default; one unsafe to write means no setup,
1156 // since the default file would never be read.
1157 const readFrom = (value: string | undefined, fallback: string) =>
1158 !value ? fallback : value.startsWith("/") && /^[\w./-]+$/.test(value) ? value : undefined;
1159 if (shell === "fish") {
1160 const configHome = readFrom(input.configHome, "~/.config");
1161 if (configHome === undefined) return undefined;
1162 // --path changes $PATH itself; fish_user_paths would go ahead of the system folders.
1163 return {
1164 file: `${configHome}/fish/config.fish`,
1165 line: `fish_add_path --append --path ${directory}`,
1166 };
1168 // macOS bash reads only the first of .bash_profile, .bash_login, and .profile; no file is safe.
1169 const zdotdir = readFrom(input.zdotdir, "~");
1170 const file =
1171 shell === "zsh"
1172 ? zdotdir && `${zdotdir}/.zshrc`
1173 : shell === "bash" && input.platform !== "darwin"
1174 ? "~/.bashrc"
1175 : undefined;
1176 return file === undefined ? undefined : { file, line: `export PATH="$PATH:${directory}"` };
1178​
1179/** A command to paste that does what {@link pathSetup} describes. */
1180export function pathSetupCommand(input: PathSetupInput): string | undefined {
1181 const setup = pathSetup(input);
1182 if (!setup) return undefined;
1183 // The leading newline keeps the line out of a final comment with no newline after it.
1184 const append = `printf '\\n%s\\n' '${setup.line}' >> ${setup.file}`;
1185 // fish's config folder may not exist yet; `&&` works in fish 3 too.
1186 return setup.file.endsWith(".fish")
1187 ? `mkdir -p ${setup.file.slice(0, setup.file.lastIndexOf("/"))} && ${append}`
1188 : append;