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

os-jank.ts

92 lines2.8 KB

1import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
2import {
3 listLoginShellCandidates,
4 mergePathEntries,
5 readPathFromLoginShell,
6 readPathFromLaunchctl,
7 resolveWindowsEnvironment,
8} from "@t3tools/shared/shell";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Path from "effect/Path";
12import * as NodeOS from "node:os";
13​
14function logPathHydrationWarning(message: string, error?: unknown): void {
15 process.stderr.write(
16 `[server] ${message} ${error instanceof Error ? error.message : (error ?? "")}\n`,
17 );
19​
20function hydratePosixPath(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): void {
21 let shellPath: string | undefined;
22 for (const shell of listLoginShellCandidates(platform, env.SHELL)) {
23 try {
24 shellPath = readPathFromLoginShell(shell);
25 } catch (error) {
26 logPathHydrationWarning(`Failed to read PATH from login shell ${shell}.`, error);
27 }
28​
29 if (shellPath) break;
30 }
31​
32 const launchctlPath = platform === "darwin" && !shellPath ? readPathFromLaunchctl() : undefined;
33 const mergedPath = mergePathEntries(shellPath ?? launchctlPath, env.PATH, platform);
34 if (mergedPath) {
35 env.PATH = mergedPath;
36 }
38​
39export const fixPath = Effect.fn("fixPath")(function* (): Effect.fn.Return<
40 void,
41 never,
42 FileSystem.FileSystem | Path.Path
43> {
44 const platform = yield* HostProcessPlatform;
45 const env = yield* HostProcessEnvironment;
46​
47 if (platform === "win32") {
48 const repairedEnvironment = yield* resolveWindowsEnvironment(env).pipe(
49 Effect.catchDefect((defect) =>
50 Effect.sync(() => {
51 logPathHydrationWarning("Failed to hydrate PATH from the user environment.", defect);
52 return {} as Partial<NodeJS.ProcessEnv>;
53 }),
54 ),
55 );
56 for (const [key, value] of Object.entries(repairedEnvironment)) {
57 if (value !== undefined) {
58 env[key] = value;
59 }
60 }
61 return;
62 }
63​
64 if (platform !== "darwin" && platform !== "linux") return;
65​
66 yield* Effect.sync(() => hydratePosixPath(env, platform)).pipe(
67 Effect.catchDefect((defect) =>
68 Effect.sync(() => {
69 logPathHydrationWarning("Failed to hydrate PATH from the user environment.", defect);
70 }),
71 ),
72 );
73});
74​
75export const expandHomePath = Effect.fn(function* (input: string) {
76 const { join } = yield* Path.Path;
77 if (input === "~") {
78 return NodeOS.homedir();
79 }
80 if (input.startsWith("~/") || input.startsWith("~\\")) {
81 return join(NodeOS.homedir(), input.slice(2));
82 }
83 return input;
84});
85​
86export const resolveBaseDir = Effect.fn(function* (raw: string | undefined) {
87 const { join, resolve } = yield* Path.Path;
88 if (!raw || raw.trim().length === 0) {
89 return join(NodeOS.homedir(), ".t3");
90 }
91 return resolve(yield* expandHomePath(raw.trim()));
92});