Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
7 changes: 6 additions & 1 deletion src/runtime/cli/filter_run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -867,6 +867,8 @@ pub(crate) fn run_scripts_with_filter(

// SAFETY: Transpiler::init always sets `env` to the process-lifetime singleton.
let env_ptr: *mut bun_dotenv::Loader = this_transpiler.env;
// SAFETY: env_ptr is the process-lifetime DotEnv loader.
RunCommand::forward_color_to_piped_scripts(unsafe { &mut *env_ptr });
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
let event_loop = MiniEventLoopMod::init_global(
// SAFETY: see above; `&'static mut` reborrow of the singleton for first-init only.
Some(unsafe { &mut *env_ptr }),
Expand Down Expand Up @@ -907,14 +909,17 @@ pub(crate) fn run_scripts_with_filter(
remaining_scripts: 0,
draw_buf: Vec::new(),
last_lines_written: 0,
// Redraw renderer emits cursor-up/erase-line sequences; those only make
// sense on a real terminal. `FORCE_COLOR` (which we now inject for
// child scripts) must not enable it on a pipe.
Comment thread
robobun marked this conversation as resolved.
Resolved
pretty_output: {
#[cfg(windows)]
{
windows_is_terminal() && Output::enable_ansi_colors_stdout()
}
#[cfg(not(windows))]
{
Output::enable_ansi_colors_stdout()
Output::is_stdout_tty() && Output::enable_ansi_colors_stdout()
}
},
shell_bin,
Expand Down
2 changes: 2 additions & 0 deletions src/runtime/cli/multi_run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -802,6 +802,8 @@ pub(crate) fn run(ctx: &mut Command::ContextData) -> Result<core::convert::Infal

// SAFETY: transpiler.env is a process-lifetime *mut Loader set in init.
let env_ptr: *mut DotEnvLoader = this_transpiler.env;
// SAFETY: env_ptr is the process-lifetime DotEnv loader; no other borrow is live yet.
RunCommand::forward_color_to_piped_scripts(unsafe { &mut *env_ptr });
let event_loop = bun_event_loop::MiniEventLoop::init_global(
// SAFETY: env_ptr is the process-lifetime DotEnv loader; no other borrow of it is live yet.
Some(unsafe { &mut *env_ptr }),
Expand Down
29 changes: 29 additions & 0 deletions src/runtime/cli/run_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1917,6 +1917,35 @@ impl RunCommand {
Ok(())
}

/// `--filter` / `--parallel` pipe script stdio, so isatty() in the script
/// is false. Forward the parent's color decision via `FORCE_COLOR` unless
/// the user set `FORCE_COLOR`/`NO_COLOR`/`NODE_DISABLE_COLORS` themselves.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub fn forward_color_to_piped_scripts(env: &mut DotEnv::Loader) {
if !(Output::is_stdout_tty() && Output::enable_ansi_colors_stdout()) {
return;
}
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
if env.map.get(b"FORCE_COLOR").is_some()
|| env.map.get(b"NO_COLOR").is_some_and(|v| !v.is_empty())
|| env
.map
.get(b"NODE_DISABLE_COLORS")
.is_some_and(|v| !v.is_empty())
{
return;
}
use bun_core::output::{ColorDepth, Source};
let depth: &[u8] = match Source::color_depth() {
ColorDepth::C16m => b"3",
ColorDepth::C256 => b"2",
ColorDepth::C16 => b"1",
// Windows terminals typically don't set TERM/COLORTERM; every
// supported Windows build has truecolor (see is_color_terminal).
Comment thread
robobun marked this conversation as resolved.
Resolved
ColorDepth::None if cfg!(windows) => b"3",
ColorDepth::None => b"1",
};
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
let _ = env.map.put(b"FORCE_COLOR", depth);
}

/// Builds a new PATH with `node_modules/.bin` for each ancestor of `cwd`
/// (plus `package_json_dir` and the bun-node shim dir) prepended, returns
/// it as an owned buffer, and writes the original PATH out via
Expand Down
270 changes: 214 additions & 56 deletions test/cli/run/filter-workspace.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,25 +87,16 @@ function runInCwdSuccess({
antipattern,
command = ["present"],
auto = false,
env = {},
elideCount,
}: {
cwd: string;
pattern: string | string[];
target_pattern: RegExp | RegExp[];
antipattern?: RegExp | RegExp[];
command?: string[];
auto?: boolean;
env?: Record<string, string | undefined>;
elideCount?: number;
}) {
const cmd = auto ? [bunExe()] : [bunExe(), "run"];

// Add elide-lines first if specified
if (elideCount !== undefined) {
cmd.push("--elide-lines", elideCount.toString());
}

if (Array.isArray(pattern)) {
for (const p of pattern) {
cmd.push("--filter", p);
Expand All @@ -121,7 +112,7 @@ function runInCwdSuccess({
const { exitCode, stdout, stderr } = spawnSync({
cwd,
cmd,
env: { ...bunEnv, ...env },
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
Expand Down Expand Up @@ -471,7 +462,7 @@ describe("bun", () => {
expect(exitCode).toBe(23);
});

function runElideLinesTest({
async function runElideLinesTest({
elideLines,
target_pattern,
antipattern,
Expand All @@ -498,63 +489,58 @@ describe("bun", () => {
}),
});

if (process.platform === "win32") {
// Windows spawnSync pipes stdout, so `windowsIsTerminal()` returns false,
// `state.pretty_output` is false, and `redraw()` short-circuits before
// ever emitting elision output. `target_pattern` is intentionally NOT
// iterated here: every caller bundles TTY-only regexes such as
// `/\[N lines elided\]/` that would never appear in piped Windows output
// and would fail the test for the wrong reason. The hardcoded log_line
// match covers the non-TTY subset of every caller's target_pattern.
// `antipattern` is iterated because absence-checks remain valid on either
// code path.
const { exitCode, stderr, stdout } = spawnSync({
cwd: dir,
cmd: [bunExe(), "run", "--filter", "./packages/dep0", "--elide-lines", String(elideLines), "script"],
env: { ...bunEnv, FORCE_COLOR: "1", NO_COLOR: "0" },
stdout: "pipe",
stderr: "pipe",
});

const stdoutval = stdout.toString();
expect(stderr.toString()).not.toContain("--elide-lines is only supported in terminal environments");
expect(stdoutval).toMatch(/(?:log_line[\s\S]*?){20}/);
if (antipattern) {
for (const r of antipattern) {
expect(stdoutval).not.toMatch(r);
}
}
expect(exitCode).toBe(0);
return;
}

runInCwdSuccess({
// Elision lives in the redraw renderer which only runs when stdout is a
// real terminal, so spawn on a pty. The final frame is written in full at
// exit so `[N lines elided]` is observable in the collected output.
const decoder = new TextDecoder();
let output = "";
const done = Promise.withResolvers<void>();
await using proc = Bun.spawn({
cmd: [bunExe(), "run", "--elide-lines", String(elideLines), "--filter", "./packages/dep0", "script"],
cwd: dir,
pattern: "./packages/dep0",
env: { FORCE_COLOR: "1", NO_COLOR: "0" },
target_pattern,
antipattern,
command: ["script"],
elideCount: elideLines,
env: { ...bunEnv, FORCE_COLOR: undefined, NO_COLOR: undefined, TERM: "xterm-256color" },
terminal: {
cols: 200,
rows: 40,
data(_t, chunk: Uint8Array) {
output += decoder.decode(chunk, { stream: true });
},
exit() {
done.resolve();
},
},
});
await done.promise;
const exitCode = await proc.exited;
output += decoder.decode();
const stdoutval = Bun.stripANSI(output);
Comment thread
robobun marked this conversation as resolved.
Resolved
for (const r of target_pattern) {
expect(stdoutval).toMatch(r);
}
if (antipattern) {
for (const r of antipattern) {
expect(stdoutval).not.toMatch(r);
}
}
expect(exitCode).toBe(0);
}

test("elides output by default when using --filter", () => {
runElideLinesTest({
test("elides output by default when using --filter", async () => {
await runElideLinesTest({
elideLines: 10,
target_pattern: [/\[10 lines elided\]/, /(?:log_line[\s\S]*?){20}/],
target_pattern: [/\[10 lines elided\]/, /(?:log_line[\s\S]*?){10}/],
});
});

test("respects --elide-lines argument", () => {
runElideLinesTest({
test("respects --elide-lines argument", async () => {
await runElideLinesTest({
elideLines: 15,
target_pattern: [/\[5 lines elided\]/, /(?:log_line[\s\S]*?){20}/],
target_pattern: [/\[5 lines elided\]/, /(?:log_line[\s\S]*?){15}/],
});
});

test("--elide-lines=0 shows all output", () => {
runElideLinesTest({
test("--elide-lines=0 shows all output", async () => {
await runElideLinesTest({
elideLines: 0,
target_pattern: [/(?:log_line[\s\S]*?){20}/],
antipattern: [/lines elided/],
Expand Down Expand Up @@ -662,3 +648,175 @@ describe("bun", () => {
expect(exitCode).toBe(0);
});
});

// https://github.com/oven-sh/bun/issues/10346
// `bun --filter` pipes child stdout/stderr, so the child's isatty() is false and
// tools that gate color on it go monochrome. When the parent is attached to a
// color terminal the filter runner now forwards that decision via FORCE_COLOR.
describe("--filter forwards color to scripts", () => {
function colorFixture() {
return tempDirWithFiles("filter-color", {
packages: {
pkga: {
"probe.js": `process.stdout.write("RESULT " + JSON.stringify({
FORCE_COLOR: process.env.FORCE_COLOR ?? null,
NO_COLOR: process.env.NO_COLOR ?? null,
enableANSI: Bun.enableANSIColors,
}) + "\\n");`,
"package.json": JSON.stringify({
name: "pkga",
scripts: { probe: `${bunExe()} probe.js` },
}),
},
},
"package.json": JSON.stringify({ name: "ws", workspaces: ["packages/*"] }),
});
}

async function runOnPTY(
dir: string,
extraEnv: Record<string, string | undefined>,
args = ["--filter", "*", "probe"],
) {
const decoder = new TextDecoder();
let output = "";
const done = Promise.withResolvers<void>();
await using proc = Bun.spawn({
cmd: [bunExe(), "run", ...args],
cwd: dir,
env: {
...bunEnv,
NO_COLOR: undefined,
FORCE_COLOR: undefined,
NODE_DISABLE_COLORS: undefined,
CI: undefined,
TERM: "xterm-256color",
COLORTERM: undefined,
TMUX: undefined,
TERM_PROGRAM: undefined,
...extraEnv,
},
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
terminal: {
cols: 200,
rows: 24,
data(_t, chunk: Uint8Array) {
output += decoder.decode(chunk, { stream: true });
if (output.includes("RESULT ") && output.includes("}")) done.resolve();
},
exit() {
done.resolve();
},
},
});
await done.promise;
Comment thread
robobun marked this conversation as resolved.
Resolved
const exitCode = await proc.exited;
output += decoder.decode();
const stripped = Bun.stripANSI(output).replace(/\r/g, "");
const m = stripped.match(/RESULT (\{[^}]*\})/);
if (!m) throw new Error("missing RESULT in terminal output: " + JSON.stringify(output));
const result = JSON.parse(m[1]);
expect(exitCode).toBe(0);
return result;
}

test("sets FORCE_COLOR when parent stdout is a color TTY", async () => {
const dir = colorFixture();
const result = await runOnPTY(dir, {});
expect(result).toEqual({
FORCE_COLOR: "2",
NO_COLOR: null,
enableANSI: true,
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
});
});

test("sets FORCE_COLOR=3 for a truecolor terminal", async () => {
const dir = colorFixture();
const result = await runOnPTY(dir, { COLORTERM: "truecolor" });
expect(result).toEqual({
FORCE_COLOR: "3",
NO_COLOR: null,
enableANSI: true,
});
});

test("respects an explicit NO_COLOR", async () => {
const dir = colorFixture();
const result = await runOnPTY(dir, { NO_COLOR: "1" });
expect(result).toEqual({
FORCE_COLOR: null,
NO_COLOR: "1",
enableANSI: false,
});
});

test("respects an explicit FORCE_COLOR value", async () => {
const dir = colorFixture();
const result = await runOnPTY(dir, { FORCE_COLOR: "0" });
expect(result.FORCE_COLOR).toBe("0");
});

test("respects NODE_DISABLE_COLORS", async () => {
const dir = colorFixture();
const result = await runOnPTY(dir, { NODE_DISABLE_COLORS: "1" });
expect(result.FORCE_COLOR).toBe(null);
});

test("--parallel forwards FORCE_COLOR the same way", async () => {
const dir = colorFixture();
const result = await runOnPTY(dir, {}, ["--filter", "*", "--parallel", "probe"]);
expect(result).toEqual({
FORCE_COLOR: "2",
NO_COLOR: null,
enableANSI: true,
});
});

test("does not set FORCE_COLOR when parent stdout is not a TTY", async () => {
const dir = colorFixture();
await using proc = Bun.spawn({
cmd: [bunExe(), "run", "--filter", "*", "probe"],
cwd: dir,
env: {
...bunEnv,
NO_COLOR: undefined,
FORCE_COLOR: undefined,
NODE_DISABLE_COLORS: undefined,
CI: undefined,
TERM: "xterm-256color",
COLORTERM: undefined,
TMUX: undefined,
TERM_PROGRAM: undefined,
},
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
const m = stdout.match(/RESULT (\{[^}]*\})/);
if (!m) throw new Error("missing RESULT in: " + JSON.stringify({ stdout, stderr }));
const result = JSON.parse(m[1]);
expect({ FORCE_COLOR: result.FORCE_COLOR, NO_COLOR: result.NO_COLOR }).toEqual({
FORCE_COLOR: null,
NO_COLOR: null,
});
expect(exitCode).toBe(0);
});

// A nested `bun --filter` inherits the outer runner's injected FORCE_COLOR
// but its own stdout is a pipe. The redraw renderer must stay off so its
// cursor-up/erase sequences don't corrupt the outer tree.
test("FORCE_COLOR on piped stdout uses the line-prefixed writer, not redraw", async () => {
const dir = colorFixture();
await using proc = Bun.spawn({
cmd: [bunExe(), "run", "--filter", "*", "probe"],
cwd: dir,
env: { ...bunEnv, NO_COLOR: undefined, FORCE_COLOR: "2" },
stdout: "pipe",
stderr: "pipe",
});
const [stdout, , exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stdout).toContain("pkga probe: RESULT ");
expect(stdout).not.toContain("\x1b[?2026h");
expect(stdout).not.toContain("\x1b[1A");
expect(exitCode).toBe(0);
});
});
Loading