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

shell.ts

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