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

shell.ts

838 lines27.6 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 Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12​
13import * as HostProcess from "./HostProcess.ts";
14import * as Context from "effect/Context";
15const SHELL_ENV_NAME_PATTERN = /^[A-Z0-9_]+$/;
16const WINDOWS_PATH_DELIMITER = ";";
17const POSIX_PATH_DELIMITER = ":";
18const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
19​
20type ExecFileSyncLike = (
21 file: string,
22 args: ReadonlyArray<string>,
23 options: { encoding: "utf8"; timeout: number },
24) => string;
25​
26function canExecuteFile(filePath: string): boolean {
27 try {
28 NodeFS.accessSync(filePath, NodeFS.constants.X_OK);
29 return true;
30 } catch {
31 return false;
32 }
34​
35export interface CommandAvailabilityOptions {
36 readonly env?: NodeJS.ProcessEnv;
37 readonly extendEnv?: boolean;
39​
40export type CommandAvailabilityChecker = (
41 command: string,
42 options?: CommandAvailabilityOptions,
43) => Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path>;
44​
45const WINDOWS_SHELL_META_CHARS = /([()\][%!^"`<>&|;, *?])/g;
46​
47/**
48 * Node hands the command string to `cmd.exe /d /s /c "<command>"` without any
49 * quoting, so every dynamic argument must be escaped to survive both cmd.exe
50 * parsing and the target program's `CommandLineToArgvW` parsing.
51 */
52function escapeWindowsShellArg(arg: string): string {
53 let escaped = arg.replace(/(\\*)"/g, '$1$1\\"');
54 // Double up trailing backslashes so the closing quote is not escaped away.
55 escaped = escaped.replace(/(\\*)$/, "$1$1");
56 escaped = `"${escaped}"`;
57 return escaped.replace(WINDOWS_SHELL_META_CHARS, "^$1");
59​
60export interface ResolvedSpawnCommand {
61 readonly command: string;
62 readonly args: ReadonlyArray<string>;
63 readonly shell: boolean;
65​
66export type SpawnExecutableResolver = (
67 command: string,
68 platform: NodeJS.Platform,
69 env: NodeJS.ProcessEnv,
70) => string | undefined;
71​
72function resolveSpawnExecutableWithNode(
73 command: string,
74 platform: NodeJS.Platform,
75 env: NodeJS.ProcessEnv,
76): string | undefined {
77 const path = platform === "win32" ? NodePath.win32 : NodePath.posix;
78 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
79 const candidates = resolveCommandCandidates(
80 command,
81 platform,
82 windowsPathExtensions,
83 path.extname,
84 );
85 const isExecutable = (candidate: string) => {
86 try {
87 if (!NodeFS.statSync(candidate).isFile()) return false;
88 if (platform === "win32") {
89 return windowsPathExtensions.includes(path.extname(candidate).toUpperCase());
90 }
91 return canExecuteFile(candidate);
92 } catch {
93 return false;
94 }
95 };
96​
97 if (command.includes("/") || command.includes("\\")) {
98 return candidates.find(isExecutable);
99 }
100​
101 for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) {
102 const normalizedPathEntry = stripWrappingQuotes(pathEntry.trim());
103 if (normalizedPathEntry.length === 0) continue;
104 for (const candidate of candidates) {
105 const candidatePath = path.join(normalizedPathEntry, candidate);
106 if (isExecutable(candidatePath)) return candidatePath;
107 }
108 }
109 return undefined;
111​
112export const SpawnExecutableResolution = Context.Reference<SpawnExecutableResolver>(
113 "@t3tools/shared/shell/SpawnExecutableResolution",
114 {
115 defaultValue: () => resolveSpawnExecutableWithNode,
116 },
117);
118​
119export interface WindowsEnvironmentProbeOptions {
120 readonly loadProfile?: boolean;
122​
123function trimNonEmpty(value: string | null | undefined): string | undefined {
124 const trimmed = value?.trim();
125 return trimmed && trimmed.length > 0 ? trimmed : undefined;
127​
128function readUserLoginShell(): string | undefined {
129 try {
130 return trimNonEmpty(NodeOS.userInfo().shell);
131 } catch {
132 return undefined;
133 }
135​
136export function listLoginShellCandidates(
137 platform: NodeJS.Platform,
138 shell: string | undefined,
139 userShell = readUserLoginShell(),
140): ReadonlyArray<string> {
141 const fallbackShell =
142 platform === "darwin" ? "/bin/zsh" : platform === "linux" ? "/bin/bash" : undefined;
143 const seen = new Set<string>();
144 const candidates: string[] = [];
145​
146 for (const candidate of [trimNonEmpty(shell), trimNonEmpty(userShell), fallbackShell]) {
147 if (!candidate || seen.has(candidate)) {
148 continue;
149 }
150 seen.add(candidate);
151 candidates.push(candidate);
152 }
153​
154 return candidates;
156​
157export function readPathFromLaunchctl(
158 execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,
159): string | undefined {
160 try {
161 return trimNonEmpty(
162 execFile("/bin/launchctl", ["getenv", "PATH"], {
163 encoding: "utf8",
164 timeout: 2000,
165 }),
166 );
167 } catch {
168 return undefined;
169 }
171​
172export function mergePathEntries(
173 preferredPath: string | undefined,
174 inheritedPath: string | undefined,
175 platform: NodeJS.Platform,
176): string | undefined {
177 const delimiter = platform === "win32" ? ";" : ":";
178 const merged: string[] = [];
179 const seen = new Set<string>();
180​
181 for (const pathValue of [preferredPath, inheritedPath]) {
182 if (!pathValue) continue;
183 for (const entry of pathValue.split(delimiter)) {
184 const trimmedEntry = entry.trim();
185 if (!trimmedEntry || seen.has(trimmedEntry)) {
186 continue;
187 }
188 seen.add(trimmedEntry);
189 merged.push(trimmedEntry);
190 }
191 }
192​
193 return merged.length > 0 ? merged.join(delimiter) : undefined;
195​
196function envCaptureStart(name: string): string {
197 return `__T3CODE_ENV_${name}_START__`;
199​
200function envCaptureEnd(name: string): string {
201 return `__T3CODE_ENV_${name}_END__`;
203​
204function buildEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
205 return names
206 .map((name) => {
207 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
208 throw new Error(`Unsupported environment variable name: ${name}`);
209 }
210​
211 return [
212 `printf '%s\\n' '${envCaptureStart(name)}'`,
213 `printenv ${name} || true`,
214 `printf '%s\\n' '${envCaptureEnd(name)}'`,
215 ].join("; ");
216 })
217 .join("; ");
219​
220function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
221 return [
222 "$ErrorActionPreference = 'Stop'",
223 ...names.flatMap((name) => {
224 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
225 throw new Error(`Unsupported environment variable name: ${name}`);
226 }
227​
228 return [
229 `Write-Output '${envCaptureStart(name)}'`,
230 `$value = [Environment]::GetEnvironmentVariable('${name}')`,
231 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
232 `Write-Output '${envCaptureEnd(name)}'`,
233 ];
234 }),
235 ].join("; ");
237​
238function extractEnvironmentValue(output: string, name: string): string | undefined {
239 const startMarker = envCaptureStart(name);
240 const endMarker = envCaptureEnd(name);
241 const startIndex = output.indexOf(startMarker);
242 if (startIndex === -1) return undefined;
243​
244 const valueStartIndex = startIndex + startMarker.length;
245 const endIndex = output.indexOf(endMarker, valueStartIndex);
246 if (endIndex === -1) return undefined;
247​
248 const value = output
249 .slice(valueStartIndex, endIndex)
250 .replace(/^\r?\n/, "")
251 .replace(/\r?\n$/, "");
252​
253 return value.length > 0 ? value : undefined;
255​
256export type ShellEnvironmentReader = (
257 shell: string,
258 names: ReadonlyArray<string>,
259 execFile?: ExecFileSyncLike,
260) => Partial<Record<string, string>>;
261​
262export const readEnvironmentFromLoginShell: ShellEnvironmentReader = (
263 shell,
264 names,
265 execFile = NodeChildProcess.execFileSync,
266) => {
267 if (names.length === 0) {
268 return {};
269 }
270​
271 const output = execFile(shell, ["-ilc", buildEnvironmentCaptureCommand(names)], {
272 encoding: "utf8",
273 timeout: 5000,
274 });
275​
276 const environment: Partial<Record<string, string>> = {};
277 for (const name of names) {
278 const value = extractEnvironmentValue(output, name);
279 if (value !== undefined) {
280 environment[name] = value;
281 }
282 }
283​
284 return environment;
285};
286​
287export type WindowsShellEnvironmentReader = (
288 names: ReadonlyArray<string>,
289 options?: WindowsEnvironmentProbeOptions,
290) => Partial<Record<string, string>>;
291​
292export const WindowsShellEnvironment = Context.Reference<WindowsShellEnvironmentReader>(
293 "@t3tools/shared/shell/WindowsShellEnvironment",
294 {
295 defaultValue: () => readEnvironmentFromWindowsShell,
296 },
297);
298​
299export const CommandAvailability = Context.Reference<CommandAvailabilityChecker>(
300 "@t3tools/shared/shell/CommandAvailability",
301 {
302 defaultValue: () => isCommandAvailable,
303 },
304);
305​
306export function readEnvironmentFromWindowsShell(
307 names: ReadonlyArray<string>,
308 execFile?: ExecFileSyncLike,
309): Partial<Record<string, string>>;
310export function readEnvironmentFromWindowsShell(
311 names: ReadonlyArray<string>,
312 options?: WindowsEnvironmentProbeOptions,
313 execFile?: ExecFileSyncLike,
314): Partial<Record<string, string>>;
315export function readEnvironmentFromWindowsShell(
316 names: ReadonlyArray<string>,
317 optionsOrExecFile?: WindowsEnvironmentProbeOptions | ExecFileSyncLike,
318 maybeExecFile?: ExecFileSyncLike,
319): Partial<Record<string, string>> {
320 if (names.length === 0) {
321 return {};
322 }
323​
324 const options =
325 typeof optionsOrExecFile === "function"
326 ? ({} satisfies WindowsEnvironmentProbeOptions)
327 : (optionsOrExecFile ?? {});
328 const execFile: ExecFileSyncLike =
329 typeof optionsOrExecFile === "function"
330 ? optionsOrExecFile
331 : (maybeExecFile ?? (NodeChildProcess.execFileSync as ExecFileSyncLike));
332 const command = buildWindowsEnvironmentCaptureCommand(names);
333 const args = [
334 "-NoLogo",
335 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
336 "-NonInteractive",
337 "-Command",
338 command,
339 ];
340 for (const shell of WINDOWS_SHELL_CANDIDATES) {
341 try {
342 const output = execFile(shell, args, { encoding: "utf8", timeout: 5000 });
343​
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;
352 } catch {
353 continue;
354 }
355 }
356​
357 return {};
359​
360function stripWrappingQuotes(value: string): string {
361 return value.replace(/^"+|"+$/g, "");
363​
364function pathDelimiterForPlatform(platform: NodeJS.Platform): string {
365 return platform === "win32" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER;
367​
368function normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string {
369 const normalized = stripWrappingQuotes(entry.trim());
370 return platform === "win32" ? normalized.toLowerCase() : normalized;
372​
373function sanitizePathEntry(entry: string, platform: NodeJS.Platform): string {
374 return platform === "win32" ? entry.replaceAll('"', "") : entry;
376​
377export function mergePathValues(
378 preferredPath: string | undefined,
379 inheritedPath: string | undefined,
380 platform: NodeJS.Platform,
381): string | undefined {
382 const delimiter = pathDelimiterForPlatform(platform);
383 const merged: string[] = [];
384 const seen = new Set<string>();
385​
386 for (const rawValue of [preferredPath, inheritedPath]) {
387 if (!rawValue) continue;
388​
389 for (const entry of rawValue.split(delimiter)) {
390 const sanitized = sanitizePathEntry(entry.trim(), platform);
391 if (sanitized.length === 0) continue;
392​
393 const normalized = normalizePathEntryForComparison(sanitized, platform);
394 if (normalized.length === 0 || seen.has(normalized)) continue;
395​
396 seen.add(normalized);
397 merged.push(sanitized);
398 }
399 }
400​
401 return merged.length > 0 ? merged.join(delimiter) : undefined;
403​
404function readEnvPath(env: NodeJS.ProcessEnv): string | undefined {
405 return env.PATH ?? env.Path ?? env.path;
407​
408function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
409 return readEnvPath(env) ?? "";
411​
412function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
413 const rawValue = env.PATHEXT;
414 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
415 if (!rawValue) return fallback;
416​
417 const parsed: string[] = [];
418 for (const entry of rawValue.split(";")) {
419 const trimmed = entry.trim();
420 if (trimmed.length === 0) continue;
421 parsed.push(trimmed.startsWith(".") ? trimmed.toUpperCase() : `.${trimmed.toUpperCase()}`);
422 }
423 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
425​
426function resolveCommandCandidates(
427 command: string,
428 platform: NodeJS.Platform,
429 windowsPathExtensions: ReadonlyArray<string>,
430 extname: (path: string) => string,
431): ReadonlyArray<string> {
432 if (platform !== "win32") return [command];
433 const extension = extname(command);
434 const normalizedExtension = extension.toUpperCase();
435​
436 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
437 const commandWithoutExtension = command.slice(0, -extension.length);
438 return Array.from(
439 new Set([
440 command,
441 `${commandWithoutExtension}${normalizedExtension}`,
442 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
443 ]),
444 );
445 }
446​
447 const candidates: string[] = [];
448 for (const candidateExtension of windowsPathExtensions) {
449 candidates.push(`${command}${candidateExtension}`);
450 candidates.push(`${command}${candidateExtension.toLowerCase()}`);
451 }
452 return Array.from(new Set(candidates));
454​
455// Explicit-path resolution is never cached - callers probe paths they have
456// just written (e.g. managed binary installs). A "not-found" outcome is also
457// cached for the TTL, so a just-installed binary can stay invisible for up to
458// 30s unless resolved by explicit path.
459const COMMAND_RESOLUTION_CACHE_TTL_NANOS = 30_000_000_000n;
460const COMMAND_RESOLUTION_CACHE_MAX_ENTRIES = 512;
461const COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR = String.fromCharCode(0);
462​
463interface CommandResolutionCacheEntry {
464 readonly resolvedPath: string | null;
465 readonly expiresAtNanos: bigint;
467​
468export const CommandResolutionCache = Context.Reference<Map<string, CommandResolutionCacheEntry>>(
469 "@t3tools/shared/shell/CommandResolutionCache",
470 {
471 defaultValue: () => new Map(),
472 },
473);
474​
475interface PathDirectoryListing {
476 readonly modified: number | null | undefined;
477 readonly names: ReadonlySet<string> | undefined;
479​
480const directoryMtime = (directory: string) =>
481 FileSystem.FileSystem.use((fileSystem) => fileSystem.stat(directory)).pipe(
482 Effect.map((info) =>
483 info.type === "Directory" ? Option.getOrUndefined(info.mtime)?.getTime() : undefined,
484 ),
485 Effect.catch((error) => Effect.succeed(error.reason._tag === "NotFound" ? null : undefined)),
486 );
487​
488// Dated before it is read, so an entry added in between changes the mtime seen
489// on the next check. Without names, lookups probe candidates directly.
490const listPathDirectory = Effect.fnUntraced(function* (
491 directory: string,
492): Effect.fn.Return<PathDirectoryListing, never, FileSystem.FileSystem> {
493 const modified = yield* directoryMtime(directory);
494 if (modified == null) return { modified, names: modified === null ? new Set() : undefined };
495 const entries = yield* FileSystem.FileSystem.use((fileSystem) =>
496 fileSystem.readDirectory(directory),
497 ).pipe(Effect.orElseSucceed(() => undefined));
498 return { modified, names: entries && new Set(entries.map((entry) => entry.toLowerCase())) };
499});
500​
501const PathDirectoryListings = Context.Reference<
502 Cache.Cache<string, PathDirectoryListing, never, FileSystem.FileSystem> | undefined
503>("@t3tools/shared/shell/PathDirectoryListings", { defaultValue: () => undefined });
504​
505export const withPathDirectoryListings = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
506 Effect.gen(function* () {
507 const listings = yield* Cache.make({
508 capacity: 1024,
509 lookup: listPathDirectory,
510 requireServicesAt: "lookup",
511 });
512 return yield* effect.pipe(Effect.provideService(PathDirectoryListings, listings));
513 });
514​
515// An injected resolver may answer differently for the same search, so its
516// entries are kept apart from every other resolver's.
517let spawnResolverCacheIdCount = 0;
518const spawnResolverCacheIds = new WeakMap<SpawnExecutableResolver, number>();
519function spawnResolverCacheId(resolver: SpawnExecutableResolver): number {
520 const known = spawnResolverCacheIds.get(resolver);
521 if (known !== undefined) return known;
522 const id = spawnResolverCacheIdCount++;
523 spawnResolverCacheIds.set(resolver, id);
524 return id;
526​
527function cacheCommandResolution(
528 cache: Map<string, CommandResolutionCacheEntry>,
529 cacheKey: string,
530 resolvedPath: string | null,
531 nowNanos: bigint,
532): void {
533 if (cache.size >= COMMAND_RESOLUTION_CACHE_MAX_ENTRIES) {
534 const oldestKey = cache.keys().next().value;
535 if (oldestKey !== undefined) {
536 cache.delete(oldestKey);
537 }
538 }
539 cache.set(cacheKey, {
540 resolvedPath,
541 expiresAtNanos: nowNanos + COMMAND_RESOLUTION_CACHE_TTL_NANOS,
542 });
544​
545const isExecutableFile = Effect.fnUntraced(function* (
546 filePath: string,
547 platform: NodeJS.Platform,
548 windowsPathExtensions: ReadonlyArray<string>,
549): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
550 const fileSystem = yield* FileSystem.FileSystem;
551 const path = yield* Path.Path;
552 const stat = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
553 if (stat === null || stat.type !== "File") return false;
554​
555 if (platform === "win32") {
556 const extension = path.extname(filePath);
557 if (extension.length === 0) return false;
558 return windowsPathExtensions.includes(extension.toUpperCase());
559 }
560​
561 return canExecuteFile(filePath);
562});
563​
564const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlatform")(function* (
565 command: string,
566 options: CommandAvailabilityOptions & { readonly platform: NodeJS.Platform },
567): Effect.fn.Return<string | null, never, FileSystem.FileSystem | Path.Path> {
568 const path = yield* Path.Path;
569 const platform = options.platform;
570 const env = options.env ?? process.env;
571 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
572 const commandCandidates = resolveCommandCandidates(
573 command,
574 platform,
575 windowsPathExtensions,
576 path.extname,
577 );
578​
579 if (command.includes("/") || command.includes("\\")) {
580 for (const candidate of commandCandidates) {
581 if (yield* isExecutableFile(candidate, platform, windowsPathExtensions)) {
582 return candidate;
583 }
584 }
585 return null;
586 }
587​
588 const pathValue = resolvePathEnvironmentVariable(env);
589 if (pathValue.length === 0) {
590 return null;
591 }
592​
593 const cacheKey = [platform, pathValue, windowsPathExtensions.join(";"), command].join(
594 COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR,
595 );
596 const cache = yield* CommandResolutionCache;
597 const nowNanos = yield* Clock.monotonicTimeNanos;
598 const cached = cache.get(cacheKey);
599 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
600 return cached.resolvedPath;
601 }
602​
603 // Keep case variants: Windows can make PATH directories case-sensitive.
604 const pathEntries: string[] = [];
605 const seenPathEntries = new Set<string>();
606 for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) {
607 const pathEntry = stripWrappingQuotes(entry.trim());
608 if (pathEntry.length === 0 || seenPathEntries.has(pathEntry)) continue;
609​
610 seenPathEntries.add(pathEntry);
611 pathEntries.push(pathEntry);
612 }
613​
614 const listings = yield* PathDirectoryListings;
615 for (const pathEntry of pathEntries) {
616 let listing = listings && (yield* Cache.get(listings, pathEntry));
617 if (listings && listing?.names && listing.modified !== (yield* directoryMtime(pathEntry))) {
618 yield* Cache.invalidate(listings, pathEntry);
619 listing = yield* Cache.get(listings, pathEntry);
620 }
621 for (const candidate of commandCandidates) {
622 if (listing?.names && !listing.names.has(candidate.toLowerCase())) continue;
623 const candidatePath = path.join(pathEntry, candidate);
624 if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) {
625 cacheCommandResolution(cache, cacheKey, candidatePath, nowNanos);
626 return candidatePath;
627 }
628 }
629 }
630 cacheCommandResolution(cache, cacheKey, null, nowNanos);
631 return null;
632});
633​
634export const resolveCommandPath = Effect.fn("shell.resolveCommandPath")(function* (
635 command: string,
636 options: CommandAvailabilityOptions = {},
637) {
638 return yield* resolveCommandPathForPlatform(command, {
639 env: options.env ?? (yield* HostProcess.Environment),
640 platform: yield* HostProcess.Platform,
641 });
642});
643​
644// Git for Windows 2.56 moved x64 builds from mingw64 to ucrt64; ARM64 builds
645// live in clangarm64 and 32-bit ones in mingw32.
646const GIT_FOR_WINDOWS_BUILDS = ["ucrt64", "clangarm64", "mingw64", "mingw32"] as const;
647​
648function isFileSync(filePath: string): boolean {
649 try {
650 return NodeFS.statSync(filePath).isFile();
651 } catch {
652 return false;
653 }
655​
656/**
657 * The launcher costs a second process on every git command, and each launch
658 * leaks a kernel token reference that slows process creation machine-wide until
659 * reboot. The real binary sets HOME itself, but adds its own folders to PATH
660 * for hooks, ssh and credential helpers only when MSYSTEM is unset, so the
661 * launcher stays when MSYSTEM is set.
662 */
663export function preferGitForWindowsBinary(
664 executable: string,
665 env: NodeJS.ProcessEnv,
666 isFile: (filePath: string) => boolean = isFileSync,
667): string {
668 if (env.MSYSTEM) return executable;
669 const path = NodePath.win32;
670 if (path.basename(executable).toLowerCase() !== "git.exe") return executable;
671 const launcherDirectory = path.dirname(executable);
672 const launcherFolder = path.basename(launcherDirectory).toLowerCase();
673 if (launcherFolder !== "cmd" && launcherFolder !== "bin") return executable;
674 const installRoot = path.dirname(launcherDirectory);
675 for (const build of GIT_FOR_WINDOWS_BUILDS) {
676 const candidate = path.join(installRoot, build, "bin", "git.exe");
677 if (isFile(candidate)) return candidate;
678 }
679 return executable;
681​
682export const resolveSpawnCommand = Effect.fnUntraced(function* (
683 command: string,
684 args: ReadonlyArray<string>,
685 options: CommandAvailabilityOptions = {},
686): Effect.fn.Return<ResolvedSpawnCommand> {
687 const platform = yield* HostProcess.Platform;
688 if (platform !== "win32") {
689 return { command, args: [...args], shell: false };
690 }
691​
692 const hostEnvironment = yield* HostProcess.Environment;
693 const env =
694 options.env === undefined
695 ? hostEnvironment
696 : options.extendEnv
697 ? { ...hostEnvironment, ...options.env }
698 : options.env;
699 const resolveExecutable = yield* SpawnExecutableResolution;
700 // The scan is synchronous and runs before every child process, so it shares
701 // the PATH scan cache above. Explicit paths stay uncached for the same reason,
702 // and so do misses: a failed spawn is how providers report "not installed",
703 // and that has to clear the moment the binary appears.
704 const explicitPath = command.includes("/") || command.includes("\\");
705 const cache = yield* CommandResolutionCache;
706 const cacheKey = [
707 "spawn",
708 String(spawnResolverCacheId(resolveExecutable)),
709 platform,
710 resolvePathEnvironmentVariable(env),
711 resolveWindowsPathExtensions(env).join(";"),
712 env.MSYSTEM ? "msystem" : "",
713 command,
714 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
715 const nowNanos = yield* Clock.currentTimeNanos;
716 const cached = explicitPath ? undefined : cache.get(cacheKey);
717 let resolvedExecutable: string | null;
718 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
719 resolvedExecutable = cached.resolvedPath;
720 } else {
721 const found = resolveExecutable(command, platform, env);
722 resolvedExecutable = found === undefined ? null : preferGitForWindowsBinary(found, env);
723 if (!explicitPath && resolvedExecutable !== null) {
724 cacheCommandResolution(cache, cacheKey, resolvedExecutable, nowNanos);
725 }
726 }
727 const resolvedCommand = resolvedExecutable ?? command;
728 const extension = NodePath.win32.extname(resolvedCommand).toLowerCase();
729 if (extension !== ".cmd" && extension !== ".bat") {
730 return { command: resolvedCommand, args: [...args], shell: false };
731 }
732​
733 // Node runs a shell spawn as `cmd.exe /d /s /c "<command> <args...>"`, but
734 // passing args with `shell: true` prints DEP0190. Build the same escaped line
735 // here and pass no args.
736 return {
737 command: [resolvedCommand, ...args].map(escapeWindowsShellArg).join(" "),
738 args: [],
739 shell: true,
740 };
741});
742​
743export const isCommandAvailable = Effect.fn("shell.isCommandAvailable")(function* (
744 command: string,
745 options: CommandAvailabilityOptions = {},
746) {
747 return (yield* resolveCommandPath(command, options)) !== null;
748});
749​
750export function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
751 const appData = env.APPDATA?.trim();
752 const localAppData = env.LOCALAPPDATA?.trim();
753 const userProfile = env.USERPROFILE?.trim();
754​
755 return [
756 ...(appData ? [`${appData}\\npm`] : []),
757 ...(localAppData ? [`${localAppData}\\Programs\\nodejs`, `${localAppData}\\Volta\\bin`] : []),
758 ...(localAppData ? [`${localAppData}\\pnpm`] : []),
759 ...(userProfile
760 ? [`${userProfile}\\.local\\bin`, `${userProfile}\\.bun\\bin`, `${userProfile}\\scoop\\shims`]
761 : []),
762 ];
764​
765function readWindowsEnvironmentSafely(
766 readEnvironment: WindowsShellEnvironmentReader,
767 names: ReadonlyArray<string>,
768 options?: WindowsEnvironmentProbeOptions,
769): Partial<Record<string, string>> {
770 try {
771 return readEnvironment(names, options);
772 } catch {
773 return {};
774 }
776​
777/** Keep one PATH spelling in copied Windows environment records. */
778export function setWindowsPath(env: NodeJS.ProcessEnv, value: string): void {
779 for (const key of Object.keys(env)) {
780 if (key.toUpperCase() === "PATH") {
781 delete env[key];
782 }
783 }
784 env.PATH = value;
786​
787function mergeWindowsEnv(
788 currentEnv: NodeJS.ProcessEnv,
789 patch: Partial<Record<string, string>>,
790): NodeJS.ProcessEnv {
791 const nextEnv: NodeJS.ProcessEnv = { ...currentEnv };
792 for (const [key, value] of Object.entries(patch)) {
793 if (value === undefined) continue;
794 if (key === "PATH") {
795 setWindowsPath(nextEnv, value);
796 } else {
797 nextEnv[key] = value;
798 }
799 }
800 return nextEnv;
802​
803export const resolveWindowsEnvironment = Effect.fn("shell.resolveWindowsEnvironment")(function* (
804 env: NodeJS.ProcessEnv,
805): Effect.fn.Return<Partial<NodeJS.ProcessEnv>, never, FileSystem.FileSystem | Path.Path> {
806 const readEnvironment = yield* WindowsShellEnvironment;
807 const commandAvailable = yield* CommandAvailability;
808 const inheritedPath = readEnvPath(env);
809 const shellPath = readWindowsEnvironmentSafely(readEnvironment, ["PATH"], {
810 loadProfile: false,
811 }).PATH;
812 const mergedPath = mergePathValues(shellPath, inheritedPath, "win32");
813 const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);
814 const baselinePath = mergePathValues(mergedPath, knownCliPath, "win32");
815 const baselinePatch: Partial<NodeJS.ProcessEnv> = baselinePath ? { PATH: baselinePath } : {};
816 const baselineEnv = mergeWindowsEnv(env, baselinePatch);
817​
818 if (yield* commandAvailable("node", { env: baselineEnv })) {
819 return baselinePatch;
820 }
821​
822 const profiledEnvironment = readWindowsEnvironmentSafely(
823 readEnvironment,
824 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
825 { loadProfile: true },
826 );
827 const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, "win32");
828 const profiledPatch: Partial<NodeJS.ProcessEnv> = {
829 ...(profiledPath ? { PATH: profiledPath } : {}),
830 ...(profiledEnvironment.FNM_DIR ? { FNM_DIR: profiledEnvironment.FNM_DIR } : {}),
831 ...(profiledEnvironment.FNM_MULTISHELL_PATH
832 ? { FNM_MULTISHELL_PATH: profiledEnvironment.FNM_MULTISHELL_PATH }
833 : {}),
834 };
835 return Object.keys(profiledPatch).length > 0
836 ? { ...baselinePatch, ...profiledPatch }
837 : baselinePatch;
838});