diff --git a/src/runtime/cli/filter_run.rs b/src/runtime/cli/filter_run.rs index e506cbd3f2f5..fde6ad6d866e 100644 --- a/src/runtime/cli/filter_run.rs +++ b/src/runtime/cli/filter_run.rs @@ -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}; @@ -30,13 +30,8 @@ struct ScriptConfig { // parsed `PackageJSON` (which owns the file bytes) drops. deps: Vec>, - // $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` and this script's `npm_*` vars, layered over the run's shared env. + env: ScriptEnv, elide_count: Option, } @@ -103,36 +98,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); @@ -327,10 +308,8 @@ struct State<'a> { pretty_output: bool, 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. + // Process-lifetime loader owned by the Transpiler; `ProcessHandle::start` mutates it per + // spawn, so it is reborrowed `&mut` at use sites rather than held as `&'a`/`&'a mut`. env: *mut bun_dotenv::Loader, } @@ -765,7 +744,7 @@ pub(crate) fn run_scripts_with_filter( ) -> crate::Result { // Never returns normally; Result keeps `?` support. // Own the slice — `ctx` is reborrowed `&mut` for - // `configure_env_for_run` below while `script_name` is still live. + // `configure_env_for_multi_script_run` below while `script_name` is still live. let script_name_owned: Box<[u8]> = if ctx.positionals.len() > 1 { ctx.positionals[1].clone() } else if ctx.positionals.len() > 0 { @@ -817,8 +796,8 @@ pub(crate) fn run_scripts_with_filter( // `RunCommand::configure_env_for_run(...) -> Result`; until then // pass `&mut MaybeUninit` (zeroed() is invalid: Transpiler is not #[repr(C)] POD). let mut this_transpiler = core::mem::MaybeUninit::>::uninit(); - 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. + RunCommand::configure_env_for_multi_script_run(&mut *ctx, &mut this_transpiler)?; + // SAFETY: configure_env_for_multi_script_run fully initializes the out-param on Ok. let mut this_transpiler = unsafe { this_transpiler.assume_init() }; let mut package_json_iter = FilterArg::PackageFilterIterator::init(&patterns, resolve_root)?; @@ -867,6 +846,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() @@ -926,7 +906,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, }); } diff --git a/src/runtime/cli/multi_run.rs b/src/runtime/cli/multi_run.rs index 72c9fd15af29..347157aa92b7 100644 --- a/src/runtime/cli/multi_run.rs +++ b/src/runtime/cli/multi_run.rs @@ -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. @@ -41,8 +41,8 @@ struct ScriptConfig { label: Box<[u8]>, command: Box<[u8]>, cwd: Box<[u8]>, - /// PATH env var value for this script - path: Box<[u8]>, + /// This package's `$PATH` and this script's `npm_*` vars, layered over the run's shared env. + env: ScriptEnv, } /// Wraps a BufferedReader and tracks whether it represents stdout or stderr, @@ -156,19 +156,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 { @@ -723,7 +717,7 @@ fn add_script_configs>( raw_name: &[u8], scripts_map: Option<&StringArrayHashMap>, cwd: &[u8], - path: &[u8], + package_env: &ScriptEnv, label_prefix: Option<&[u8]>, ) -> Result<(), Error> { let group_start = configs.len(); @@ -766,7 +760,7 @@ fn add_script_configs>( 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), }); } @@ -779,7 +773,7 @@ fn add_script_configs>( 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), }); } @@ -791,7 +785,7 @@ fn add_script_configs>( label, command: cmd_buf.into_boxed_slice(), cwd: Box::from(cwd), - path: Box::from(path), + env: package_env.with_script(&post_name, pc), }); } } else { @@ -824,7 +818,7 @@ fn add_script_configs>( label, command: command_z, cwd: Box::from(cwd), - path: Box::from(path), + env: package_env.clone(), }); } @@ -878,8 +872,8 @@ pub(crate) fn run(ctx: &mut Command::ContextData) -> Result>::uninit(); - 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. + RunCommand::configure_env_for_multi_script_run(ctx, &mut this_transpiler_slot)?; + // SAFETY: `configure_env_for_multi_script_run` fully writes the slot on the success path. let this_transpiler = unsafe { this_transpiler_slot.assume_init_mut() }; let cwd: &[u8] = bun_resolver::fs::FileSystem::get().top_level_dir; @@ -958,7 +952,7 @@ pub(crate) fn run(ctx: &mut Command::ContextData) -> Result, dirpath: Box<[u8]>, scripts: OwnedScriptsMap, - path: Box<[u8]>, + env: ScriptEnv, } let mut matched_packages: Vec = Vec::new(); @@ -1021,7 +1015,7 @@ pub(crate) fn run(ctx: &mut Command::ContextData) -> Result Result Result Result = 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 @@ -1147,7 +1142,7 @@ pub(crate) fn run(ctx: &mut Command::ContextData) -> Result Result, Box<[u8]>)>, +} + +impl ScriptEnv { + 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); + // A missing name/version stays inherited, as in `configure_env_for_run` and npm. + 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), + )); + } + } + } + env + } + + /// `script` is the package.json body verbatim: that is what `npm_lifecycle_script` carries. + 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))); + } + + /// Envp of `map` plus these vars; `map` is restored so they do not reach the next spawn. + pub(crate) fn create_envp( + &self, + map: &mut DotEnv::Map, + ) -> Result { + let previous: Vec<(&[u8], Option>)> = 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)] @@ -544,7 +612,15 @@ Full documentation is available at https://bun.com/docs/cli/run log_errors: bool, store_root_fd: bool, ) -> crate::Result { - Self::configure_env_for_run_impl(ctx, this_transpiler, env, log_errors, store_root_fd, true) + Self::configure_env_for_run_impl( + ctx, + this_transpiler, + env, + log_errors, + store_root_fd, + true, + true, + ) } /// Like [`Self::configure_env_for_run`] but does **not** construct the @@ -565,9 +641,27 @@ Full documentation is available at https://bun.com/docs/cli/run log_errors, store_root_fd, false, + true, ) } + /// [`Self::configure_env_for_run`] for `--filter` / `--parallel`, whose scripts span packages: + /// the cwd package's `npm_package_*` vars are not seeded; each [`ScriptEnv`] brings its own. + pub(crate) fn configure_env_for_multi_script_run( + ctx: &mut ContextData, + this_transpiler: &mut ::core::mem::MaybeUninit>, + ) -> crate::Result<()> { + Self::configure_env_for_run_impl(ctx, this_transpiler, None, true, false, true, false)?; + // SAFETY: `configure_env_for_run_impl` returned `Ok`, so the slot is initialized. + let this_transpiler = unsafe { this_transpiler.assume_init_mut() }; + // Same value `exec` exports for `bun run