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