diff --git a/src/runtime/cli/create_command.rs b/src/runtime/cli/create_command.rs index 41d1f2c42dac..d443a7457bdb 100644 --- a/src/runtime/cli/create_command.rs +++ b/src/runtime/cli/create_command.rs @@ -1,5 +1,5 @@ use bun_collections::VecExt; -use core::sync::atomic::{AtomicU32, Ordering}; +use core::sync::atomic::{AtomicU32, AtomicU64, Ordering}; use std::cell::Cell; use std::io::Write as _; @@ -88,8 +88,14 @@ fn exec_task(task_: &[u8], cwd: &[u8], _path: &[u8], npm_client: Option = None; + if strings::starts_with(task, b"bun ") { + if npm_client.is_some() { + argv = &argv[2..]; + } + exec_argv0 = bun_core::self_exe_path().ok().map(bun_core::ZStr::as_bytes); } pretty!("\n$"); @@ -106,8 +112,14 @@ fn exec_task(task_: &[u8], cwd: &[u8], _path: &[u8], npm_client: Option::from(*s)).collect(), + let spawn_argv: Vec> = argv + .iter() + .enumerate() + .map(|(i, s)| Box::<[u8]>::from(if i == 0 { exec_argv0.unwrap_or(s) } else { *s })) + .collect(); + + let result = spawn_sync::spawn(&spawn_sync::Options { + argv: spawn_argv, envp: None, cwd: Box::from(cwd), stderr: spawn_sync::SyncStdio::Inherit, @@ -126,6 +138,16 @@ fn exec_task(task_: &[u8], cwd: &[u8], _path: &[u8], npm_client: Option {} + Ok(Err(err)) => { + bun_core::pretty_errorln!("error: failed to run task: {}", err); + } + Err(err) => { + bun_core::pretty_errorln!("error: failed to run task: {}", err); + } + } } // We don't want to allocate memory each time @@ -1085,13 +1107,15 @@ impl CreateCommand { if !create_options.skip_install { GitHandler::spawn(destination, path_env, create_options.verbose); } else { - if create_options.verbose { - create_options.skip_git = - GitHandler::run::(destination, path_env).unwrap_or(false); + let created = if create_options.verbose { + GitHandler::run::(destination, path_env).unwrap_or(false) } else { - create_options.skip_git = - GitHandler::run::(destination, path_env).unwrap_or(false); + GitHandler::run::(destination, path_env).unwrap_or(false) + }; + if created { + GitHandler::print_timing(); } + create_options.skip_git = !created; } } @@ -2375,6 +2399,7 @@ impl CreateListExamplesCommand { struct GitHandler; static SUCCESS: AtomicU32 = AtomicU32::new(0); +static GIT_ELAPSED_NS: AtomicU64 = AtomicU64::new(0); // bun_threading has no top-level Thread wrapper yet, // so use std::thread::JoinHandle directly (CLI-only, no JSC interaction). // PORTING.md §Global mutable state: written in `spawn`, taken in `wait`, both @@ -2424,9 +2449,21 @@ impl GitHandler { let outcome = SUCCESS.load(Ordering::Acquire) == 1; // SAFETY: THREAD set in spawn() on this same thread before wait() called let _ = unsafe { (*THREAD.get()).take() }.unwrap().join(); + if outcome { + Self::print_timing(); + } outcome } + // Always called from the main thread so the timing line cannot + // interleave with postinstall output. + fn print_timing() { + bun_core::pretty_error!("\n"); + Output::print_start_end(0, GIT_ELAPSED_NS.load(Ordering::Acquire) as i128); + bun_core::pretty_error!(" git\n"); + Output::flush(); + } + fn run(destination: &[u8], path: &[u8]) -> crate::Result { let git_start = bun_core::time::nano_timestamp(); @@ -2497,9 +2534,10 @@ impl GitHandler { })?; } - bun_core::pretty_error!("\n"); - Output::print_start_end(git_start, bun_core::time::nano_timestamp()); - bun_core::pretty_error!(" git\n"); + GIT_ELAPSED_NS.store( + (bun_core::time::nano_timestamp() - git_start) as u64, + Ordering::Release, + ); return Ok(true); } diff --git a/test/cli/install/bun-create.test.ts b/test/cli/install/bun-create.test.ts index 8132f66e0245..cef16b97c23b 100644 --- a/test/cli/install/bun-create.test.ts +++ b/test/cli/install/bun-create.test.ts @@ -490,3 +490,150 @@ it("should not crash with --no-install and bun-create.postinstall starting with expect(err).not.toContain("error:"); expect(exitCode).toBe(0); }); + +// The `[Xs] git` timing line used to be printed directly from the git worker +// thread, racing with postinstall output on the main thread (issue #36953). +// The stub git blocks its `commit` until postinstall starts, then postinstall +// waits for the stub to finish before printing its last line, so without the +// fix the timing line reliably lands between PI_START and PI_END. +// POSIX-only: the stub `git` is a shell script. +it.skipIf(!isPosix)( + "should not interleave the git timing line with postinstall output", + async () => { + using dir = tempDir("create-git-timing", { + "bin/git": `#!/bin/sh +case "$*" in + *commit*) + i=0 + while [ ! -f postinstall_started ] && [ $i -lt 600 ]; do sleep 0.05; i=$((i+1)); done + touch git_finished + ;; +esac +exit 0 +`, + "bun-create/tmpl/index.js": "// hi\n", + "bun-create/tmpl/package.json": JSON.stringify({ + name: "tmpl", + version: "1.0.0", + "bun-create": { postinstall: "postinstall-step" }, + scripts: { "postinstall-step": "sh scripts/postinstall.sh" }, + dependencies: { localdep: "file:./localdep" }, + }), + "bun-create/tmpl/localdep/package.json": JSON.stringify({ name: "localdep", version: "1.0.0" }), + "bun-create/tmpl/scripts/postinstall.sh": `#!/bin/sh +echo PI_START >&2 +touch postinstall_started +i=0 +while [ ! -f git_finished ] && [ $i -lt 600 ]; do sleep 0.05; i=$((i+1)); done +# the worker's stderr write happens after the stub exits and is not observable +# from here; give the unfixed binary time to print before the last line +sleep 0.5 +echo PI_END >&2 +`, + }); + chmodSync(join(String(dir), "bin", "git"), 0o755); + + await using proc = spawn({ + cmd: [bunExe(), "create", "tmpl", join(String(dir), "dest")], + cwd: String(dir), + env: { + ...env, + PATH: join(String(dir), "bin") + ":" + process.env.PATH, + BUN_CREATE_DIR: join(String(dir), "bun-create"), + }, + stdout: "pipe", + stderr: "pipe", + }); + + const [err, _out, exitCode] = await Promise.all([proc.stderr.text(), proc.stdout.text(), proc.exited]); + expect(err).toContain("PI_START"); + const endIdx = err.indexOf("PI_END"); + expect(endIdx).toBeGreaterThan(-1); + const gitIdx = err.indexOf("] git"); + expect(gitIdx).toBeGreaterThan(endIdx); + expect(exitCode).toBe(0); + }, + 45_000, +); + +// On POSIX, a `bun `-prefixed bun-create postinstall task used to silently not +// run: the ` run` prefix was stripped, leaving the bare string `bun` as +// argv[0], and posix spawn does no PATH lookup (issue #36953). +it("should run a bun-create postinstall task that starts with 'bun '", async () => { + using dir = tempDir("create-bun-postinstall", { + "bun-create/tmpl/index.js": "// hi\n", + "bun-create/tmpl/package.json": JSON.stringify({ + name: "tmpl", + version: "1.0.0", + "bun-create": { postinstall: "bun scripts/marker.ts" }, + dependencies: { localdep: "file:./localdep" }, + }), + "bun-create/tmpl/localdep/package.json": JSON.stringify({ name: "localdep", version: "1.0.0" }), + "bun-create/tmpl/scripts/marker.ts": `await Bun.write("marker.txt", "ran");`, + }); + + await using proc = spawn({ + cmd: [bunExe(), "create", "tmpl", join(String(dir), "dest"), "--no-git"], + cwd: String(dir), + env: { ...env, BUN_CREATE_DIR: join(String(dir), "bun-create") }, + stdout: "pipe", + stderr: "pipe", + }); + + const [out, err, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(out).toContain("$ bun scripts/marker.ts"); + expect(err).not.toContain("error:"); + expect(await Bun.file(join(String(dir), "dest", "marker.txt")).text()).toBe("ran"); + expect(exitCode).toBe(0); +}); + +// Same as above, but the template has no dependencies: postinstall then runs +// without the npm client, and the bare `bun` argv[0] hit the same ENOENT. +it("should run a bun-prefixed postinstall task for a template without dependencies", async () => { + using dir = tempDir("create-bun-postinstall-nodeps", { + "bun-create/tmpl/index.js": "// hi\n", + "bun-create/tmpl/package.json": JSON.stringify({ + name: "tmpl", + version: "1.0.0", + "bun-create": { postinstall: "bun scripts/marker.ts" }, + }), + "bun-create/tmpl/scripts/marker.ts": `await Bun.write("marker.txt", "ran");`, + }); + + await using proc = spawn({ + cmd: [bunExe(), "create", "tmpl", join(String(dir), "dest"), "--no-git"], + cwd: String(dir), + env: { ...env, BUN_CREATE_DIR: join(String(dir), "bun-create") }, + stdout: "pipe", + stderr: "pipe", + }); + + const [out, err, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(out).toContain("$ bun scripts/marker.ts"); + expect(err).not.toContain("error:"); + expect(await Bun.file(join(String(dir), "dest", "marker.txt")).text()).toBe("ran"); + expect(exitCode).toBe(0); +}); + +// The synchronous git path (no dependencies) set skip_git to the git +// *success* instead of its negation, so the final message was suppressed on +// success and printed when git was missing. +it("should print the git message for a template without dependencies", async () => { + using dir = tempDir("create-no-deps-git", { + "bun-create/tmpl/index.js": "// hi\n", + "bun-create/tmpl/package.json": JSON.stringify({ name: "tmpl", version: "1.0.0" }), + }); + + await using proc = spawn({ + cmd: [bunExe(), "create", "tmpl", join(String(dir), "dest")], + cwd: String(dir), + env: { ...env, BUN_CREATE_DIR: join(String(dir), "bun-create") }, + stdout: "pipe", + stderr: "pipe", + }); + + const [out, err, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(err).not.toContain("error:"); + expect(out).toContain("A local git repository was created for you."); + expect(exitCode).toBe(0); +});