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

shell.ts

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