Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 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
64 changes: 51 additions & 13 deletions src/runtime/cli/create_command.rs
Original file line number Diff line number Diff line change
@@ -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 _;

Expand Down Expand Up @@ -88,8 +88,14 @@ fn exec_task(task_: &[u8], cwd: &[u8], _path: &[u8], npm_client: Option<NPMClien
debug_assert_eq!(argv.len(), total);

let mut argv: &[&[u8]] = &argv;
if npm_client.is_some() && strings::starts_with(task, b"bun ") {
argv = &argv[2..];
// `bun `-prefixed tasks run with bun itself; posix spawn does no PATH
// lookup, so exec the absolute self path (the printed argv keeps `bun`).
Comment thread
robobun marked this conversation as resolved.
Resolved
let mut exec_argv0: Option<&[u8]> = None;
if let Some(ref client) = npm_client {
if strings::starts_with(task, b"bun ") {
argv = &argv[2..];
exec_argv0 = Some(client.bin);
}
}
Comment thread
robobun marked this conversation as resolved.
Resolved

pretty!("\n<r><d>$<b>");
Expand All @@ -106,8 +112,14 @@ fn exec_task(task_: &[u8], cwd: &[u8], _path: &[u8], npm_client: Option<NPMClien

let _unbuffered = Output::disable_buffering_scope();

let _ = spawn_sync::spawn(&spawn_sync::Options {
argv: argv.iter().map(|s| Box::<[u8]>::from(*s)).collect(),
let spawn_argv: Vec<Box<[u8]>> = 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,
Expand All @@ -126,6 +138,16 @@ fn exec_task(task_: &[u8], cwd: &[u8], _path: &[u8], npm_client: Option<NPMClien
windows: (),
..Default::default()
});

match result {
Ok(Ok(_)) => {}
Ok(Err(err)) => {
bun_core::pretty_errorln!("<r><red>error<r><d>:<r> failed to run task: {}", err);
}
Err(err) => {
bun_core::pretty_errorln!("<r><red>error<r><d>:<r> failed to run task: {}", err);
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

// We don't want to allocate memory each time
Expand Down Expand Up @@ -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::<true>(destination, path_env).unwrap_or(false);
let created = if create_options.verbose {
GitHandler::run::<true>(destination, path_env).unwrap_or(false)
} else {
create_options.skip_git =
GitHandler::run::<false>(destination, path_env).unwrap_or(false);
GitHandler::run::<false>(destination, path_env).unwrap_or(false)
};
if created {
GitHandler::print_timing();
}
create_options.skip_git = !created;
}
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Comment thread
robobun marked this conversation as resolved.
Resolved
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!(" <d>git<r>\n");
Output::flush();
}

fn run<const VERBOSE: bool>(destination: &[u8], path: &[u8]) -> crate::Result<bool> {
let git_start = bun_core::time::nano_timestamp();

Expand Down Expand Up @@ -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!(" <d>git<r>\n");
GIT_ELAPSED_NS.store(
(bun_core::time::nano_timestamp() - git_start) as u64,
Ordering::Release,
);
return Ok(true);
}

Expand Down
117 changes: 117 additions & 0 deletions test/cli/install/bun-create.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -490,3 +490,120 @@ 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
sleep 0.5
Comment thread
robobun marked this conversation as resolved.
Resolved
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 `<exe> 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);
});

// 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);
});
Loading