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

shell.ts

1,167 lines40.8 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​
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 = 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​
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​
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("; ");
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;
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;
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, "");
445​
446function pathDelimiterForPlatform(platform: NodeJS.Platform): string {
447 return platform === "win32" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER;
449​
450function normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string {
451 const normalized = stripWrappingQuotes(entry.trim());
452 return platform === "win32" ? normalized.toLowerCase() : normalized;
454​
455function sanitizePathEntry(entry: string, platform: NodeJS.Platform): string {
456 return platform === "win32" ? entry.replaceAll('"', "") : entry;
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;
485​
486function readEnvPath(env: NodeJS.ProcessEnv): string | undefined {
487 return env.PATH ?? env.Path ?? env.path;
489​
490function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
491 return readEnvPath(env) ?? "";
493​
494function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
495 const rawValue = env.PATHEXT;
496 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
497 if (!rawValue) return fallback;
498​
499 const parsed: string[] = [];
500 for (const entry of rawValue.split(";")) {
501 const trimmed = entry.trim();
502 if (trimmed.length === 0) continue;
503 parsed.push(trimmed.startsWith(".") ? trimmed.toUpperCase() : `.${trimmed.toUpperCase()}`);
504 }
505 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
507​
508function resolveCommandCandidates(
509 command: string,
510 platform: NodeJS.Platform,
511 windowsPathExtensions: ReadonlyArray<string>,
512 extname: (path: string) => string,
513): ReadonlyArray<string> {
514 if (platform !== "win32") return [command];
515 const extension = extname(command);
516 const normalizedExtension = extension.toUpperCase();
517​
518 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
519 const commandWithoutExtension = command.slice(0, -extension.length);
520 return Array.from(
521 new Set([
522 command,
523 `${commandWithoutExtension}${normalizedExtension}`,
524 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
525 ]),
526 );
527 }
528​
529 const candidates: string[] = [];
530 for (const candidateExtension of windowsPathExtensions) {
531 candidates.push(`${command}${candidateExtension}`);
532 candidates.push(`${command}${candidateExtension.toLowerCase()}`);
533 }
534 return Array.from(new Set(candidates));
536​
537// Explicit paths bypass the cache for new installs; cached misses can otherwise hide binaries for 30 seconds.
538const COMMAND_RESOLUTION_CACHE_TTL_NANOS = 30_000_000_000n;
539const COMMAND_RESOLUTION_CACHE_MAX_ENTRIES = 512;
540const COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR = String.fromCharCode(0);
541​
542interface CommandResolutionCacheEntry {
543 readonly resolvedPath: string | null;
544 readonly expiresAtNanos: bigint;
546​
547export const CommandResolutionCache = Context.Reference<Map<string, CommandResolutionCacheEntry>>(
548 "@t3tools/shared/shell/CommandResolutionCache",
549 {
550 defaultValue: () => new Map(),
551 },
552);
553​
554interface PathDirectoryListing {
555 readonly modified: number | null | undefined;
556 readonly names: ReadonlySet<string> | undefined;
558​
559const directoryMtime = (directory: string) =>
560 FileSystem.FileSystem.use((fileSystem) => fileSystem.stat(directory)).pipe(
561 Effect.map((info) =>
562 info.type === "Directory" ? Option.getOrUndefined(info.mtime)?.getTime() : undefined,
563 ),
564 Effect.catch((error) => Effect.succeed(error.reason._tag === "NotFound" ? null : undefined)),
565 );
566​
567// Timestamp before reading so concurrent additions change the next mtime check; missing listings fall back to direct probes.
568const listPathDirectory = Effect.fnUntraced(function* (
569 directory: string,
570): Effect.fn.Return<PathDirectoryListing, never, FileSystem.FileSystem> {
571 const modified = yield* directoryMtime(directory);
572 if (modified == null) return { modified, names: modified === null ? new Set() : undefined };
573 const entries = yield* FileSystem.FileSystem.use((fileSystem) =>
574 fileSystem.readDirectory(directory),
575 ).pipe(Effect.orElseSucceed(() => undefined));
576 return { modified, names: entries && new Set(entries.map((entry) => entry.toLowerCase())) };
577});
578​
579const PathDirectoryListings = Context.Reference<
580 Cache.Cache<string, PathDirectoryListing, never, FileSystem.FileSystem> | undefined
581>("@t3tools/shared/shell/PathDirectoryListings", { defaultValue: () => undefined });
582​
583export const withPathDirectoryListings =
584 /* Directory reads are cached inside one shell operation; a span for each lookup adds noise. */
585 Effect.fnUntraced(function* <A, E, R>(effect: Effect.Effect<A, E, R>) {
586 const listings = yield* Cache.make({
587 capacity: 1024,
588 lookup: listPathDirectory,
589 requireServicesAt: "lookup",
590 });
591 return yield* effect.pipe(Effect.provideService(PathDirectoryListings, listings));
592 });
593​
594// An injected resolver or locator may answer differently for the same search, so its
595// entries are kept apart from every other resolver's.
596let spawnResolverCacheIdCount = 0;
597const spawnResolverCacheIds = new WeakMap<SpawnExecutableResolver | XcodeGitLocator, number>();
598function spawnResolverCacheId(resolver: SpawnExecutableResolver | XcodeGitLocator): number {
599 const known = spawnResolverCacheIds.get(resolver);
600 if (known !== undefined) return known;
601 const id = spawnResolverCacheIdCount++;
602 spawnResolverCacheIds.set(resolver, id);
603 return id;
605​
606function cacheCommandResolution(
607 cache: Map<string, CommandResolutionCacheEntry>,
608 cacheKey: string,
609 resolvedPath: string | null,
610 nowNanos: bigint,
611): void {
612 if (cache.size >= COMMAND_RESOLUTION_CACHE_MAX_ENTRIES) {
613 const oldestKey = cache.keys().next().value;
614 if (oldestKey !== undefined) {
615 cache.delete(oldestKey);
616 }
617 }
618 cache.set(cacheKey, {
619 resolvedPath,
620 expiresAtNanos: nowNanos + COMMAND_RESOLUTION_CACHE_TTL_NANOS,
621 });
623​
624const isExecutableFile = Effect.fnUntraced(function* (
625 filePath: string,
626 platform: NodeJS.Platform,
627 windowsPathExtensions: ReadonlyArray<string>,
628): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
629 const fileSystem = yield* FileSystem.FileSystem;
630 const path = yield* Path.Path;
631 const stat = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
632 if (stat === null || stat.type !== "File") return false;
633​
634 if (platform === "win32") {
635 const extension = path.extname(filePath);
636 if (extension.length === 0) return false;
637 return windowsPathExtensions.includes(extension.toUpperCase());
638 }
639​
640 return canExecuteFile(filePath);
641});
642​
643// Called within the traced command resolvers.
644const findOnPath = Effect.fnUntraced(function* (
645 pathValue: string,
646 commandCandidates: ReadonlyArray<string>,
647 platform: NodeJS.Platform,
648 windowsPathExtensions: ReadonlyArray<string>,
649 isLast: (match: string) => boolean,
650): Effect.fn.Return<ReadonlyArray<string>, never, FileSystem.FileSystem | Path.Path> {
651 const path = yield* Path.Path;
652 // Keep case variants: Windows can make PATH directories case-sensitive.
653 const pathEntries: string[] = [];
654 const seenPathEntries = new Set<string>();
655 for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) {
656 const pathEntry = stripWrappingQuotes(entry.trim());
657 if (pathEntry.length === 0 || seenPathEntries.has(pathEntry)) continue;
658​
659 seenPathEntries.add(pathEntry);
660 pathEntries.push(pathEntry);
661 }
662​
663 const listings = yield* PathDirectoryListings;
664 const matches: string[] = [];
665 for (const pathEntry of pathEntries) {
666 let listing = listings && (yield* Cache.get(listings, pathEntry));
667 if (listings && listing?.names && listing.modified !== (yield* directoryMtime(pathEntry))) {
668 yield* Cache.invalidate(listings, pathEntry);
669 listing = yield* Cache.get(listings, pathEntry);
670 }
671 for (const candidate of commandCandidates) {
672 if (listing?.names && !listing.names.has(candidate.toLowerCase())) continue;
673 const candidatePath = path.join(pathEntry, candidate);
674 if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) {
675 matches.push(candidatePath);
676 if (isLast(candidatePath)) return matches;
677 break;
678 }
679 }
680 }
681 return matches;
682});
683​
684const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlatform")(function* (
685 command: string,
686 options: CommandAvailabilityOptions & { readonly platform: NodeJS.Platform },
687): Effect.fn.Return<string | null, never, FileSystem.FileSystem | Path.Path> {
688 const path = yield* Path.Path;
689 const platform = options.platform;
690 const env = options.env ?? process.env;
691 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
692 const commandCandidates = resolveCommandCandidates(
693 command,
694 platform,
695 windowsPathExtensions,
696 path.extname,
697 );
698​
699 if (command.includes("/") || command.includes("\\")) {
700 for (const candidate of commandCandidates) {
701 if (yield* isExecutableFile(candidate, platform, windowsPathExtensions)) {
702 return candidate;
703 }
704 }
705 return null;
706 }
707​
708 const pathValue = resolvePathEnvironmentVariable(env);
709 if (pathValue.length === 0) {
710 return null;
711 }
712​
713 const cacheKey = [platform, pathValue, windowsPathExtensions.join(";"), command].join(
714 COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR,
715 );
716 const cache = yield* CommandResolutionCache;
717 const nowNanos = yield* Clock.monotonicTimeNanos;
718 const cached = cache.get(cacheKey);
719 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
720 return cached.resolvedPath;
721 }
722​
723 const [resolvedPath = null] = yield* findOnPath(
724 pathValue,
725 commandCandidates,
726 platform,
727 windowsPathExtensions,
728 () => true,
729 );
730 cacheCommandResolution(cache, cacheKey, resolvedPath, nowNanos);
731 return resolvedPath;
732});
733​
734export const resolveCommandPath = Effect.fn("shell.resolveCommandPath")(function* (
735 command: string,
736 options: CommandAvailabilityOptions = {},
737) {
738 return yield* resolveCommandPathForPlatform(command, {
739 env: options.env ?? (yield* HostProcess.Environment),
740 platform: yield* HostProcess.Platform,
741 });
742});
743​
744// Matches for a bare command in PATH order, up to the first one `until` accepts; not cached.
745export const resolveCommandPaths = Effect.fn("shell.resolveCommandPaths")(function* (
746 command: string,
747 options: CommandAvailabilityOptions & { readonly until: (match: string) => boolean },
748) {
749 const path = yield* Path.Path;
750 const platform = yield* HostProcess.Platform;
751 const env = options.env ?? (yield* HostProcess.Environment);
752 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
753 return yield* findOnPath(
754 resolvePathEnvironmentVariable(env),
755 resolveCommandCandidates(command, platform, windowsPathExtensions, path.extname),
756 platform,
757 windowsPathExtensions,
758 options.until,
759 );
760});
761​
762// Git 2.56 x64 uses ucrt64; ARM64 uses clangarm64; older x64/32-bit builds use mingw64/mingw32.
763const GIT_FOR_WINDOWS_BUILDS = ["ucrt64", "clangarm64", "mingw64", "mingw32"] as const;
764​
765function isFileSync(filePath: string): boolean {
766 try {
767 return NodeFS.statSync(filePath).isFile();
768 } catch {
769 return false;
770 }
772​
773/** Bypass the launcher's extra process and kernel-token leak. Retain it when MSYSTEM is set, or git.exe omits hook/helper PATH entries. */
774export function preferGitForWindowsBinary(
775 executable: string,
776 env: NodeJS.ProcessEnv,
777 isFile: (filePath: string) => boolean = isFileSync,
778): string {
779 if (env.MSYSTEM) return executable;
780 const path = NodePath.win32;
781 if (path.basename(executable).toLowerCase() !== "git.exe") return executable;
782 const launcherDirectory = path.dirname(executable);
783 const launcherFolder = path.basename(launcherDirectory).toLowerCase();
784 if (launcherFolder !== "cmd" && launcherFolder !== "bin") return executable;
785 const installRoot = path.dirname(launcherDirectory);
786 for (const build of GIT_FOR_WINDOWS_BUILDS) {
787 const candidate = path.join(installRoot, build, "bin", "git.exe");
788 if (isFile(candidate)) return candidate;
789 }
790 return executable;
792​
793// npm cmd-shim format for native executables.
794const NPM_EXECUTABLE_SHIM_PREFIX = [
795 "@ECHO off",
796 "GOTO start",
797 ":find_dp0",
798 "SET dp0=%~dp0",
799 "EXIT /b",
800 ":start",
801 "SETLOCAL",
802 "CALL :find_dp0",
803];
804const NPM_EXECUTABLE_SHIM_RUN = /^"%dp0%\\([^"%]+\.exe)" +%\*$/;
805​
806function readFileSyncOrUndefined(filePath: string): string | undefined {
807 try {
808 return NodeFS.readFileSync(filePath, "utf8");
809 } catch {
810 return undefined;
811 }
813​
814/** Resolve shims that only launch native executables so direct spawning keeps them in libuv's kill-on-close job. */
815export function npmShimExecutable(
816 shimPath: string,
817 readFile: (filePath: string) => string | undefined = readFileSyncOrUndefined,
818 isFile: (filePath: string) => boolean = isFileSync,
819): string | undefined {
820 const path = NodePath.win32;
821 if (path.extname(shimPath).toLowerCase() !== ".cmd") return undefined;
822 // Match exactly because preserved SET whitespace can select a different file.
823 const lines = readFile(shimPath)
824 ?.split(/\r?\n/)
825 .filter((line) => line.length > 0);
826 if (lines?.length !== NPM_EXECUTABLE_SHIM_PREFIX.length + 1) return undefined;
827 if (NPM_EXECUTABLE_SHIM_PREFIX.some((expected, index) => lines[index] !== expected)) {
828 return undefined;
829 }
830 const target = NPM_EXECUTABLE_SHIM_RUN.exec(lines.at(-1)!)?.[1];
831 if (target === undefined) return undefined;
832 const executable = path.join(path.dirname(shimPath), target);
833 return isFile(executable) ? executable : undefined;
835​
836export type XcodeGitLocator = (env: NodeJS.ProcessEnv) => string | undefined;
837​
838// xcrun honors DEVELOPER_DIR and the `xcode-select` choice, as the shim does.
839function locateXcodeGitWithXcrun(env: NodeJS.ProcessEnv): string | undefined {
840 try {
841 const located = NodeChildProcess.execFileSync("/usr/bin/xcrun", ["--find", "git"], {
842 encoding: "utf8",
843 env,
844 timeout: 5_000,
845 stdio: ["ignore", "pipe", "ignore"],
846 }).trim();
847 return NodePath.isAbsolute(located) ? located : undefined;
848 } catch {
849 return undefined;
850 }
852​
853export const XcodeGitLocation = Context.Reference<XcodeGitLocator>(
854 "@t3tools/shared/shell/XcodeGitLocation",
855 { defaultValue: () => locateXcodeGitWithXcrun },
856);
857​
858const MACOS_GIT_SHIM = "/usr/bin/git";
859​
860/**
861 * Skip the xcrun shim's per-spawn lookup only when git resolves to /usr/bin/git.
862 * User-selected git on PATH still wins, children keep PATH, and lookup failures use `git`.
863 */
864const resolveMacosGit = Effect.fnUntraced(function* (
865 env: NodeJS.ProcessEnv,
866 resolveExecutable: SpawnExecutableResolver,
867) {
868 const locateXcodeGit = yield* XcodeGitLocation;
869 const cache = yield* CommandResolutionCache;
870 const cacheKey = [
871 "xcode-git",
872 String(spawnResolverCacheId(resolveExecutable)),
873 String(spawnResolverCacheId(locateXcodeGit)),
874 resolvePathEnvironmentVariable(env),
875 env.DEVELOPER_DIR ?? "",
876 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
877 const nowNanos = yield* Clock.currentTimeNanos;
878 const cached = cache.get(cacheKey);
879 // An Xcode update or removal deletes the binary; look again instead of failing the spawn.
880 if (
881 cached !== undefined &&
882 cached.expiresAtNanos > nowNanos &&
883 (cached.resolvedPath === null ||
884 resolveExecutable(cached.resolvedPath, "darwin", env) !== undefined)
885 ) {
886 return cached.resolvedPath ?? "git";
887 }
888 const located =
889 resolveExecutable("git", "darwin", env) === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined;
890 const realGit =
891 located !== undefined && resolveExecutable(located, "darwin", env) !== undefined
892 ? located
893 : null;
894 cacheCommandResolution(cache, cacheKey, realGit, nowNanos);
895 return realGit ?? "git";
896});
897​
898export interface SpawnCommandOptions extends CommandAvailabilityOptions {
899 /** Bypass npm cmd-shims; see npmShimExecutable for process-lifetime semantics. */
900 readonly bypassNpmShim?: boolean;
902​
903// `*` is one argument that is not an option. These forms read refs or config
904// only, so git starts no hook, helper, pager, editor or lazy fetch for them.
905const CONSOLE_FREE_GIT_READS = [
906 "rev-parse --git-path index",
907 "rev-parse --git-common-dir",
908 "rev-parse --show-toplevel",
909 "rev-parse --symbolic-full-name HEAD",
910 "rev-parse --abbrev-ref --symbolic-full-name @{upstream}",
911 "symbolic-ref --quiet HEAD",
912 "symbolic-ref *",
913 "remote",
914 "remote get-url *",
915 "remote get-url -- *",
916 "config --get *",
917].map((form) => form.split(" "));
918​
919export function runsGitWithoutConsole(
920 platform: NodeJS.Platform,
921 executable: string,
922 args: ReadonlyArray<string>,
923): boolean {
924 if (platform !== "win32") return false;
925 const { basename, dirname } = NodePath.win32;
926 const bin = dirname(executable);
927 const build = basename(dirname(bin)).toLowerCase();
928 if (basename(executable).toLowerCase() !== "git.exe" || basename(bin).toLowerCase() !== "bin") {
929 return false;
930 }
931 if (!GIT_FOR_WINDOWS_BUILDS.some((candidate) => candidate === build)) return false;
932 const rest =
933 args[0] === "--git-dir" && args[1] !== undefined && !args[1].startsWith("-")
934 ? args.slice(2)
935 : args;
936 return CONSOLE_FREE_GIT_READS.some(
937 (form) =>
938 form.length === rest.length &&
939 form.every((part, i) => part === rest[i] || (part === "*" && !rest[i]!.startsWith("-"))),
940 );
942​
943export const resolveSpawnCommand = Effect.fnUntraced(function* (
944 command: string,
945 args: ReadonlyArray<string>,
946 options: SpawnCommandOptions = {},
947): Effect.fn.Return<ResolvedSpawnCommand> {
948 const platform = yield* HostProcess.Platform;
949 const isMacosGit = platform === "darwin" && command === "git";
950 if (platform !== "win32" && !isMacosGit) {
951 return { command, args: [...args], shell: false };
952 }
953​
954 const hostEnvironment = yield* HostProcess.Environment;
955 const env =
956 options.env === undefined
957 ? hostEnvironment
958 : options.extendEnv
959 ? { ...hostEnvironment, ...options.env }
960 : options.env;
961 const resolveExecutable = yield* SpawnExecutableResolution;
962 if (isMacosGit) {
963 return {
964 command: yield* resolveMacosGit(env, resolveExecutable),
965 args: [...args],
966 shell: false,
967 };
968 }
969 // The scan is synchronous and runs before every child process, so it shares
970 // the PATH scan cache above. Explicit paths stay uncached for the same reason,
971 // and so do misses: a failed spawn is how providers report "not installed",
972 // and that has to clear the moment the binary appears.
973 const explicitPath = command.includes("/") || command.includes("\\");
974 const cache = yield* CommandResolutionCache;
975 const cacheKey = [
976 "spawn",
977 String(spawnResolverCacheId(resolveExecutable)),
978 platform,
979 resolvePathEnvironmentVariable(env),
980 resolveWindowsPathExtensions(env).join(";"),
981 env.MSYSTEM ? "msystem" : "",
982 command,
983 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
984 const nowNanos = yield* Clock.currentTimeNanos;
985 const cached = explicitPath ? undefined : cache.get(cacheKey);
986 let resolvedExecutable: string | null;
987 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
988 resolvedExecutable = cached.resolvedPath;
989 } else {
990 const found = resolveExecutable(command, platform, env);
991 resolvedExecutable = found === undefined ? null : preferGitForWindowsBinary(found, env);
992 if (!explicitPath && resolvedExecutable !== null) {
993 cacheCommandResolution(cache, cacheKey, resolvedExecutable, nowNanos);
994 }
995 }
996 const resolvedCommand = resolvedExecutable ?? command;
997 const extension = NodePath.win32.extname(resolvedCommand).toLowerCase();
998 if (extension !== ".cmd" && extension !== ".bat") {
999 return { command: resolvedCommand, args: [...args], shell: false };
1001 const shimExecutable = options.bypassNpmShim ? npmShimExecutable(resolvedCommand) : undefined;
1002 if (shimExecutable !== undefined) {
1003 return { command: shimExecutable, args: [...args], shell: false };
1005​
1006 // Build the escaped command line without separate args to avoid Node DEP0190 with shell:true.
1007 return {
1008 command: [resolvedCommand, ...args].map(escapeWindowsShellArg).join(" "),
1009 args: [],
1010 shell: true,
1011 };
1012});
1013​
1014export const isCommandAvailable = Effect.fn("shell.isCommandAvailable")(function* (
1015 command: string,
1016 options: CommandAvailabilityOptions = {},
1017) {
1018 return (yield* resolveCommandPath(command, options)) !== null;
1019});
1020​
1021function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
1022 const appData = env.APPDATA?.trim();
1023 const localAppData = env.LOCALAPPDATA?.trim();
1024 const userProfile = env.USERPROFILE?.trim();
1025​
1026 return [
1027 ...(appData ? [`${appData}\\npm`] : []),
1028 ...(localAppData ? [`${localAppData}\\Programs\\nodejs`, `${localAppData}\\Volta\\bin`] : []),
1029 ...(localAppData ? [`${localAppData}\\pnpm`] : []),
1030 ...(userProfile
1031 ? [`${userProfile}\\.local\\bin`, `${userProfile}\\.bun\\bin`, `${userProfile}\\scoop\\shims`]
1032 : []),
1033 ];
1035​
1036/** Keep one PATH spelling in copied Windows environment records. */
1037export function setWindowsPath(env: NodeJS.ProcessEnv, value: string | null): void {
1038 for (const key of Object.keys(env)) {
1039 if (key.toUpperCase() === "PATH") {
1040 delete env[key];
1043 if (value !== null) env.PATH = value;
1045​
1046function mergeWindowsEnv(
1047 currentEnv: NodeJS.ProcessEnv,
1048 patch: Partial<Record<string, string>>,
1049): NodeJS.ProcessEnv {
1050 const nextEnv: NodeJS.ProcessEnv = { ...currentEnv };
1051 for (const [key, value] of Object.entries(patch)) {
1052 if (value === undefined) continue;
1053 if (key === "PATH") {
1054 setWindowsPath(nextEnv, value);
1055 } else {
1056 nextEnv[key] = value;
1059 return nextEnv;
1061​
1062export const resolveWindowsEnvironment = Effect.fn("shell.resolveWindowsEnvironment")(function* (
1063 env: NodeJS.ProcessEnv,
1064): Effect.fn.Return<Partial<NodeJS.ProcessEnv>, never, FileSystem.FileSystem | Path.Path> {
1065 const readEnvironment = yield* WindowsShellEnvironment;
1066 const commandAvailable = yield* CommandAvailability;
1067 const inheritedPath = readEnvPath(env);
1068 const shellPath = (yield* readEnvironment(["PATH"], { loadProfile: false })).PATH;
1069 const mergedPath = mergePathValues(shellPath, inheritedPath, "win32");
1070 const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);
1071 const baselinePath = mergePathValues(mergedPath, knownCliPath, "win32");
1072 const baselinePatch: Partial<NodeJS.ProcessEnv> = baselinePath ? { PATH: baselinePath } : {};
1073 const baselineEnv = mergeWindowsEnv(env, baselinePatch);
1074​
1075 if (yield* commandAvailable("node", { env: baselineEnv })) {
1076 return baselinePatch;
1078​
1079 const profiledEnvironment = yield* readEnvironment(["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"], {
1080 loadProfile: true,
1081 });
1082 const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, "win32");
1083 const profiledPatch: Partial<NodeJS.ProcessEnv> = {
1084 ...(profiledPath ? { PATH: profiledPath } : {}),
1085 ...(profiledEnvironment.FNM_DIR ? { FNM_DIR: profiledEnvironment.FNM_DIR } : {}),
1086 ...(profiledEnvironment.FNM_MULTISHELL_PATH
1087 ? { FNM_MULTISHELL_PATH: profiledEnvironment.FNM_MULTISHELL_PATH }
1088 : {}),
1089 };
1090 return Object.keys(profiledPatch).length > 0
1091 ? { ...baselinePatch, ...profiledPatch }
1092 : baselinePatch;
1093});
1094​
1095export function applyShellEnvironment(
1096 env: NodeJS.ProcessEnv,
1097 patch: ShellEnvironmentPatch,
1098 platform: NodeJS.Platform,
1099): void {
1100 for (const [key, value] of Object.entries(patch)) {
1101 if (key === "PATH" && platform === "win32") setWindowsPath(env, value);
1102 else if (value === null) delete env[key];
1103 else env[key] = value;
1106​
1107interface PathSetupInput {
1108 readonly directory: string;
1109 readonly home: string;
1110 readonly shell: string | undefined;
1111 readonly platform: NodeJS.Platform;
1112 /** `XDG_CONFIG_HOME`, where fish reads its startup file when set. */
1113 readonly configHome?: string | undefined;
1114 /** `ZDOTDIR`, where zsh reads `.zshrc` when set. */
1115 readonly zdotdir?: string | undefined;
1117​
1118/**
1119 * The startup file (`~/...`, or absolute under `configHome`) and line that put `directory` last on
1120 * 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
1121 * `%VAR%` entries), for other shells, macOS bash, or unsafe paths.
1122 */
1123export function pathSetup(
1124 input: PathSetupInput,
1125): { readonly file: string; readonly line: string } | undefined {
1126 // A relative folder on PATH would follow the working directory into any checkout.
1127 if (input.platform === "win32" || !input.directory.startsWith("/")) return undefined;
1128 const underHome = input.directory.startsWith(`${input.home}/`);
1129 const rest = underHome ? input.directory.slice(input.home.length) : input.directory;
1130 if (!/^[\w./-]+$/.test(rest)) return undefined;
1131 const directory = underHome ? `$HOME${rest}` : rest;
1132 const shell = input.shell?.split("/").pop();
1133 // A set folder the shell reads from replaces the default; one unsafe to write means no setup,
1134 // since the default file would never be read.
1135 const readFrom = (value: string | undefined, fallback: string) =>
1136 !value ? fallback : value.startsWith("/") && /^[\w./-]+$/.test(value) ? value : undefined;
1137 if (shell === "fish") {
1138 const configHome = readFrom(input.configHome, "~/.config");
1139 if (configHome === undefined) return undefined;
1140 // --path changes $PATH itself; fish_user_paths would go ahead of the system folders.
1141 return {
1142 file: `${configHome}/fish/config.fish`,
1143 line: `fish_add_path --append --path ${directory}`,
1144 };
1146 // macOS bash reads only the first of .bash_profile, .bash_login, and .profile; no file is safe.
1147 const zdotdir = readFrom(input.zdotdir, "~");
1148 const file =
1149 shell === "zsh"
1150 ? zdotdir && `${zdotdir}/.zshrc`
1151 : shell === "bash" && input.platform !== "darwin"
1152 ? "~/.bashrc"
1153 : undefined;
1154 return file === undefined ? undefined : { file, line: `export PATH="$PATH:${directory}"` };
1156​
1157/** A command to paste that does what {@link pathSetup} describes. */
1158export function pathSetupCommand(input: PathSetupInput): string | undefined {
1159 const setup = pathSetup(input);
1160 if (!setup) return undefined;
1161 // The leading newline keeps the line out of a final comment with no newline after it.
1162 const append = `printf '\\n%s\\n' '${setup.line}' >> ${setup.file}`;
1163 // fish's config folder may not exist yet; `&&` works in fish 3 too.
1164 return setup.file.endsWith(".fish")
1165 ? `mkdir -p ${setup.file.slice(0, setup.file.lastIndexOf("/"))} && ${append}`
1166 : append;