Open History to see the last commit
1import * as OS from "node:os";
2import { execFileSync } from "node:child_process";
3
4const PATH_CAPTURE_START = "__T3CODE_PATH_START__";
5const PATH_CAPTURE_END = "__T3CODE_PATH_END__";
6const SHELL_ENV_NAME_PATTERN = /^[A-Z0-9_]+$/;
7
8type ExecFileSyncLike = (
9 file: string,
10 args: ReadonlyArray<string>,
11 options: { encoding: "utf8"; timeout: number },
12) => string;
13
14function trimNonEmpty(value: string | null | undefined): string | undefined {
15 const trimmed = value?.trim();
16 return trimmed && trimmed.length > 0 ? trimmed : undefined;
17}
18
19function readUserLoginShell(): string | undefined {
20 try {
21 return trimNonEmpty(OS.userInfo().shell);
22 } catch {
23 return undefined;
24 }
25}
26
27export function listLoginShellCandidates(
28 platform: NodeJS.Platform,
29 shell: string | undefined,
30 userShell = readUserLoginShell(),
31): ReadonlyArray<string> {
32 const fallbackShell =
33 platform === "darwin" ? "/bin/zsh" : platform === "linux" ? "/bin/bash" : undefined;
34 const seen = new Set<string>();
35 const candidates: string[] = [];
36
37 for (const candidate of [trimNonEmpty(shell), trimNonEmpty(userShell), fallbackShell]) {
38 if (!candidate || seen.has(candidate)) {
39 continue;
40 }
41 seen.add(candidate);
42 candidates.push(candidate);
43 }
44
45 return candidates;
46}
47
48export function extractPathFromShellOutput(output: string): string | null {
49 const startIndex = output.indexOf(PATH_CAPTURE_START);
50 if (startIndex === -1) return null;
51
52 const valueStartIndex = startIndex + PATH_CAPTURE_START.length;
53 const endIndex = output.indexOf(PATH_CAPTURE_END, valueStartIndex);
54 if (endIndex === -1) return null;
55
56 const pathValue = output.slice(valueStartIndex, endIndex).trim();
57 return pathValue.length > 0 ? pathValue : null;
58}
59
60export function readPathFromLoginShell(
61 shell: string,
62 execFile: ExecFileSyncLike = execFileSync,
63): string | undefined {
64 return readEnvironmentFromLoginShell(shell, ["PATH"], execFile).PATH;
65}
66
67export function readPathFromLaunchctl(
68 execFile: ExecFileSyncLike = execFileSync,
69): string | undefined {
70 try {
71 return trimNonEmpty(
72 execFile("/bin/launchctl", ["getenv", "PATH"], {
73 encoding: "utf8",
74 timeout: 2000,
75 }),
76 );
77 } catch {
78 return undefined;
79 }
80}
81
82export function mergePathEntries(
83 preferredPath: string | undefined,
84 inheritedPath: string | undefined,
85 platform: NodeJS.Platform,
86): string | undefined {
87 const delimiter = platform === "win32" ? ";" : ":";
88 const merged: string[] = [];
89 const seen = new Set<string>();
90
91 for (const pathValue of [preferredPath, inheritedPath]) {
92 if (!pathValue) continue;
93 for (const entry of pathValue.split(delimiter)) {
94 const trimmedEntry = entry.trim();
95 if (!trimmedEntry || seen.has(trimmedEntry)) {
96 continue;
97 }
98 seen.add(trimmedEntry);
99 merged.push(trimmedEntry);
100 }
101 }
102
103 return merged.length > 0 ? merged.join(delimiter) : undefined;
104}
105
106function envCaptureStart(name: string): string {
107 return `__T3CODE_ENV_${name}_START__`;
108}
109
110function envCaptureEnd(name: string): string {
111 return `__T3CODE_ENV_${name}_END__`;
112}
113
114function buildEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
115 return names
116 .map((name) => {
117 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
118 throw new Error(`Unsupported environment variable name: ${name}`);
119 }
120
121 return [
122 `printf '%s\\n' '${envCaptureStart(name)}'`,
123 `printenv ${name} || true`,
124 `printf '%s\\n' '${envCaptureEnd(name)}'`,
125 ].join("; ");
126 })
127 .join("; ");
128}
129
130function extractEnvironmentValue(output: string, name: string): string | undefined {
131 const startMarker = envCaptureStart(name);
132 const endMarker = envCaptureEnd(name);
133 const startIndex = output.indexOf(startMarker);
134 if (startIndex === -1) return undefined;
135
136 const valueStartIndex = startIndex + startMarker.length;
137 const endIndex = output.indexOf(endMarker, valueStartIndex);
138 if (endIndex === -1) return undefined;
139
140 let value = output.slice(valueStartIndex, endIndex);
141 if (value.startsWith("\n")) {
142 value = value.slice(1);
143 }
144 if (value.endsWith("\n")) {
145 value = value.slice(0, -1);
146 }
147
148 return value.length > 0 ? value : undefined;
149}
150
151export type ShellEnvironmentReader = (
152 shell: string,
153 names: ReadonlyArray<string>,
154 execFile?: ExecFileSyncLike,
155) => Partial<Record<string, string>>;
156
157export const readEnvironmentFromLoginShell: ShellEnvironmentReader = (
158 shell,
159 names,
160 execFile = execFileSync,
161) => {
162 if (names.length === 0) {
163 return {};
164 }
165
166 const output = execFile(shell, ["-ilc", buildEnvironmentCaptureCommand(names)], {
167 encoding: "utf8",
168 timeout: 5000,
169 });
170
171 const environment: Partial<Record<string, string>> = {};
172 for (const name of names) {
173 const value = extractEnvironmentValue(output, name);
174 if (value !== undefined) {
175 environment[name] = value;
176 }
177 }
178
179 return environment;
180};