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

syncShellEnvironment.ts

79 lines2.4 KB

1import {
2 listLoginShellCandidates,
3 mergePathEntries,
4 readPathFromLaunchctl,
5 readEnvironmentFromLoginShell,
6 ShellEnvironmentReader,
7} from "@t3tools/shared/shell";
8​
9const LOGIN_SHELL_ENV_NAMES = [
10 "PATH",
11 "SSH_AUTH_SOCK",
12 "HOMEBREW_PREFIX",
13 "HOMEBREW_CELLAR",
14 "HOMEBREW_REPOSITORY",
15 "XDG_CONFIG_HOME",
16 "XDG_DATA_HOME",
17] as const;
18​
19function logShellEnvironmentWarning(message: string, error?: unknown): void {
20 console.warn(`[desktop] ${message}`, error instanceof Error ? error.message : (error ?? ""));
22​
23export function syncShellEnvironment(
24 env: NodeJS.ProcessEnv = process.env,
25 options: {
26 platform?: NodeJS.Platform;
27 readEnvironment?: ShellEnvironmentReader;
28 readLaunchctlPath?: typeof readPathFromLaunchctl;
29 userShell?: string;
30 logWarning?: (message: string, error?: unknown) => void;
31 } = {},
32): void {
33 const platform = options.platform ?? process.platform;
34 if (platform !== "darwin" && platform !== "linux") return;
35​
36 const logWarning = options.logWarning ?? logShellEnvironmentWarning;
37 const readEnvironment = options.readEnvironment ?? readEnvironmentFromLoginShell;
38 const shellEnvironment: Partial<Record<string, string>> = {};
39​
40 try {
41 for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
42 try {
43 Object.assign(shellEnvironment, readEnvironment(shell, LOGIN_SHELL_ENV_NAMES));
44 if (shellEnvironment.PATH) {
45 break;
46 }
47 } catch (error) {
48 logWarning(`Failed to read login shell environment from ${shell}.`, error);
49 }
50 }
51​
52 const launchctlPath =
53 platform === "darwin" && !shellEnvironment.PATH
54 ? (options.readLaunchctlPath ?? readPathFromLaunchctl)()
55 : undefined;
56 const mergedPath = mergePathEntries(shellEnvironment.PATH ?? launchctlPath, env.PATH, platform);
57 if (mergedPath) {
58 env.PATH = mergedPath;
59 }
60​
61 if (!env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
62 env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
63 }
64​
65 for (const name of [
66 "HOMEBREW_PREFIX",
67 "HOMEBREW_CELLAR",
68 "HOMEBREW_REPOSITORY",
69 "XDG_CONFIG_HOME",
70 "XDG_DATA_HOME",
71 ] as const) {
72 if (!env[name] && shellEnvironment[name]) {
73 env[name] = shellEnvironment[name];
74 }
75 }
76 } catch (error) {
77 logWarning("Failed to synchronize the desktop shell environment.", error);
78 }