diff --git a/docs/runtime/child-process.mdx b/docs/runtime/child-process.mdx index c4774c34db7d..d601ee132fc6 100644 --- a/docs/runtime/child-process.mdx +++ b/docs/runtime/child-process.mdx @@ -105,13 +105,31 @@ console.log(text); // => "1.3.3\n" Configure the output stream by passing one of the following values to `stdout/stderr`: -| Value | Description | -| ------------ | --------------------------------------------------------------------------------------------------- | -| `"pipe"` | **Default for `stdout`.** Pipe the output to a `ReadableStream` on the returned `Subprocess` object | -| `"inherit"` | **Default for `stderr`.** Inherit from the parent process | -| `"ignore"` | Discard the output | -| `Bun.file()` | Write to the specified file | -| `number` | Write to the file with the given file descriptor | +| Value | Description | +| ---------------- | --------------------------------------------------------------------------------------------------- | +| `"pipe"` | **Default for `stdout`.** Pipe the output to a `ReadableStream` on the returned `Subprocess` object | +| `"inherit"` | **Default for `stderr`.** Inherit from the parent process | +| `"ignore"` | Discard the output | +| `Bun.file(path)` | Write to the file at that path. Bun creates the file if it does not exist and replaces its content | +| `number` | Write to the file with the given file descriptor. Bun does not create or truncate the file | + +Bun opens a `Bun.file(path)` and empties it before the command starts. If the command cannot start, the file can already be empty. + +Do not pass the same file to `stdin`: the command would read an empty file. `Bun.spawn` throws when `stdin` is a `Bun.file()` with the same path string, unless that path is a device such as `/dev/null`. Bun does not detect a second name for the file (for example a symlink) or a file descriptor of the file. To filter a file in place, pass `stdin: await Bun.file(path).bytes()`. If the command does not read `stdin`, pass `stdin: "ignore"`. + +To append to a file, or to keep its content, open the file and pass the file descriptor. To collect `stdout` and `stderr` in one file, pass the same file descriptor to both. + +```ts +import { closeSync, openSync } from "node:fs"; + +const fd = openSync("build.log", "a"); // "a" appends. "w" replaces the content. +try { + const proc = Bun.spawn(["bun", "--version"], { stdout: fd, stderr: fd }); + await proc.exited; +} finally { + closeSync(fd); +} +``` ## Exit handling diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index 59aa530c8e58..6fffdfd41534 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -7819,7 +7819,8 @@ declare module "bun" { * - `"ignore"`, `null`: The process has no standard output/error * - `"inherit"`: The process inherits the standard output/error of the current process * - `ArrayBufferView`: The process writes to the preallocated buffer. Not implemented. - * - `number`: The process writes to the file descriptor + * - `Bun.file(path)`: The process writes to the file at that path. Bun creates the file if it does not exist and empties it before the process starts. To append, to keep the content, or to send stdout and stderr to one file, open the file and pass the file descriptor. To filter a file in place, pass `stdin: await Bun.file(path).bytes()`. + * - `number`: The process writes to the file descriptor. Bun does not create or truncate the file. * * At indices >= 3, `"socket-fd"` (POSIX only) is also accepted: * creates a socketpair like `"pipe"`, but the parent-end fd exposed @@ -7852,7 +7853,8 @@ declare module "bun" { * - `"ignore"`, `null`: The process has no standard output/error * - `"inherit"`: The process inherits the standard output/error of the current process * - `ArrayBufferView`: The process writes to the preallocated buffer. Not implemented. - * - `number`: The process writes to the file descriptor + * - `Bun.file(path)`: The process writes to the file at that path. Bun creates the file if it does not exist and empties it before the process starts. To append, to keep the content, or to send stdout and stderr to one file, open the file and pass the file descriptor. To filter a file in place, pass `stdin: await Bun.file(path).bytes()`. + * - `number`: The process writes to the file descriptor. Bun does not create or truncate the file. * * @default "pipe" */ @@ -7864,7 +7866,8 @@ declare module "bun" { * - `"ignore"`, `null`: The process has no standard output/error * - `"inherit"`: The process inherits the standard output/error of the current process * - `ArrayBufferView`: The process writes to the preallocated buffer. Not implemented. - * - `number`: The process writes to the file descriptor + * - `Bun.file(path)`: The process writes to the file at that path. Bun creates the file if it does not exist and empties it before the process starts. To append, to keep the content, or to send stdout and stderr to one file, open the file and pass the file descriptor. To filter a file in place, pass `stdin: await Bun.file(path).bytes()`. + * - `number`: The process writes to the file descriptor. Bun does not create or truncate the file. * * @default "inherit" for `spawn` * "pipe" for `spawnSync` diff --git a/src/libuv_sys/libuv.rs b/src/libuv_sys/libuv.rs index 19eaf5b60d6d..f0c0bd78e316 100644 --- a/src/libuv_sys/libuv.rs +++ b/src/libuv_sys/libuv.rs @@ -2395,7 +2395,7 @@ pub mod O { } /// Convert from internal `bun.O` flags to libuv/Windows flags. - pub fn from_bun_o(c_flags: i32) -> i32 { + pub const fn from_bun_o(c_flags: i32) -> i32 { let mut flags: i32 = 0; if c_flags & bun_o::WRONLY != 0 { flags |= WRONLY; diff --git a/src/runtime/api/bun/js_bun_spawn_bindings.rs b/src/runtime/api/bun/js_bun_spawn_bindings.rs index 87508dca2880..0b36b4c05307 100644 --- a/src/runtime/api/bun/js_bun_spawn_bindings.rs +++ b/src/runtime/api/bun/js_bun_spawn_bindings.rs @@ -75,6 +75,22 @@ unsafe extern "C" { safe static BUN_DEFAULT_PATH_FOR_SPAWN: *const c_char; } +/// Whether a `Path` stdio opens a regular file at `path`. `O_TRUNC` changes nothing in a device or a FIFO. +fn path_stdio_opens_regular_file(path: &[u8], has_cwd: bool) -> bool { + // A POSIX child can open a relative path under `cwd`, where a stat from this process finds another file. + if cfg!(unix) && has_cwd && !bun_paths::is_absolute_posix(path) { + return true; + } + let Ok(path) = sys::to_posix_path(path) else { + return false; + }; + match sys::stat(ZStr::from_cstr(&path)) { + Ok(stat) => sys::is_regular_file(stat.st_mode as _), + // `O_CREAT` makes a regular file, or the open fails. + Err(err) => err.get_errno() == sys::Errno::ENOENT, + } +} + struct Argv0Result { /// Was arena-owned `[:0]const u8`; caller stashes in its `Vec` backing /// store so the pointer outlives `spawn_process`. @@ -918,6 +934,27 @@ fn spawn_maybe_sync( } } + // The open of stdout or stderr empties the file before the child reads stdin. + if let Stdio::Path(input) = &stdio[0] { + let is_input = |output: &Stdio| match output { + Stdio::Path(path) => path.slice() == input.slice(), + _ => false, + }; + if (is_input(&stdio[1]) || is_input(&stdio[2])) + && path_stdio_opens_regular_file(input.slice(), user_specified_cwd) + { + // `WindowsStdio` has no `Drop`. + #[cfg(windows)] + for e in &mut extra_fds { + e.deinit(); + } + return Err(cx.global().throw_invalid_arguments(format_args!( + "stdin cannot be the same file as stdout or stderr: the command would read an empty {}. To filter the file in place, pass stdin: await Bun.file(path).bytes(). If the command does not read stdin, pass stdin: \"ignore\".", + bun_fmt::quote(input.slice()) + ))); + } + } + bun_output::scoped_log!(Subprocess, "spawn maxBuffer: {:?}", max_buffer); // Owns the `K=V\0` storage when inheriting the parent env; the struct diff --git a/src/runtime/shell/shell_body.rs b/src/runtime/shell/shell_body.rs index 8b5134f7e366..e7abcb0881ac 100644 --- a/src/runtime/shell/shell_body.rs +++ b/src/runtime/shell/shell_body.rs @@ -304,6 +304,19 @@ pub(crate) fn shell_cmd_from_js( const MAX_TEMPLATE_ARRAY_DEPTH: u32 = 100; +/// A C open stops at a NUL byte, so a path that holds one names another file. +pub(crate) fn throw_path_with_nul(global: &JSGlobalObject, path: &[u8]) -> jsc::JsError { + global + .err( + jsc::ErrorCode::INVALID_ARG_VALUE, + format_args!( + "The shell argument must be a string without null bytes. Received {}", + bun_core::fmt::quote(path) + ), + ) + .throw() +} + pub(crate) fn handle_template_value( global: &JSGlobalObject, template_value: JSValue, @@ -340,12 +353,7 @@ pub(crate) fn handle_template_value( // Check for null bytes in path (security: prevent null byte injection) if strings::index_of_char(path, 0).is_some() { - return Err(global - .err(jsc::ErrorCode::INVALID_ARG_VALUE, format_args!( - "The shell argument must be a string without null bytes. Received {}", - bun_core::fmt::quote(path) - )) - .throw()); + return Err(throw_path_with_nul(global, path)); } if !builder.append_utf8::(path)? { diff --git a/src/runtime/shell/states/Cmd.rs b/src/runtime/shell/states/Cmd.rs index 1f1006c9a770..ab20f255495c 100644 --- a/src/runtime/shell/states/Cmd.rs +++ b/src/runtime/shell/states/Cmd.rs @@ -780,17 +780,30 @@ impl Cmd { // `get_body_value` is `&self`. let req = unsafe { &*req }; req.get_body_value().to_blob_if_possible(); + let body = req.get_body_value().use_as_any_blob(); + // As `Stdio::Path` it would get the flags of `Bun.spawn`, not of the operator. + if let Some(path) = file_path(&body) { + let Ok(path_z) = bun_sys::to_posix_path(path) else { + return Err(crate::shell::shell_body::throw_path_with_nul( + global, path, + )); + }; + let path = bun_core::ZStr::from_cstr(&path_z); + return Ok(Self::open_redirect_path(interp, this, stdio, flags, path)); + } + let mut body = Some(body); + let mut next_blob = || { + body.take() + .unwrap_or_else(|| req.get_body_value().use_as_any_blob()) + }; if flags.stdin() { - let b = req.get_body_value().use_as_any_blob(); - stdio[STDIN_NO].extract_blob(global, b, STDIN_NO as i32)?; + stdio[STDIN_NO].extract_blob(global, next_blob(), STDIN_NO as i32)?; } if flags.stdout() { - let b = req.get_body_value().use_as_any_blob(); - stdio[STDOUT_NO].extract_blob(global, b, STDOUT_NO as i32)?; + stdio[STDOUT_NO].extract_blob(global, next_blob(), STDOUT_NO as i32)?; } if flags.stderr() { - let b = req.get_body_value().use_as_any_blob(); - stdio[STDERR_NO].extract_blob(global, b, STDERR_NO as i32)?; + stdio[STDERR_NO].extract_blob(global, next_blob(), STDERR_NO as i32)?; } } else { return Err(global.throw(format_args!( @@ -826,34 +839,42 @@ impl Cmd { }; let path = bun_core::ZStr::from_buf(&path_buf, path_buf.len() - 1); log!("Expanded Redirect: {}\n", bstr::BStr::new(path.as_bytes())); - let cwd_fd = interp.as_cmd(this).base.shell().cwd_fd; - let redirfd = match crate::shell::interpreter::shell_openat( - cwd_fd, - path, - flags.to_flags(), - 0o666, - ) { - Ok(f) => f, - Err(e) => { - let sys_err = e.to_shell_system_error(); - return Ok(Some(Builtin::cmd_write_failing_error( - interp, - this, - format_args!( - "bun: {}: {}", - sys_err.message, - bstr::BStr::new(path.as_bytes()) - ), - ))); - } - }; - interp.as_cmd_mut(this).redirection_fd = Some(CowFd::init(redirfd)); - set_stdio_from_redirect(stdio, flags, redirfd); + return Ok(Self::open_redirect_path(interp, this, stdio, flags, path)); } } Ok(None) } + /// Opens `path` with the flags of the redirect operator. `Some` is the queued error write. + fn open_redirect_path( + interp: &Interpreter, + this: NodeId, + stdio: &mut [Stdio; 3], + flags: ast::RedirectFlags, + path: &bun_core::ZStr, + ) -> Option { + let cwd_fd = interp.as_cmd(this).base.shell().cwd_fd; + let redirfd = + match crate::shell::interpreter::shell_openat(cwd_fd, path, flags.to_flags(), 0o666) { + Ok(f) => f, + Err(e) => { + let sys_err = e.to_shell_system_error(); + return Some(Builtin::cmd_write_failing_error( + interp, + this, + format_args!( + "bun: {}: {}", + sys_err.message, + bstr::BStr::new(path.as_bytes()) + ), + )); + } + }; + interp.as_cmd_mut(this).redirection_fd = Some(CowFd::init(redirfd)); + set_stdio_from_redirect(stdio, flags, redirfd); + None + } + /// Called by `Builtin::done` / subprocess exit handler. pub(crate) fn on_exec_done(interp: &Interpreter, this: NodeId, exit_code: ExitCode) -> Yield { log!("Cmd {} execDone exit={}", this, exit_code); @@ -1123,6 +1144,20 @@ fn is_assignment_word(atom: &ast::Atom) -> bool { .all(|&b| b.is_ascii_alphanumeric() || b == b'_') } +/// The path of a blob that `Stdio::extract_blob` lowers to `Stdio::Path`. +fn file_path(blob: &crate::webcore::blob::Any) -> Option<&[u8]> { + if !blob.needs_to_read_file() { + return None; + } + let crate::webcore::blob::store::Data::File(file) = &blob.store()?.data else { + return None; + }; + match &file.pathlike { + crate::node::PathOrFileDescriptor::Path(path) => Some(path.slice()), + crate::node::PathOrFileDescriptor::Fd(_) => None, + } +} + fn set_stdio_from_redirect(stdio: &mut [Stdio; 3], flags: ast::RedirectFlags, fd: bun_sys::Fd) { if flags.stdin() { stdio[0] = Stdio::Fd(fd); diff --git a/src/runtime/shell/subproc.rs b/src/runtime/shell/subproc.rs index 41b4f2ad9eb6..bdc31292a7cb 100644 --- a/src/runtime/shell/subproc.rs +++ b/src/runtime/shell/subproc.rs @@ -632,6 +632,9 @@ impl ShellSubprocess { true }; + // `${Bun.file(path)}` is a path word, and `Cmd` opens a `Response` over a file itself. + debug_assert!(!stdio_guard.iter().any(|s| matches!(s, Stdio::Path(_)))); + // Hoist asSpawnOption results so a later one failing doesn't strand an earlier // Windows *uv.Pipe in an unbound temporary inside the struct initializer. // `mut` only for the Windows-only `.deinit()` rollback below. diff --git a/src/spawn/process.rs b/src/spawn/process.rs index 8235db3b16e4..9e03e9b13b31 100644 --- a/src/spawn/process.rs +++ b/src/spawn/process.rs @@ -2083,11 +2083,6 @@ mod spawn_process_body { for fd_i in 0..3usize { let pipe_flags = uv::UV_CREATE_PIPE | uv::UV_READABLE_PIPE | uv::UV_WRITABLE_PIPE; let stdio: &mut uv::uv_stdio_container_t = &mut stdio_containers[fd_i]; - let flag: c_int = if fd_i == 0 { - uv::O::RDONLY - } else { - uv::O::WRONLY - }; let mut treat_as_dup: bool = false; @@ -2117,36 +2112,20 @@ mod spawn_process_body { stdio.flags = uv::UV_IGNORE; } WindowsStdio::Path(path) => { - let mut req = uv::fs_t::uninitialized(); // Cleanup is via manual calls at each exit path, so `?` here // would leak any fds opened by earlier loop iterations. - let path_z = match bun_sys::to_posix_path(path) { - Ok(p) => p, + let fd = match open_path_slot(loop_, path, fd_i) { + Ok(Ok(fd)) => fd, + Ok(Err(err)) => { + cleanup_uv_files(&uv_files_to_close, loop_); + return Ok(Err(err)); + } Err(e) => { cleanup_uv_files(&uv_files_to_close, loop_); - return Err(crate::Error::Sys(e)); + return Err(e); } }; - // SAFETY: `req` is a fresh `fs_t`, `loop_` is the live uv - // loop, `path_z` is NUL-terminated and outlives the call - // (sync — no callback). - let rc = unsafe { - uv::uv_fs_open( - loop_, - &mut req, - path_z.as_ptr(), - flag | uv::O::CREAT, - 0o644, - None, - ) - }; - req.deinit(); - if let Some(err) = rc.to_error(bun_sys::Tag::open) { - cleanup_uv_files(&uv_files_to_close, loop_); - return Ok(Err(err)); - } stdio.flags = uv::UV_INHERIT_FD; - let fd = rc.int(); uv_files_to_close.push(fd); stdio.data.fd = fd; } @@ -2186,7 +2165,6 @@ mod spawn_process_body { for (i, ipc) in options.extra_fds.iter().enumerate() { let stdio: &mut uv::uv_stdio_container_t = &mut stdio_containers[3 + i]; - let flag: c_int = uv::O::RDWR; match ipc { WindowsStdio::Dup2(_) => panic!("TODO dup2 extra fd"), @@ -2198,34 +2176,19 @@ mod spawn_process_body { stdio.flags = uv::UV_IGNORE; } WindowsStdio::Path(path) => { - let mut req = uv::fs_t::uninitialized(); // See stdio loop above: manual cleanup on every exit path. - let path_z = match bun_sys::to_posix_path(path) { - Ok(p) => p, + let fd = match open_path_slot(loop_, path, 3 + i) { + Ok(Ok(fd)) => fd, + Ok(Err(err)) => { + cleanup_uv_files(&uv_files_to_close, loop_); + return Ok(Err(err)); + } Err(e) => { cleanup_uv_files(&uv_files_to_close, loop_); - return Err(crate::Error::Sys(e)); + return Err(e); } }; - // SAFETY: `req` is a fresh `fs_t`, `loop_` is the live uv loop, - // `path_z` is NUL-terminated and outlives the call (sync). - let rc = unsafe { - uv::uv_fs_open( - loop_, - &mut req, - path_z.as_ptr(), - flag | uv::O::CREAT, - 0o644, - None, - ) - }; - req.deinit(); - if let Some(err) = rc.to_error(bun_sys::Tag::open) { - cleanup_uv_files(&uv_files_to_close, loop_); - return Ok(Err(err)); - } stdio.flags = uv::UV_INHERIT_FD; - let fd = rc.int(); uv_files_to_close.push(fd); stdio.data.fd = fd; } @@ -2431,6 +2394,42 @@ mod spawn_process_body { } } + /// Opens the file of a `Path` stdio for child fd `slot`. + #[cfg(windows)] + fn open_path_slot( + loop_: *mut uv::uv_loop_t, + path: &[u8], + slot: usize, + ) -> Result, crate::Error> { + let path_z = bun_sys::to_posix_path(path).map_err(crate::Error::Sys)?; + let open = |flags: c_int| { + let mut req = uv::fs_t::uninitialized(); + // SAFETY: `req` is a fresh `fs_t`, `loop_` is the live uv loop, + // `path_z` is NUL-terminated and outlives the call (sync — no callback). + let rc = + unsafe { uv::uv_fs_open(loop_, &mut req, path_z.as_ptr(), flags, 0o644, None) }; + req.deinit(); + rc + }; + let flags = uv::O::from_bun_o(bun_spawn_sys::path_slot_open_flags(slot)); + let rc = open(flags); + // CREATE_ALWAYS refuses a hidden file (https://github.com/oven-sh/bun/issues/6820). + if flags & uv::O::TRUNC != 0 && rc.errno() == Some(bun_sys::E::EPERM) { + let in_place = open(flags & !(uv::O::CREAT | uv::O::TRUNC)); + if !in_place.is_err() { + let fd = Fd::from_uv(in_place.int()); + if bun_sys::ftruncate(fd, 0).is_ok() { + return Ok(Ok(in_place.int())); + } + bun_io::Closer::close(fd, loop_); + } + } + Ok(match rc.to_error(bun_sys::Tag::open) { + Some(err) => Err(err), + None => Ok(rc.int()), + }) + } + pub mod sync { use super::*; // `Options.windows` is `WindowsOptions` on Windows; surface it under the diff --git a/src/spawn_sys/lib.rs b/src/spawn_sys/lib.rs index 0caf9805c495..cda14a026ba3 100644 --- a/src/spawn_sys/lib.rs +++ b/src/spawn_sys/lib.rs @@ -190,5 +190,5 @@ pub use spawn_process::spawn_process_posix; pub use spawn_process::uv_getrusage; pub use spawn_process::{ Dup2, ExtraPipe, PidT, PosixSpawnOptions, PosixSpawnResult, PosixStdio, Rusage, RusageFields, - StdioKind, rusage_zeroed, + StdioKind, path_slot_open_flags, rusage_zeroed, }; diff --git a/src/spawn_sys/spawn_process.rs b/src/spawn_sys/spawn_process.rs index d1cc73ec0371..cd5e62d67102 100644 --- a/src/spawn_sys/spawn_process.rs +++ b/src/spawn_sys/spawn_process.rs @@ -448,6 +448,25 @@ impl PosixStdio { } } +/// `bun_sys::O` flags that open a `Path` stdio at child fd `slot`, on every platform. +pub const fn path_slot_open_flags(slot: usize) -> i32 { + use bun_sys::O; + match slot { + 0 => O::RDONLY | O::CREAT, + 1 | 2 => O::WRONLY | O::CREAT | O::TRUNC, // like `>` + _ => O::RDWR | O::CREAT, // like `n<>file`: the child can read it or write it + } +} + +#[cfg(windows)] +const _: () = { + use bun_libuv_sys::O; + assert!(O::from_bun_o(path_slot_open_flags(0)) == O::RDONLY | O::CREAT); + assert!(O::from_bun_o(path_slot_open_flags(1)) == O::WRONLY | O::CREAT | O::TRUNC); + assert!(O::from_bun_o(path_slot_open_flags(2)) == O::WRONLY | O::CREAT | O::TRUNC); + assert!(O::from_bun_o(path_slot_open_flags(3)) == O::RDWR | O::CREAT); +}; + #[derive(Default)] pub struct PosixSpawnResult { pub pid: PidT, @@ -798,7 +817,7 @@ pub unsafe fn spawn_process_posix( actions.open_z(fileno, c"/dev/null", flag | bun_sys::O::CREAT as u32, 0o664)?; } PosixStdio::Path(path) => { - actions.open(fileno, path, flag | bun_sys::O::CREAT as u32, 0o664)?; + actions.open(fileno, path, path_slot_open_flags(i) as u32, 0o664)?; } PosixStdio::Buffer => { #[cfg(any(target_os = "linux", target_os = "android"))] @@ -955,12 +974,7 @@ pub unsafe fn spawn_process_posix( extra_fds.push(ExtraPipe::Unavailable); } PosixStdio::Path(path) => { - actions.open( - fileno, - path, - (bun_sys::O::RDWR | bun_sys::O::CREAT) as u32, - 0o664, - )?; + actions.open(fileno, path, path_slot_open_flags(3 + i) as u32, 0o664)?; extra_fds.push(ExtraPipe::Unavailable); } PosixStdio::Ipc | PosixStdio::Buffer | PosixStdio::SocketFd => { diff --git a/test/js/bun/shell/file-io.test.ts b/test/js/bun/shell/file-io.test.ts index 5b10f0351a8e..10a7ee4027c2 100644 --- a/test/js/bun/shell/file-io.test.ts +++ b/test/js/bun/shell/file-io.test.ts @@ -1,7 +1,8 @@ +import { $ } from "bun"; import { describe, expect, test } from "bun:test"; import { bunEnv, bunExe, isPosix, tempDir } from "harness"; import * as fs from "node:fs"; -import { join } from "node:path"; +import { basename, join } from "node:path"; import { createTestBuilder } from "./test_builder"; const TestBuilder = createTestBuilder(import.meta.path); @@ -261,3 +262,97 @@ test.concurrent("write completion survives dropping the redirect writer's last r exitCode: 0, }); }); + +// An external command redirected to Bun.file(path), or to a Response that wraps one, opens +// the file like `> path` does, so the operator decides: read, replace or append. +describe.each([ + { target: "Bun.file(path)", file: (path: string) => Bun.file(path) }, + { target: "a Response that wraps Bun.file(path)", file: (path: string) => new Response(Bun.file(path)) }, +])("external command redirected to $target", ({ file }) => { + const OLD = "OLD-OLD-OLD-OLD\n"; + // The children use fs on the fd numbers: process.stdout and process.stdin load slowly in a debug build. + const writeStdout = `require("fs").writeSync(1, "new\\n")`; + const writeStderr = `require("fs").writeSync(2, "new\\n")`; + const writeBoth = `const fs = require("fs"); fs.writeSync(1, "out\\n"); fs.writeSync(2, "err\\n")`; + const echoStdin = `const fs = require("fs"); fs.writeSync(1, fs.readFileSync(0))`; + + test.concurrent("> replaces the file", async () => { + using dir = tempDir("shell-file-redirect", { "out.txt": OLD }); + const out = join(String(dir), "out.txt"); + const { exitCode } = await $`${bunExe()} -e ${writeStdout} > ${file(out)}`.env(bunEnv).nothrow().quiet(); + expect(fs.readFileSync(out, "utf8")).toBe("new\n"); + expect(exitCode).toBe(0); + }); + + test.concurrent("2> replaces the file", async () => { + using dir = tempDir("shell-file-redirect", { "err.txt": OLD }); + const err = join(String(dir), "err.txt"); + const { exitCode } = await $`${bunExe()} -e ${writeStderr} 2> ${file(err)}`.env(bunEnv).nothrow().quiet(); + expect(fs.readFileSync(err, "utf8")).toBe("new\n"); + expect(exitCode).toBe(0); + }); + + test.concurrent(">> appends to the file", async () => { + using dir = tempDir("shell-file-redirect", { "out.txt": OLD }); + const out = join(String(dir), "out.txt"); + const { exitCode } = await $`${bunExe()} -e ${writeStdout} >> ${file(out)}`.env(bunEnv).nothrow().quiet(); + expect(fs.readFileSync(out, "utf8")).toBe(OLD + "new\n"); + expect(exitCode).toBe(0); + }); + + test.concurrent("&> sends stdout and stderr to the file", async () => { + using dir = tempDir("shell-file-redirect", { "both.txt": OLD }); + const both = join(String(dir), "both.txt"); + const { exitCode } = await $`${bunExe()} -e ${writeBoth} &> ${file(both)}`.env(bunEnv).nothrow().quiet(); + expect(fs.readFileSync(both, "utf8").split("\n").sort()).toEqual(["", "err", "out"]); + expect(exitCode).toBe(0); + }); + + test.concurrent("< reads the file", async () => { + using dir = tempDir("shell-file-redirect", { "in.txt": OLD }); + const input = join(String(dir), "in.txt"); + const { stdout, exitCode } = await $`${bunExe()} -e ${echoStdin} < ${file(input)}`.env(bunEnv).nothrow().quiet(); + expect({ stdout: stdout.toString(), file: fs.readFileSync(input, "utf8") }).toEqual({ stdout: OLD, file: OLD }); + expect(exitCode).toBe(0); + }); + + test.concurrent("< fails on a file that does not exist and does not create it", async () => { + using dir = tempDir("shell-file-redirect", {}); + const missing = join(String(dir), "missing.txt"); + const { stdout, stderr, exitCode } = await $`${bunExe()} -e ${echoStdin} < ${file(missing)}` + .env(bunEnv) + .nothrow() + .quiet(); + expect({ stdout: stdout.toString(), stderr: stderr.toString(), created: fs.existsSync(missing) }).toEqual({ + stdout: "", + stderr: `bun: No such file or directory: ${missing}`, + created: false, + }); + expect(exitCode).toBe(1); + }); + + // Like `> out.txt`: the cwd of the shell, not the cwd of the process. + test.concurrent("a relative path resolves against the cwd of the shell", async () => { + using dir = tempDir("shell-file-redirect", {}); + // No other test uses this name. A build that resolves it against the cwd of the process creates it there. + const name = `${basename(String(dir))}.txt`; + const inShellCwd = join(String(dir), name); + const inProcessCwd = join(process.cwd(), name); + try { + const write = await $`${bunExe()} -e ${writeStdout} > ${file(name)}` + .cwd(String(dir)) + .env(bunEnv) + .nothrow() + .quiet(); + const read = await $`${bunExe()} -e ${echoStdin} < ${file(name)}`.cwd(String(dir)).env(bunEnv).nothrow().quiet(); + expect({ + written: fs.existsSync(inShellCwd) && fs.readFileSync(inShellCwd, "utf8"), + read: read.stdout.toString(), + inProcessCwd: fs.existsSync(inProcessCwd), + exitCodes: [write.exitCode, read.exitCode], + }).toEqual({ written: "new\n", read: "new\n", inProcessCwd: false, exitCodes: [0, 0] }); + } finally { + fs.rmSync(inProcessCwd, { force: true }); + } + }); +}); diff --git a/test/js/bun/spawn/spawn-stdio-file.test.ts b/test/js/bun/spawn/spawn-stdio-file.test.ts new file mode 100644 index 000000000000..57a5a529581a --- /dev/null +++ b/test/js/bun/spawn/spawn-stdio-file.test.ts @@ -0,0 +1,353 @@ +// A `Bun.file(path)` at a stdio slot is opened for the child by path. The slot +// decides the open flags: stdin reads, stdout and stderr replace the file, and +// an extra slot is opened for reading and writing with its content kept. +import type { BunFile } from "bun"; +import { describe, expect, test } from "bun:test"; +import { bunEnv, bunExe, isWindows, tempDir } from "harness"; +import { closeSync, existsSync, openSync, readFileSync, symlinkSync } from "node:fs"; +import { join } from "node:path"; + +const OLD = "OLD-CONTENT-0123456789ABCDEF"; +// The children use fs on the fd numbers: process.stdout and process.stdin load slowly in a debug build. +const writeStdout = `require("fs").writeSync(1, "NEW")`; +const echoStdin = `const fs = require("fs"); fs.writeSync(1, fs.readFileSync(0))`; + +// Writes "NEW" to `fd`. On the other stream it reports how large the file at `fd` was when the child started. +const sizeThenWrite = (fd: 1 | 2) => + `const fs = require("fs"); fs.writeSync(${fd === 1 ? 2 : 1}, String(fs.fstatSync(${fd}).size)); fs.writeSync(${fd}, "NEW")`; + +describe("Bun.file(path) as stdout or stderr replaces the file", () => { + // The other output stream is a pipe: the child reports on it. + const forms: { slot: string; fd: 1 | 2; stdio: (file: BunFile) => object }[] = [ + { slot: "stdout", fd: 1, stdio: file => ({ stdout: file, stderr: "pipe" }) }, + { slot: "stderr", fd: 2, stdio: file => ({ stderr: file, stdout: "pipe" }) }, + { slot: "stdio[1]", fd: 1, stdio: file => ({ stdio: ["ignore", file, "pipe"] }) }, + { slot: "stdio[2]", fd: 2, stdio: file => ({ stdio: ["ignore", "pipe", file] }) }, + ]; + // The file is empty when the child starts, and holds only the new output when the child exits. + const replaced = { sizeAtStart: "0", file: "NEW", exitCode: 0 }; + + describe.concurrent("Bun.spawn", () => { + test.each(forms)("$slot", async ({ fd, stdio }) => { + using dir = tempDir("spawn-stdio-file", { "out.txt": OLD }); + const out = join(String(dir), "out.txt"); + await using proc = Bun.spawn<"ignore", "pipe", "pipe">({ + cmd: [bunExe(), "-e", sizeThenWrite(fd)], + env: bunEnv, + ...stdio(Bun.file(out)), + }); + const [sizeAtStart, exitCode] = await Promise.all([(fd === 1 ? proc.stderr : proc.stdout).text(), proc.exited]); + expect({ sizeAtStart, file: readFileSync(out, "utf8"), exitCode }).toEqual(replaced); + }); + + test("a child that writes nothing leaves an empty file", async () => { + using dir = tempDir("spawn-stdio-file", { "out.txt": OLD }); + const out = join(String(dir), "out.txt"); + await using proc = Bun.spawn({ cmd: [bunExe(), "-e", "0"], env: bunEnv, stdout: Bun.file(out) }); + const exitCode = await proc.exited; + expect(readFileSync(out, "utf8")).toBe(""); + expect(exitCode).toBe(0); + }); + + // The way to filter a file in place: the file is read before stdout empties it. + test("stdin from the bytes of the file that stdout replaces", async () => { + using dir = tempDir("spawn-stdio-file", { "both.txt": OLD }); + const both = join(String(dir), "both.txt"); + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", `const fs = require("fs"); fs.writeSync(1, fs.readFileSync(0, "utf8").toLowerCase())`], + env: bunEnv, + stdin: await Bun.file(both).bytes(), + stdout: Bun.file(both), + stderr: "inherit", + }); + const exitCode = await proc.exited; + expect(readFileSync(both, "utf8")).toBe(OLD.toLowerCase()); + expect(exitCode).toBe(0); + }); + }); + + describe("Bun.spawnSync", () => { + test.each(forms)("$slot", ({ fd, stdio }) => { + using dir = tempDir("spawn-stdio-file", { "out.txt": OLD }); + const out = join(String(dir), "out.txt"); + const { stdout, stderr, exitCode } = Bun.spawnSync<"ignore", "pipe", "pipe">({ + cmd: [bunExe(), "-e", sizeThenWrite(fd)], + env: bunEnv, + ...stdio(Bun.file(out)), + }); + const sizeAtStart = (fd === 1 ? stderr : stdout).toString(); + expect({ sizeAtStart, file: readFileSync(out, "utf8"), exitCode }).toEqual(replaced); + }); + }); + + // Bun opens the file before it starts the command, so a command that cannot start leaves an empty file. + // A command that is not in PATH fails before the open. + test.each([ + { name: "is already empty when the command cannot be executed", command: "./no-such-command", file: "" }, + { name: "is kept when the command is not in PATH", command: "no-such-command-for-spawn-stdio-file", file: OLD }, + ])("the file $name", ({ command, file }) => { + using dir = tempDir("spawn-stdio-file", { "out.txt": OLD }); + const out = join(String(dir), "out.txt"); + let code: unknown; + try { + Bun.spawnSync({ cmd: [command], cwd: String(dir), env: bunEnv, stdout: Bun.file(out) }); + } catch (error) { + code = (error as NodeJS.ErrnoException).code; + } + expect({ code, file: readFileSync(out, "utf8") }).toEqual({ code: "ENOENT", file }); + }); + + // stdout and stderr empty the file before the child reads stdin, so one regular file at both is an error. + describe("the same Bun.file(path) as stdin and as stdout or stderr", () => { + type Spawned = { exitCode: number | null; exited?: Promise }; + const slots: { name: string; stdio: (file: BunFile) => object }[] = [ + { name: "stdin and stdout", stdio: file => ({ stdin: file, stdout: file }) }, + { name: "stdin and stderr", stdio: file => ({ stdin: file, stderr: file }) }, + { name: "stdio[0] and stdio[1]", stdio: file => ({ stdio: [file, file, "inherit"] }) }, + { name: "stdio[0] and stdio[2]", stdio: file => ({ stdio: [file, "ignore", file] }) }, + ]; + const sameFile = "stdin cannot be the same file as stdout or stderr"; + + describe.each(["spawn", "spawnSync"] as const)("Bun.%s", method => { + const run = (path: string, stdio = slots[0].stdio, script = echoStdin) => + (Bun[method] as (options: object) => Spawned)({ + cmd: [bunExe(), "-e", script], + env: bunEnv, + ...stdio(Bun.file(path)), + }); + + test.each(slots)("$name: throws and keeps the file", ({ stdio }) => { + using dir = tempDir("spawn-stdio-file", { "both.txt": OLD }); + const both = join(String(dir), "both.txt"); + expect(() => run(both, stdio)).toThrow( + /stdin cannot be the same file as stdout or stderr: the command would read an empty ".*both\.txt"/, + ); + expect(readFileSync(both, "utf8")).toBe(OLD); + }); + + test("throws for an empty file", () => { + using dir = tempDir("spawn-stdio-file", { "empty.txt": "" }); + expect(() => run(join(String(dir), "empty.txt"))).toThrow(sameFile); + }); + + test("throws for a file that does not exist, and does not create it", () => { + using dir = tempDir("spawn-stdio-file", {}); + const missing = join(String(dir), "missing.txt"); + expect(() => run(missing)).toThrow(sameFile); + expect(existsSync(missing)).toBe(false); + }); + + test.skipIf(isWindows)("throws for a symlink to a file, and keeps the file", () => { + using dir = tempDir("spawn-stdio-file", { "target.txt": OLD }); + const link = join(String(dir), "link.txt"); + symlinkSync(join(String(dir), "target.txt"), link); + expect(() => run(link)).toThrow(sameFile); + expect(readFileSync(link, "utf8")).toBe(OLD); + }); + + // The open cannot empty a device, so the command loses no input. + test("runs the command when the path is a device", async () => { + const proc = run("/dev/null", slots[0].stdio, "process.exit(42)"); + expect(await (proc.exited ?? proc.exitCode)).toBe(42); + }); + + // Only a regular file and a missing file throw. Every other path goes to the open. + test.skipIf(isWindows)("a path below a file fails in the open, with ENOTDIR", () => { + using dir = tempDir("spawn-stdio-file", { "file.txt": OLD }); + let code: unknown; + try { + run(join(String(dir), "file.txt", "below")); + } catch (error) { + code = (error as NodeJS.ErrnoException).code; + } + expect(code).toBe("ENOTDIR"); + }); + }); + + // On POSIX the child can open a relative path under `cwd`, where a stat from the parent finds another file. + // Here `data` is a directory for the parent and a regular file in `sub`. + test.skipIf(isWindows).each(["spawn", "spawnSync"] as const)( + "Bun.%s throws for a relative path with cwd, and keeps the file", + async method => { + using dir = tempDir("spawn-stdio-file", { "data/placeholder.txt": "", "sub/data": OLD }); + const script = ` + const options = { + cmd: [process.execPath, "-e", ${JSON.stringify(echoStdin)}], + cwd: "sub", + stdin: Bun.file("data"), + stdout: Bun.file("data"), + }; + let message = ""; + try { + await Bun.${method}(options).exited; + } catch (error) { + message = error.message; + } + console.log(JSON.stringify({ message, file: require("fs").readFileSync("sub/data", "utf8") })); + `; + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", script], + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "inherit", + }); + const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); + expect(JSON.parse(stdout)).toEqual({ message: expect.stringContaining(sameFile), file: OLD }); + expect(exitCode).toBe(0); + }, + ); + + // `terminal` takes stdin, stdout and stderr, so Bun opens neither file. + test("with terminal, the command runs and the file is kept", async () => { + using dir = tempDir("spawn-stdio-file", { "both.txt": OLD }); + const both = join(String(dir), "both.txt"); + const proc = Bun.spawn({ + cmd: [bunExe(), "-e", "process.exit(42)"], + env: bunEnv, + terminal: { data() {} }, + stdin: Bun.file(both), + stdout: Bun.file(both), + }); + const exitCode = await proc.exited; + proc.terminal?.close(); + expect({ exitCode, file: readFileSync(both, "utf8") }).toEqual({ exitCode: 42, file: OLD }); + }); + }); + + describe.skipIf(!isWindows)("on Windows", () => { + const attrib = (dir: string, change: string) => + Bun.spawnSync(["cmd", "/C", `attrib ${change} out.txt`], { cwd: dir, stdio: ["ignore", "ignore", "ignore"] }) + .exitCode; + + // CREATE_ALWAYS refuses a hidden file, so bun opens it in place and truncates it. + test("a hidden file is replaced", () => { + using dir = tempDir("spawn-stdio-file", { "out.txt": OLD }); + const out = join(String(dir), "out.txt"); + expect(attrib(String(dir), "+h")).toBe(0); + const { exitCode } = Bun.spawnSync({ cmd: [bunExe(), "-e", writeStdout], env: bunEnv, stdout: Bun.file(out) }); + expect(readFileSync(out, "utf8")).toBe("NEW"); + expect(exitCode).toBe(0); + }); + + test("a read-only file fails with EPERM and keeps its content", () => { + using dir = tempDir("spawn-stdio-file", { "out.txt": OLD }); + const out = join(String(dir), "out.txt"); + expect(attrib(String(dir), "+r")).toBe(0); + let code: unknown; + try { + Bun.spawnSync({ cmd: [bunExe(), "-e", writeStdout], env: bunEnv, stdout: Bun.file(out) }); + } catch (error) { + code = (error as NodeJS.ErrnoException).code; + } finally { + // tempDir cannot remove a read-only file on Windows. + attrib(String(dir), "-r"); + } + expect({ code, file: readFileSync(out, "utf8") }).toEqual({ code: "EPERM", file: OLD }); + }); + }); +}); + +describe.concurrent("slots that keep the content of the file", () => { + test("Bun.file(path) as stdin is read and not truncated", async () => { + using dir = tempDir("spawn-stdio-file", { "in.txt": OLD }); + const input = join(String(dir), "in.txt"); + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", echoStdin], + env: bunEnv, + stdin: Bun.file(input), + stdout: "pipe", + stderr: "inherit", + }); + const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); + expect({ stdout, file: readFileSync(input, "utf8") }).toEqual({ stdout: OLD, file: OLD }); + expect(exitCode).toBe(0); + }); + + test("Bun.file(path) at index 3 keeps the file, and creates a file that does not exist", async () => { + using dir = tempDir("spawn-stdio-file", { "existing.txt": OLD }); + const files: Record = {}; + for (const name of ["existing.txt", "created.txt"]) { + const extra = join(String(dir), name); + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", "0"], + env: bunEnv, + stdio: ["ignore", "inherit", "inherit", Bun.file(extra)], + }); + expect(await proc.exited).toBe(0); + files[name] = readFileSync(extra, "utf8"); + } + expect(files).toEqual({ "existing.txt": OLD, "created.txt": "" }); + }); + + // Windows: same exclusion as "Bun.file(path) at index >= 3 is readable in the child" in spawn.test.ts. + test.skipIf(isWindows)("a write through Bun.file(path) at index 3 keeps the rest of the file", async () => { + using dir = tempDir("spawn-stdio-file", { "extra.txt": OLD }); + const extra = join(String(dir), "extra.txt"); + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", `require("fs").writeSync(3, "NEW")`], + env: bunEnv, + stdio: ["ignore", "inherit", "inherit", Bun.file(extra)], + }); + const exitCode = await proc.exited; + expect(readFileSync(extra, "utf8")).toBe("NEW" + OLD.slice(3)); + expect(exitCode).toBe(0); + }); + + // The way to append or to write in place: the caller opens the file and passes the fd. + test.each([ + { flags: "r+", as: "a number", expected: "NEW" + OLD.slice(3) }, + { flags: "r+", as: "Bun.file(fd)", expected: "NEW" + OLD.slice(3) }, + { flags: "a", as: "a number", expected: OLD + "NEW" }, + ])(`a file descriptor opened with "$flags" as stdout, passed as $as`, async ({ flags, as, expected }) => { + using dir = tempDir("spawn-stdio-file", { "out.txt": OLD }); + const out = join(String(dir), "out.txt"); + const fd = openSync(out, flags); + try { + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", writeStdout], + env: bunEnv, + stdout: as === "a number" ? fd : Bun.file(fd), + }); + const exitCode = await proc.exited; + expect(readFileSync(out, "utf8")).toBe(expected); + expect(exitCode).toBe(0); + } finally { + closeSync(fd); + } + }); + + // One fd is one open file: stdout and stderr share its offset. + test("one file descriptor as stdout and stderr keeps both streams", async () => { + using dir = tempDir("spawn-stdio-file", {}); + const out = join(String(dir), "out.txt"); + const fd = openSync(out, "w"); + try { + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", `const fs = require("fs"); fs.writeSync(1, "out\\n"); fs.writeSync(2, "err\\n")`], + env: bunEnv, + stdout: fd, + stderr: fd, + }); + const exitCode = await proc.exited; + expect(readFileSync(out, "utf8").split("\n").sort()).toEqual(["", "err", "out"]); + expect(exitCode).toBe(0); + } finally { + closeSync(fd); + } + }); +}); + +describe("Bun.spawnSync, a slot above stderr", () => { + test("Bun.file(path) at index 4 keeps the file", () => { + using dir = tempDir("spawn-stdio-file", { "extra.txt": OLD }); + const extra = join(String(dir), "extra.txt"); + const { exitCode } = Bun.spawnSync({ + cmd: [bunExe(), "-e", "0"], + env: bunEnv, + stdio: ["ignore", "inherit", "inherit", "ignore", Bun.file(extra)], + }); + expect(readFileSync(extra, "utf8")).toBe(OLD); + expect(exitCode).toBe(0); + }); +});