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