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

shell.ts

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