Skip to content

Commit 2fcefc9

Browse files
fix(shared): hydrate Nushell environments in CLI and desktop (pingdotgg#7894)
Co-authored-by: Julius Marminge <[email protected]>
1 parent 26a88af commit 2fcefc9

4 files changed

Lines changed: 170 additions & 20 deletions

File tree

‎apps/desktop/src/shell/DesktopShellEnvironment.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// @effect-diagnostics nodeBuiltinImport:off -- The process fixture runs real shell commands with isolated config files.
12
import * as NodeServices from "@effect/platform-node/NodeServices";
23
import * as Clock from "effect/Clock";
34
import { assert, describe, it } from "@effect/vitest";
@@ -12,8 +13,11 @@ import * as Sink from "effect/Sink";
1213
import * as Stream from "effect/Stream";
1314
import * as ChildProcess from "effect/process/ChildProcess";
1415
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
16+
import * as NodeChildProcess from "node:child_process";
17+
import * as NodeFS from "node:fs";
1518
import * as TestClock from "effect/testing/TestClock";
1619
import * as NodeOS from "node:os";
20+
import * as NodePath from "node:path";
1721
import { vi } from "vite-plus/test";
1822

1923
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
@@ -130,6 +134,77 @@ function runShellEnvironment(input: {
130134
}
131135

132136
describe("DesktopShellEnvironment", () => {
137+
// Explicit opt-in keeps real shell coverage independent of globally installed tools.
138+
it.effect.runIf(process.env.T3_TEST_NU_PATH !== undefined)(
139+
"hydrates the desktop through a renamed Nushell symlink with native export conversions",
140+
() =>
141+
Effect.gen(function* () {
142+
const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-desktop-nu-"));
143+
try {
144+
const toolPath = NodePath.join(home, "nu tools", "bin");
145+
const extraToolPath = NodePath.join(home, "extra-tools", "bin");
146+
const convertedToolPath = NodePath.join(home, "converted-tools", "bin");
147+
NodeFS.mkdirSync(toolPath, { recursive: true });
148+
NodeFS.mkdirSync(extraToolPath, { recursive: true });
149+
NodeFS.mkdirSync(convertedToolPath, { recursive: true });
150+
const shell = NodePath.join(toolPath, "nushell");
151+
NodeFS.symlinkSync(process.env.T3_TEST_NU_PATH!, shell);
152+
const config = NodePath.join(home, "config.nu");
153+
const envConfig = NodePath.join(home, "env.nu");
154+
NodeFS.writeFileSync(envConfig, "");
155+
NodeFS.writeFileSync(
156+
config,
157+
[
158+
`$env.PATH = [${JSON.stringify(toolPath)}, ${JSON.stringify(extraToolPath)}]`,
159+
'$env.SSH_AUTH_SOCK = "/tmp/nu-agent.sock"',
160+
'$env.__MISE_DIFF = " first\\nsecond "',
161+
'$env.HOMEBREW_PREFIX = ""',
162+
"$env.ENV_CONVERSIONS = {",
163+
" PATH: {",
164+
" from_string: {|value| $value | split row (char esep) },",
165+
' to_string: {|value| $value | str join (char esep) | str replace "nu tools" "converted-tools" }',
166+
" },",
167+
" __MISE_DIFF: { from_string: {|value| $value }, to_string: { str upcase } }",
168+
"}",
169+
'print "startup noise"',
170+
].join("\n"),
171+
);
172+
const env: NodeJS.ProcessEnv = { SHELL: shell, PATH: `/inherited/bin:${extraToolPath}` };
173+
yield* runShellEnvironment({
174+
env,
175+
platform: "linux",
176+
handler: (command) => {
177+
if (command._tag !== "StandardCommand" || command.command !== shell) return "";
178+
const result = NodeChildProcess.spawnSync(
179+
command.command,
180+
["--no-history", "--config", config, "--env-config", envConfig, ...command.args],
181+
{
182+
encoding: "utf8",
183+
timeout: 5000,
184+
env: { HOME: home, XDG_CONFIG_HOME: home, PATH: toolPath },
185+
},
186+
);
187+
if (result.error) throw result.error;
188+
return { output: result.stdout, exitCode: result.status ?? 1 };
189+
},
190+
});
191+
192+
assert.deepEqual(
193+
{ PATH: env.PATH, __MISE_DIFF: env.__MISE_DIFF },
194+
{
195+
PATH: `${convertedToolPath}:${extraToolPath}:/inherited/bin`,
196+
__MISE_DIFF: " FIRST\nSECOND ",
197+
},
198+
);
199+
assert.equal(env.SSH_AUTH_SOCK, "/tmp/nu-agent.sock");
200+
assert.isUndefined(env.DISPLAY);
201+
assert.isUndefined(env.HOMEBREW_PREFIX);
202+
} finally {
203+
NodeFS.rmSync(home, { recursive: true, force: true });
204+
}
205+
}),
206+
);
207+
133208
it.effect("rejects PATH output from a failed shell and tries the next candidate", () =>
134209
Effect.gen(function* () {
135210
const env: NodeJS.ProcessEnv = { SHELL: "/bin/failing", PATH: "/usr/bin" };

‎apps/desktop/src/shell/DesktopShellEnvironment.ts‎

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
import { listLoginShellCandidates, setWindowsPath } from "@t3tools/shared/shell";
1+
import {
2+
buildEnvironmentCaptureCommand,
3+
listLoginShellCandidates,
4+
setWindowsPath,
5+
} from "@t3tools/shared/shell";
26
import * as Clock from "effect/Clock";
37
import * as Context from "effect/Context";
48
import * as Duration from "effect/Duration";
@@ -231,17 +235,6 @@ const logShellEnvironmentCommandError = (
231235
}),
232236
);
233237

234-
const capturePosixEnvironmentCommand = (names: ReadonlyArray<string>) =>
235-
names
236-
.map((name) => {
237-
return [
238-
`printf '%s\\n' '${startMarker(name)}'`,
239-
`printenv ${name} || true`,
240-
`printf '%s\\n' '${endMarker(name)}'`,
241-
].join("; ");
242-
})
243-
.join("; ");
244-
245238
const captureWindowsEnvironmentCommand = (names: ReadonlyArray<string>) =>
246239
[
247240
"$ErrorActionPreference = 'Stop'",
@@ -352,7 +345,7 @@ const readLoginShellEnvironment = (
352345
: runCommandOutput({
353346
probe: "login-shell",
354347
command: shell,
355-
args: ["-ilc", capturePosixEnvironmentCommand(names)],
348+
args: ["-ilc", buildEnvironmentCaptureCommand(shell, names)],
356349
timeout: LOGIN_SHELL_TIMEOUT,
357350
}).pipe(Effect.map((output) => extractEnvironment(output, names)));
358351

‎packages/shared/src/shell.test.ts‎

Lines changed: 60 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// @effect-diagnostics nodeBuiltinImport:off -- The synchronous shell probe runs real commands with isolated config files.
12
import * as NodeServices from "@effect/platform-node/NodeServices";
23
import { it as effectIt } from "@effect/vitest";
34
import * as HostProcess from "@t3tools/shared/HostProcess";
@@ -8,6 +9,10 @@ import * as Path from "effect/Path";
89
import * as Result from "effect/Result";
910
import * as TestClock from "effect/testing/TestClock";
1011
import * as Tracer from "effect/Tracer";
12+
import * as NodeChildProcess from "node:child_process";
13+
import * as NodeFS from "node:fs";
14+
import * as NodeOS from "node:os";
15+
import * as NodePath from "node:path";
1116
import { describe, expect, it, vi } from "vite-plus/test";
1217

1318
import {
@@ -129,6 +134,54 @@ describe("readPathFromLaunchctl", () => {
129134
});
130135

131136
describe("readEnvironmentFromLoginShell", () => {
137+
// Opt in with an explicit binary, like the provider live probes; CI need not install Nu.
138+
it.runIf(process.env.T3_TEST_NU_PATH !== undefined)(
139+
"captures Nushell PATH and multiline values without external tools",
140+
() => {
141+
const shell = process.env.T3_TEST_NU_PATH!;
142+
const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-nu-env-"));
143+
try {
144+
const toolPath = NodePath.join(home, "nu tools", "bin");
145+
const extraToolPath = NodePath.join(home, "extra-tools", "bin");
146+
NodeFS.mkdirSync(toolPath, { recursive: true });
147+
NodeFS.mkdirSync(extraToolPath, { recursive: true });
148+
const config = NodePath.join(home, "config.nu");
149+
const envConfig = NodePath.join(home, "env.nu");
150+
NodeFS.writeFileSync(envConfig, "");
151+
NodeFS.writeFileSync(
152+
config,
153+
[
154+
`$env.PATH = [${JSON.stringify(toolPath)}, "~/extra-tools/bin", "rel/dir", ""]`,
155+
'$env.CUSTOM_VAR = " first\\nsecond "',
156+
'$env.EMPTY_VAR = ""',
157+
'print "startup noise"',
158+
].join("\n"),
159+
);
160+
161+
expect(
162+
readEnvironmentFromLoginShell(
163+
shell,
164+
["MISSING_VAR", "PATH", "EMPTY_VAR", "CUSTOM_VAR"],
165+
(file, args, options) =>
166+
NodeChildProcess.execFileSync(
167+
file,
168+
["--no-history", "--config", config, "--env-config", envConfig, ...args],
169+
{
170+
...options,
171+
env: { HOME: home, XDG_CONFIG_HOME: home, PATH: toolPath },
172+
},
173+
),
174+
),
175+
).toEqual({
176+
PATH: `${toolPath}:${extraToolPath}:rel/dir:`,
177+
CUSTOM_VAR: " first\nsecond ",
178+
});
179+
} finally {
180+
NodeFS.rmSync(home, { recursive: true, force: true });
181+
}
182+
},
183+
);
184+
132185
it("extracts multiple environment variables from a login shell command", () => {
133186
const execFile = vi.fn<
134187
(
@@ -176,21 +229,23 @@ describe("readEnvironmentFromLoginShell", () => {
176229
});
177230
});
178231

179-
it("preserves surrounding whitespace in captured values", () => {
232+
it("preserves multiline values and surrounding whitespace", () => {
180233
const execFile = vi.fn<
181234
(
182235
file: string,
183236
args: ReadonlyArray<string>,
184237
options: { encoding: "utf8"; timeout: number },
185238
) => string
186239
>(() =>
187-
["__T3CODE_ENV_CUSTOM_VAR_START__", " padded value ", "__T3CODE_ENV_CUSTOM_VAR_END__"].join(
188-
"\n",
189-
),
240+
[
241+
"__T3CODE_ENV_CUSTOM_VAR_START__",
242+
" first\nsecond ",
243+
"__T3CODE_ENV_CUSTOM_VAR_END__",
244+
].join("\n"),
190245
);
191246

192247
expect(readEnvironmentFromLoginShell("/bin/zsh", ["CUSTOM_VAR"], execFile)).toEqual({
193-
CUSTOM_VAR: " padded value ",
248+
CUSTOM_VAR: " first\nsecond ",
194249
});
195250
});
196251
});

‎packages/shared/src/shell.ts‎

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -206,13 +206,40 @@ function envCaptureEnd(name: string): string {
206206
return `__T3CODE_ENV_${name}_END__`;
207207
}
208208

209-
function buildEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
209+
export function buildEnvironmentCaptureCommand(
210+
shell: string,
211+
names: ReadonlyArray<string>,
212+
): string {
213+
const executableName = NodePath.basename(shell).toLowerCase();
214+
const isNushell = executableName.startsWith("nu");
215+
210216
return names
211217
.map((name) => {
212218
if (!SHELL_ENV_NAME_PATTERN.test(name)) {
213219
throw new Error(`Unsupported environment variable name: ${name}`);
214220
}
215221

222+
if (isNushell) {
223+
// Without a configured conversion, Nu expands home paths only in a list PATH.
224+
const defaultValue =
225+
name === "PATH"
226+
? "if ($env.PATH? | describe | str starts-with 'list') { " +
227+
"$env.PATH | each {|p| if ($p | str starts-with '~') { " +
228+
"$p | path expand --no-symlink } else { $p } } | str join (char esep) " +
229+
"} else { $env.PATH? | default '' }"
230+
: `$env.${name}? | default ''`;
231+
const value =
232+
`if $env.${name}? == null { '' } else if ` +
233+
`$env.ENV_CONVERSIONS?.${name}?.to_string? != null { ` +
234+
`$env.${name} | do $env.ENV_CONVERSIONS.${name}.to_string $env.${name} ` +
235+
`} else { ${defaultValue} }`;
236+
return [
237+
`print '${envCaptureStart(name)}'`,
238+
`print (${value})`,
239+
`print '${envCaptureEnd(name)}'`,
240+
].join("; ");
241+
}
242+
216243
return [
217244
`printf '%s\\n' '${envCaptureStart(name)}'`,
218245
`printenv ${name} || true`,
@@ -275,7 +302,7 @@ export const readEnvironmentFromLoginShell: ShellEnvironmentReader = (
275302

276303
// Interactive startup loads PATH entries; detaching prevents job control on an
277304
// inherited controlling TTY from stopping the probe while the parent waits.
278-
const output = execFile(shell, ["-ilc", buildEnvironmentCaptureCommand(names)], {
305+
const output = execFile(shell, ["-ilc", buildEnvironmentCaptureCommand(shell, names)], {
279306
encoding: "utf8",
280307
timeout: 5000,
281308
detached: true,

0 commit comments

Comments
 (0)