Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 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
60 changes: 25 additions & 35 deletions src/runtime/cli/filter_run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::api::bun::process::SpawnResultExt as _;
use crate::api::bun::process::{self as spawn, Process, Rusage, SpawnOptions, Status};
use crate::cli::Command;
use crate::cli::filter_arg as FilterArg;
use crate::cli::run_command::RunCommand;
use crate::cli::run_command::{RunCommand, ScriptEnv};
use bun_collections::StringHashMap;
use bun_core::{Global, Output};
use bun_core::{ZStr, strings};
Expand All @@ -30,13 +30,10 @@ struct ScriptConfig {
// parsed `PackageJSON` (which owns the file bytes) drops.
deps: Vec<Box<[u8]>>,

// $PATH must be set per script because it contains
// node_modules/.bin
// ../node_modules/.bin
// ../../node_modules/.bin
// and so forth, in addition to the user's $PATH.
#[allow(non_snake_case)]
PATH: Box<[u8]>,
/// This package's `$PATH` (its own `node_modules/.bin` chain) plus the
/// `npm_package_*` / `npm_lifecycle_*` vars for this package and script;
/// everything else comes from the env shared by the whole run.
Comment thread
robobun marked this conversation as resolved.
Resolved
env: ScriptEnv,
elide_count: Option<usize>,
}

Expand Down Expand Up @@ -103,36 +100,22 @@ impl<'a> ProcessHandle<'a> {
core::ptr::null(),
];
handle.start_time = Some(Instant::now());
let spawned: spawn::SpawnProcessResult = 'brk: {
// Get the envp with the PATH configured
// There's probably a more optimal way to do this where you have a Vec shared
// instead of creating a new one for each process
let env_ptr = state.env;
// SAFETY: state.env is the process-lifetime DotEnv loader (Transpiler::env).
let env = unsafe { &mut *env_ptr };
// Copy to owned — `original_path` borrows env.map which is
// mutated by put() below.
let original_path: Box<[u8]> = env.map.get(b"PATH").unwrap_or(b"").into();
let _ = env.map.put(b"PATH", &handle.config.PATH);
// Restores PATH unconditionally at block exit (success OR error).
// Keep the guard armed for the whole block so `?` early-returns also
// restore.
scopeguard::defer! {
// SAFETY: env_ptr valid for the run loop lifetime (see above).
let _ = unsafe { (*env_ptr).map.put(b"PATH", &original_path) };
}
// SAFETY: see above; reborrow through raw ptr to avoid overlapping &mut with guard.
let envp = unsafe { (*env_ptr).map.create_null_delimited_env_map()? };
let spawned: spawn::SpawnProcessResult = {
// SAFETY: state.env is the process-lifetime DotEnv loader (Transpiler::env);
// this is the only borrow of it while `create_envp` runs.
let envp = handle
.config
.env
.create_envp(unsafe { &mut (*state.env).map })?;
// SAFETY: `argv`/`envp` are local null-terminated C-string arrays
// with argv[0] non-null; valid for this call.
break 'brk unsafe {
unsafe {
spawn::spawn_process(
&handle.options,
argv.as_ptr(),
envp.as_ptr().cast::<*const c_char>(),
)
}??;
// `_guard` drops here (or on `?` above), restoring PATH.
}??
};
#[cfg(unix)]
let (stdout_fd, stderr_fd) = (spawned.stdout, spawned.stderr);
Expand Down Expand Up @@ -328,9 +311,10 @@ struct State<'a> {
shell_bin: &'static ZStr, // intentionally leaked (process exits)
aborted: bool,
// Raw `*mut` — process-lifetime singleton owned
// by Transpiler; ProcessHandle::start mutates `env.map` (PATH swap) so a
// shared borrow won't do, and `&'a mut` would conflict with the Transpiler's
// own raw-ptr field. Reborrow `&mut *env` at use sites.
// by Transpiler; ProcessHandle::start mutates `env.map` (per-script
// `ScriptEnv` overlay) so a shared borrow won't do, and `&'a mut` would
// conflict with the Transpiler's own raw-ptr field. Reborrow `&mut *env`
// at use sites.
Comment thread
robobun marked this conversation as resolved.
Resolved
env: *mut bun_dotenv::Loader,
}

Expand Down Expand Up @@ -820,6 +804,11 @@ pub(crate) fn run_scripts_with_filter(
let _ = RunCommand::configure_env_for_run(&mut *ctx, &mut this_transpiler, None, true, false)?;
// SAFETY: configure_env_for_run fully initializes the out-param on Ok.
let mut this_transpiler = unsafe { this_transpiler.assume_init() };
// Same value `bun run <script>` exports (see `RunCommand::exec`).
this_transpiler
.env_mut()
.map
.put(b"npm_command", b"run-script")?;

let mut package_json_iter = FilterArg::PackageFilterIterator::init(&patterns, resolve_root)?;
// defer package_json_iter.deinit() — handled by Drop
Expand Down Expand Up @@ -867,6 +856,7 @@ pub(crate) fn run_scripts_with_filter(
dirpath,
run_in_bun,
)?;
let package_env = ScriptEnv::new(&path_var, Some(&pkgjson));

for (i, name) in [&pre_script_name[..], script_name, &post_script_name[..]]
.iter()
Expand Down Expand Up @@ -926,7 +916,7 @@ pub(crate) fn run_scripts_with_filter(
script_content: Box::<[u8]>::from(&interned[0..len_command_only]),
combined,
deps,
PATH: Box::<[u8]>::from(&path_var[..]),
env: package_env.with_script(name, original_content),
elide_count: ctx.bundler_options.elide_lines,
});
}
Expand Down
53 changes: 27 additions & 26 deletions src/runtime/cli/multi_run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use bun_resolver::package_json::{IncludeDependencies, IncludeScripts};

use crate::Command;
use crate::filter_arg as FilterArg;
use crate::run_command::RunCommand;
use crate::run_command::{RunCommand, ScriptEnv};

// `bun.spawn` (Process/Status/SpawnOptions/Rusage/spawnProcess) —
// lives under crate::api::bun::process.
Expand All @@ -41,8 +41,9 @@ struct ScriptConfig {
label: Box<[u8]>,
command: Box<[u8]>,
cwd: Box<[u8]>,
/// PATH env var value for this script
path: Box<[u8]>,
/// `$PATH` and the `npm_*` vars specific to this script's package and
/// (for package.json scripts) to the script itself.
Comment thread
robobun marked this conversation as resolved.
Resolved
env: ScriptEnv,
}

/// Wraps a BufferedReader and tracks whether it represents stdout or stderr,
Expand Down Expand Up @@ -156,19 +157,13 @@ impl<'a> ProcessHandle<'a> {
];

self.start_time = Instant::now().into();
let envp;
let env_ptr = state.env;
let spawned: SpawnProcessResult = {
// SAFETY: state.env points at the process-lifetime DotEnv loader.
let env = unsafe { &mut *env_ptr };
let original_path: Box<[u8]> = env.map.get(b"PATH").map(Box::from).unwrap_or_default();
let _ = env.map.put(b"PATH", &self.config.path);
let _restore = scopeguard::guard(original_path, move |original_path| {
// SAFETY: env_ptr is the process-lifetime loader; outlives this scope.
let _ = unsafe { (*env_ptr).map.put(b"PATH", &original_path) };
});
// SAFETY: same loader; the `_restore` guard's closure has not fired yet.
envp = unsafe { (*env_ptr).map.create_null_delimited_env_map()? };
// SAFETY: state.env points at the process-lifetime DotEnv loader; this
// is the only borrow of it while `create_envp` runs.
let envp = self
.config
.env
.create_envp(unsafe { &mut (*state.env).map })?;
// SAFETY: `argv`/`envp` are local null-terminated C-string arrays
// with argv[0] non-null; valid for this call.
unsafe {
Expand Down Expand Up @@ -723,7 +718,7 @@ fn add_script_configs<V: core::ops::Deref<Target = [u8]>>(
raw_name: &[u8],
scripts_map: Option<&StringArrayHashMap<V>>,
cwd: &[u8],
path: &[u8],
package_env: &ScriptEnv,
label_prefix: Option<&[u8]>,
) -> Result<(), Error> {
let group_start = configs.len();
Expand Down Expand Up @@ -766,7 +761,7 @@ fn add_script_configs<V: core::ops::Deref<Target = [u8]>>(
label: label.clone(),
command: cmd_buf.into_boxed_slice(),
cwd: Box::from(cwd),
path: Box::from(path),
env: package_env.with_script(&pre_name, pc),
});
}

Expand All @@ -779,7 +774,7 @@ fn add_script_configs<V: core::ops::Deref<Target = [u8]>>(
label: label.clone(),
command: cmd_buf.into_boxed_slice(),
cwd: Box::from(cwd),
path: Box::from(path),
env: package_env.with_script(raw_name, content),
});
}

Expand All @@ -791,7 +786,7 @@ fn add_script_configs<V: core::ops::Deref<Target = [u8]>>(
label,
command: cmd_buf.into_boxed_slice(),
cwd: Box::from(cwd),
path: Box::from(path),
env: package_env.with_script(&post_name, pc),
});
}
} else {
Expand Down Expand Up @@ -824,7 +819,7 @@ fn add_script_configs<V: core::ops::Deref<Target = [u8]>>(
label,
command: command_z,
cwd: Box::from(cwd),
path: Box::from(path),
env: package_env.clone(),
});
}

Expand Down Expand Up @@ -881,6 +876,11 @@ pub(crate) fn run(ctx: &mut Command::ContextData) -> Result<core::convert::Infal
let _ = RunCommand::configure_env_for_run(ctx, &mut this_transpiler_slot, None, true, false)?;
// SAFETY: `configure_env_for_run` fully writes the slot on the success path.
let this_transpiler = unsafe { this_transpiler_slot.assume_init_mut() };
// Same value `bun run <script>` exports (see `RunCommand::exec`).
this_transpiler
.env_mut()
.map
.put(b"npm_command", b"run-script")?;
let cwd: &[u8] = bun_resolver::fs::FileSystem::get().top_level_dir;

// SAFETY: transpiler.env is a process-lifetime *mut Loader set in init.
Expand Down Expand Up @@ -958,7 +958,7 @@ pub(crate) fn run(ctx: &mut Command::ContextData) -> Result<core::convert::Infal
name: Box<[u8]>,
dirpath: Box<[u8]>,
scripts: OwnedScriptsMap,
path: Box<[u8]>,
env: ScriptEnv,
}
let mut matched_packages: Vec<MatchedPackage> = Vec::new();

Expand Down Expand Up @@ -1021,7 +1021,7 @@ pub(crate) fn run(ctx: &mut Command::ContextData) -> Result<core::convert::Infal
name: pkg_name,
dirpath,
scripts: owned_scripts,
path: pkg_path_env.into(),
env: ScriptEnv::new(&pkg_path_env, Some(&pkgjson)),
});
}

Expand Down Expand Up @@ -1053,7 +1053,7 @@ pub(crate) fn run(ctx: &mut Command::ContextData) -> Result<core::convert::Infal
matched_name,
Some(&pkg.scripts),
&pkg.dirpath,
&pkg.path,
&pkg.env,
Some(&pkg.name),
)?;
}
Expand All @@ -1065,7 +1065,7 @@ pub(crate) fn run(ctx: &mut Command::ContextData) -> Result<core::convert::Infal
raw_name,
Some(&pkg.scripts),
&pkg.dirpath,
&pkg.path,
&pkg.env,
Some(&pkg.name),
)?;
} else if ctx.workspaces && !ctx.if_present {
Expand Down Expand Up @@ -1116,6 +1116,7 @@ pub(crate) fn run(ctx: &mut Command::ContextData) -> Result<core::convert::Infal

let package_json = (*root_dir_info).enclosing_package_json;
let scripts_map: Option<&ScriptsMap> = package_json.and_then(|pkg| pkg.scripts.as_deref());
let package_env = ScriptEnv::new(&path_env, package_json);

for raw_name in &script_names {
// Check if this is a glob pattern
Expand Down Expand Up @@ -1147,7 +1148,7 @@ pub(crate) fn run(ctx: &mut Command::ContextData) -> Result<core::convert::Infal
matched_name,
scripts_map,
cwd,
&path_env,
&package_env,
None,
)?;
}
Expand All @@ -1165,7 +1166,7 @@ pub(crate) fn run(ctx: &mut Command::ContextData) -> Result<core::convert::Infal
raw_name,
scripts_map,
cwd,
&path_env,
&package_env,
None,
)?;
}
Expand Down
80 changes: 80 additions & 0 deletions src/runtime/cli/run_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,86 @@
const PACKAGE_VERSION: &'static [u8] = b"npm_package_version";
}

/// The env vars that differ between the scripts one `bun run` spawns
/// (`--filter`, `--parallel`, `--sequential`): the package's `$PATH` and the
/// `npm_package_*` / `npm_lifecycle_*` vars `bun run <script>` sets when run
/// inside that package. Those runners share one env loader, which
/// `configure_env_for_run` seeded from the cwd package, so [`Self::create_envp`]
/// overlays these vars on it only while building each script's envp.
Comment thread
robobun marked this conversation as resolved.
Resolved
#[derive(Clone)]
pub(crate) struct ScriptEnv {
vars: Vec<(Box<[u8]>, Box<[u8]>)>,
}

impl ScriptEnv {
/// `path` is the `$PATH` built for the package directory by
/// `configure_path_for_run_with_package_json_dir`.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn new(path: &[u8], package_json: Option<&PackageJSON>) -> Self {
let mut env = Self { vars: Vec::new() };
env.set(b"PATH", path);
if let Some(package_json) = package_json {
env.set(b"npm_package_json", package_json.source.path.text);
// Like `configure_env_for_run` (and npm), a package.json without a
// name or version leaves the inherited values alone.
Comment thread
robobun marked this conversation as resolved.
Resolved
if !package_json.name.is_empty() {
env.set(NpmArgs::PACKAGE_NAME, &package_json.name);
}
if !package_json.version.is_empty() {
env.set(NpmArgs::PACKAGE_VERSION, &package_json.version);
}
if let Some(config) = package_json.config.as_deref() {
for (key, value) in config.iter() {
env.vars.push((
strings::concat(&[b"npm_package_config_", &key[..]]),
Box::from(*value),
));
}
}

Check warning on line 108 in src/runtime/cli/run_command.rs

View check run for this annotation

Claude / Claude Code Review

Root npm_package_config_* keys still leak to workspace packages that lack them

After 675f39ab, `ScriptEnv::new` overlays each package's own `npm_package_config_*` keys, but `configure_env_for_run` (lines 839-845) still seeds the *root* package's config into the shared map, and `create_envp`'s restore loop only touches keys in `self.vars` — so a root-only key (root has `"config":{"port":"3000"}`, workspace pkg-b has no `config`) still reaches pkg-b under `--filter`, whereas `cd packages/b && bun run …` would not set it. The new test's root package.json has no `config` field
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
}
env
}
Comment thread
robobun marked this conversation as resolved.
Resolved

/// The env for one package.json script of this package. `script` is the
/// body as written in package.json: `npm_lifecycle_script` carries it
/// verbatim, not the rewritten command that actually runs.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn with_script(&self, name: &[u8], script: &[u8]) -> Self {
let mut env = self.clone();
env.set(b"npm_lifecycle_event", name);
env.set(b"npm_lifecycle_script", script);
env
}

fn set(&mut self, key: &[u8], value: &[u8]) {
self.vars.push((Box::from(key), Box::from(value)));
}

/// Builds the script's envp from the shared `map` with these vars applied.
/// `map` is put back the way it was found, so nothing set for this script
/// is seen by the next script spawned from the same map.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn create_envp(
&self,
map: &mut DotEnv::Map,
) -> Result<DotEnv::NullDelimitedEnvMap, bun_alloc::AllocError> {
let previous: Vec<(&[u8], Option<Box<[u8]>>)> = self
.vars
.iter()
.map(|(key, _)| (&key[..], map.get(key).map(Box::from)))
.collect();
let envp = self
.vars
.iter()
.try_for_each(|(key, value)| map.put(key, value))
.and_then(|()| map.create_null_delimited_env_map());
for (key, value) in &previous {
match value {
Some(value) => map.put(key, value)?,
None => map.remove(key),
}
}
envp
}
}

/// Runtime knobs `Command::start` passes through to select the per-tag exec
/// behavior.
#[derive(Clone, Copy)]
Expand Down
Loading