Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
149 changes: 94 additions & 55 deletions src/dotenv/env_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1137,74 +1137,113 @@ impl<'a> Parser<'a> {
if value.len() < 2 {
return Ok(None);
}

self.value_buffer.clear();
if !Self::expand_into(map, value, self.value_buffer, 0) {
return Ok(None);
}
Ok(Some(self.value_buffer.as_slice()))
}

let mut pos = value.len() - 2;
let mut last = value.len();
loop {
if value[pos] == b'$' {
if pos > 0 && value[pos - 1] == b'\\' {
// PERF: splice at the front is O(n)
self.value_buffer
.splice(0..0, value[pos..last].iter().copied());
pos -= 1;
} else {
let mut end = if value[pos + 1] == b'{' {
pos + 2
} else {
pos + 1
};
let key_start = end;
while end < value.len() {
match value[end] {
b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' => {
end += 1;
continue;
}
_ => break,
/// Left-to-right expansion of `$NAME` / `${NAME}` / `${NAME:-default}`.
/// `${...}` locates its matching `}` by depth (`${` opens, `}` closes,
/// `\x` skipped); malformed forms fall through as literal text. The `:-`
/// default clause is expanded recursively.
Comment thread
robobun marked this conversation as resolved.
Resolved
fn expand_into(map: &Map, value: &[u8], out: &mut Vec<u8>, depth: u8) -> bool {
#[inline]
fn is_ident(b: u8) -> bool {
matches!(b, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_')
}

let mut pos = 0;
let mut changed = false;
while pos < value.len() {
let b = value[pos];
if b == b'\\' && value.get(pos + 1) == Some(&b'$') {
out.push(b'$');
pos += 2;
changed = true;
continue;
}
if b != b'$' || pos + 1 >= value.len() {
out.push(b);
pos += 1;
continue;
}
let next = value[pos + 1];
if next == b'{' {
let inner_start = pos + 2;
let close = {
let mut i = inner_start;
let mut nest = 1usize;
loop {
if i >= value.len() {
break None;
}
}
let lookup_value = map.get(&value[key_start..end]);
let default_value: &[u8] = if value[end..].starts_with(b":-") {
end += b":-".len();
let value_start = end;
while end < value.len() {
match value[end] {
b'}' | b'\\' => break,
_ => {
end += 1;
continue;
match value[i] {
b'\\' if i + 1 < value.len() => i += 2,
b'$' if value.get(i + 1) == Some(&b'{') => {
nest += 1;
i += 2;
}
b'}' => {
nest -= 1;
if nest == 0 {
break Some(i);
}
i += 1;
}
_ => i += 1,
}
&value[value_start..end]
}
};
let Some(close) = close else {
out.extend_from_slice(&value[pos..]);
pos = value.len();
continue;
};
changed = true;
let inner = &value[inner_start..close];
let key_end = inner
.iter()
.position(|&c| !is_ident(c))
.unwrap_or(inner.len());
let key = &inner[..key_end];
let rest = &inner[key_end..];
if rest.is_empty() {
if let Some(v) = map.get(key) {
out.extend_from_slice(v);
}
} else if let Some(default) = rest.strip_prefix(b":-") {
if let Some(v) = map.get(key) {
out.extend_from_slice(v);
} else if depth < 200 {
Self::expand_into(map, default, out, depth + 1);
} else {
b""
};
if end < value.len() && value[end] == b'}' {
end += 1;
out.extend_from_slice(default);
}
self.value_buffer
.splice(0..0, value[end..last].iter().copied());
self.value_buffer
.splice(0..0, lookup_value.unwrap_or(default_value).iter().copied());
} else {
out.extend_from_slice(&value[pos..=close]);
}
last = pos;
pos = close + 1;
continue;
}
if pos == 0 {
if last == value.len() {
return Ok(None);
if is_ident(next) {
changed = true;
let key_start = pos + 1;
let mut k = key_start;
while k < value.len() && is_ident(value[k]) {
k += 1;
}
break;
if let Some(v) = map.get(&value[key_start..k]) {
out.extend_from_slice(v);
}
pos = k;
continue;
}
pos -= 1;
}
if last > 0 {
self.value_buffer
.splice(0..0, value[..last].iter().copied());
out.push(b'$');
pos += 1;
}
Ok(Some(self.value_buffer.as_slice()))
changed
}

fn parse<const OVERRIDE: bool, const IS_PROCESS: bool, const EXPAND: bool>(
Expand Down
81 changes: 81 additions & 0 deletions test/cli/run/env.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,87 @@
expect(stdout).toBe("foo|foo bar|foo foo bar moo");
});

test(".env ${VAR:-default} with nested references", () => {
// A ${NAME} nested inside a ${VAR:-default} clause used to panic the loader
// ("slice index starts at N but ends at M") before any user code ran. The
// expander now scans left-to-right, pairs `${` with its matching `}` by
// depth, and expands the default clause recursively, so every case below
// loads and malformed forms fall through as literals.

Check warning on line 260 in test/cli/run/env.test.ts

View check run for this annotation

Claude / Claude Code Review

Regression-test comment narrates bug history; missing issue reference

nit: the first half of this comment is bug-history narration ("used to panic the loader … slice index starts at N but ends at M") that already lives in the PR description — REVIEW.md asks for the issue URL instead. Consider replacing that sentence with `// https://github.com/oven-sh/bun/issues/32411` (or appending `(issue #32411)` to the test name, matching neighbors #411/#2823/#3042) and keeping just the spec line about depth-pairing / literal fallthrough, which does explain the assertion table
Comment thread
robobun marked this conversation as resolved.
Resolved
const dir = tempDirWithFiles("dotenv-expand-nested", {

Check warning on line 261 in test/cli/run/env.test.ts

View check run for this annotation

Claude / Claude Code Review

New test uses tempDirWithFiles without disposal instead of `using tempDir`

This test creates its temp directory with `const dir = tempDirWithFiles(...)` — no `using`, no cleanup — while the immediately adjacent single-shot tests (`.env value expansion` above, `.env comments` below) use `using dir = tempDir(...)`. Change to `using dir = tempDir("dotenv-expand-nested", {...})` and pass `cwd: String(dir)` to `Bun.spawnSync` so the directory is disposed when the test exits (including on assertion failure).
Comment thread
robobun marked this conversation as resolved.
Resolved
".env": [
"NSTD_FALLBACK=localhost",
"NSTD_SET=hi",
"NSTD_HOST=${NSTD_UNSET:-${NSTD_FALLBACK}}",
"NSTD_EMPTY=${NSTD_UNSET:-${NSTD_ALSO_UNSET}}",
"NSTD_DEEP=${NSTD_UNSET:-${NSTD_ALSO_UNSET:-c}}",
"NSTD_PREFIX=${NSTD_UNSET:-x${NSTD_ALSO_UNSET}}",
'NSTD_QUOTED="${NSTD_UNSET:-${NSTD_ALSO_UNSET:-${NSTD_FALLBACK}}}suffix"',
"NSTD_SET_WINS=${NSTD_SET:-${NSTD_ALSO_UNSET}}",
"NSTD_BARE=${NSTD_UNSET:-$NSTD_FALLBACK}",
"NSTD_DOLLAR=${NSTD_UNSET:-$}",
"NSTD_DUBL=$${NSTD_UNSET:-${NSTD_FALLBACK}}",
"NSTD_NOKEY=${:-${NSTD_FALLBACK}}",
"NSTD_AROUND=pre${NSTD_UNSET:-$NSTD_FALLBACK}post",
"NSTD_TWO=${NSTD_FALLBACK}${NSTD_UNSET:-$NSTD_FALLBACK}",
"NSTD_PATH=$NSTD_FALLBACK/${NSTD_UNSET:-$NSTD_FALLBACK}/x",
"NSTD_UNTERM=${NSTD_UNSET:-${",
"NSTD_UNTERM2=${NSTD_UNSET",
"NSTD_BSLASH=${NSTD_UNSET:-a\\b}",
"NSTD_DASH=${NSTD_UNSET-${NSTD_FALLBACK}}",
].join("\n"),
"index.ts":
"const keys = process.argv.slice(2);" +
"const out = {};" +
"for (const k of keys) out[k] = process.env[k];" +
"console.log(JSON.stringify(out));",
});
const keys = [
"NSTD_HOST",
"NSTD_EMPTY",
"NSTD_DEEP",
"NSTD_PREFIX",
"NSTD_QUOTED",
"NSTD_SET_WINS",
"NSTD_BARE",
"NSTD_DOLLAR",
"NSTD_DUBL",
"NSTD_NOKEY",
"NSTD_AROUND",
"NSTD_TWO",
"NSTD_PATH",
"NSTD_UNTERM",
"NSTD_UNTERM2",
"NSTD_BSLASH",
"NSTD_DASH",
];
const result = Bun.spawnSync([bunExe(), `${dir}/index.ts`, ...keys], {
cwd: dir,
env: { ...bunEnv, NODE_ENV: undefined },
});
const stdout = result.stdout.toString("utf8").trim();
expect(stdout).toStartWith("{");
expect(JSON.parse(stdout)).toEqual({
NSTD_HOST: "localhost",
NSTD_EMPTY: "",
NSTD_DEEP: "c",
NSTD_PREFIX: "x",
NSTD_QUOTED: "localhostsuffix",
NSTD_SET_WINS: "hi",
NSTD_BARE: "localhost",
NSTD_DOLLAR: "$",
NSTD_DUBL: "$localhost",
NSTD_NOKEY: "localhost",
NSTD_AROUND: "prelocalhostpost",
NSTD_TWO: "localhostlocalhost",
NSTD_PATH: "localhost/localhost/x",
NSTD_UNTERM: "${NSTD_UNSET:-${",
NSTD_UNTERM2: "${NSTD_UNSET",
NSTD_BSLASH: "a\\b",
NSTD_DASH: "${NSTD_UNSET-${NSTD_FALLBACK}}",
});
expect(result.exitCode).toBe(0);
});

test(".env comments", () => {
using dir = tempDir("dotenv-comments", {
".env": "#FOZ\nFOO = foo#FAIL\nBAR='bar' #BAZ",
Expand Down
Loading