Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 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
52 changes: 22 additions & 30 deletions src/runtime/node/node_fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1479,19 +1479,7 @@ mod _async_tasks {
&parent.args,
);

'brk: {
match result {
Err(ref err) => {
if err.errno == E::EEXIST as _ && !args.flags.error_on_exist {
break 'brk;
}
parent.finish_concurrently(result);
}
Ok(_) => {
parent.on_copy(self.src(), self.dest());
}
}
}
parent.record_copy_result(self.src(), self.dest(), result);

// `self: Box<Self>` drops here (frees the owned `path_buf`).
drop(self);
Expand Down Expand Up @@ -1532,6 +1520,25 @@ mod _async_tasks {
.cp_on_copy(src.as_ref(), dest.as_ref());
}

/// Accounts for one file's `copy_single_file_sync` result, whether the
/// file is the whole `cp` or one entry of the directory walk. Only a
/// copy that happened is reported through `on_copy`; an `EEXIST` the
/// flags tolerate is neither a copy nor an error. Success needs no
/// record: `on_subtask_done` resolves with `Ok` unless an error was
/// recorded.
Comment thread
robobun marked this conversation as resolved.
Resolved
fn record_copy_result(
&self,
src: &OSPathSliceZ,
dest: &OSPathSliceZ,
result: Maybe<ret::CopyFile>,
) {
match result {
Ok(()) => self.on_copy(src, dest),
Err(e) if e.get_errno() == E::EEXIST && !self.args.flags.error_on_exist => {}
Err(e) => self.finish_concurrently(Err(e)),
}
}

/// `fs.cp` / `fs.promises.cp` (JS thread): a promise, an async-stack
/// tracker, and this VM's loop.
pub(crate) fn create(
Expand Down Expand Up @@ -1852,14 +1859,7 @@ mod _async_tasks {
Some(attributes),
&this.args,
);
if let Err(e) = &r {
if e.errno == E::EEXIST as _ && !args.flags.error_on_exist {
this.finish_concurrently(Ok(()));
return;
}
}
this.on_copy(src, dest);
this.finish_concurrently(r);
this.record_copy_result(src, dest, r);
return;
}
}
Expand Down Expand Up @@ -1891,15 +1891,7 @@ mod _async_tasks {
Some(&stat_),
&this.args,
);
if let Err(e) = &r {
if e.errno == E::EEXIST as _ && !args.flags.error_on_exist {
this.on_copy(src, dest);
this.finish_concurrently(Ok(()));
return;
}
}
this.on_copy(src, dest);
this.finish_concurrently(r);
this.record_copy_result(src, dest, r);
return;
}
}
Expand Down
100 changes: 98 additions & 2 deletions test/js/bun/shell/commands/cp.test.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import { $ } from "bun";
import { shellInternals } from "bun:internal-for-testing";
import { describe, expect } from "bun:test";
import { tempDirWithFiles } from "harness";
import { describe, expect, test } from "bun:test";
import { bunEnv, tempDir, tempDirWithFiles } from "harness";
import { chmodSync, lstatSync, readFileSync, symlinkSync } from "node:fs";
import { join } from "node:path";
import { bunExe, createTestBuilder } from "../test_builder";
import { sortedShellOutput } from "../util";
const { builtinDisabled } = shellInternals;

const TestBuilder = createTestBuilder(import.meta.path);

const p = process.platform === "win32" ? (s: string) => s.replaceAll("/", "\\") : (s: string) => s;
const isRoot = process.getuid?.() === 0;

$.nothrow();

Expand Down Expand Up @@ -173,6 +176,99 @@ describe.if(!builtinDisabled("cp"))("bunshell cp", async () => {
});
});

// The builtin is only the default on Windows; on POSIX it is switched on by an
// env var that is read once per process, so each cp runs in a child bun.
describe.concurrent("bunshell cp -v only reports copies that happened", () => {
const builtinEnv = { ...bunEnv, BUN_ENABLE_EXPERIMENTAL_SHELL_BUILTINS: "1" };

/** Runs `command` through the shell builtin with `cwd` as the shell's cwd; returns what cp exited with and printed. */
async function cp(cwd: string, command: string): Promise<{ exitCode: number; stdout: string; stderr: string }> {
await using proc = Bun.spawn({
cmd: [
bunExe(),
"-e",
"const r = await Bun.$`${{ raw: process.argv[1] }}`.cwd(process.argv[2]).nothrow().quiet();" +
"console.log(JSON.stringify({ exitCode: r.exitCode, stdout: r.stdout.toString(), stderr: r.stderr.toString() }));",
command,
cwd,
],
cwd,
env: builtinEnv,
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stderr).toBe("");
expect(exitCode).toBe(0);
return JSON.parse(stdout);
}

const failed = { exitCode: 1, stdout: "", stderr: expect.stringMatching(/^cp: /) };

test("file -> dir whose entry of that name is a directory", async () => {
using dir = tempDir("shell-cp-v-failed", { "b.txt": "b\n", "d": { "b.txt": {} } });

expect(await cp(String(dir), "cp -v b.txt d")).toEqual(failed);
});

test("file+ -> dir reports only the file that was copied", async () => {
using dir = tempDir("shell-cp-v-mixed", { "a.txt": "a\n", "b.txt": "b\n", "d": { "b.txt": {} } });
const cwd = String(dir);

expect(await cp(cwd, "cp -v a.txt b.txt d")).toEqual({
...failed,
stdout: `${join(cwd, "a.txt")} -> ${join(cwd, "d", "a.txt")}\n`,
});
expect(readFileSync(join(cwd, "d", "a.txt"), "utf8")).toBe("a\n");
});

test.skipIf(isRoot)("file -> read-only file", async () => {
using dir = tempDir("shell-cp-v-readonly", { "a.txt": "a\n", "ro.txt": "keep\n" });
const ro = join(String(dir), "ro.txt");
chmodSync(ro, 0o444);
try {
expect(await cp(String(dir), "cp -v a.txt ro.txt")).toEqual(failed);
expect(readFileSync(ro, "utf8")).toBe("keep\n");
} finally {
chmodSync(ro, 0o644);
}
});

test("-R: lists the directories and files that were copied, not the file that failed", async () => {
using dir = tempDir("shell-cp-v-recursive", {
"src": { "ok.txt": "ok\n", "sub": { "bad.txt": "bad\n" } },
"dest": { "src": { "sub": { "bad.txt": {} } } },
});
const cwd = String(dir);
const src = (...parts: string[]) => join(cwd, "src", ...parts);
const dest = (...parts: string[]) => join(cwd, "dest", "src", ...parts);

const result = await cp(cwd, "cp -R -v src dest");
// Files inside the tree are copied concurrently, so their lines come out in any order.
expect({ ...result, stdout: sortedShellOutput(result.stdout) }).toEqual({
...failed,
stdout: sortedShellOutput([
`${src()} -> ${dest()}`,
`${src("ok.txt")} -> ${dest("ok.txt")}`,
`${src("sub")} -> ${dest("sub")}`,
]),
});
expect(readFileSync(dest("ok.txt"), "utf8")).toBe("ok\n");
});

test("symlink -> existing file is listed only if the destination is now the link", async () => {
using dir = tempDir("shell-cp-v-symlink", { "target.txt": "target\n", "existing.txt": "keep\n" });
const cwd = String(dir);
symlinkSync("target.txt", join(cwd, "lnk"));

const { stdout } = await cp(cwd, "cp -v lnk existing.txt");
// A link source is recreated with symlink(2), which on most platforms cannot
// replace an existing destination (cp tolerates that EEXIST and leaves the
// destination alone). Whatever happened to the destination, the line has to agree with it.
const replaced = lstatSync(join(cwd, "existing.txt")).isSymbolicLink();
expect(stdout).toBe(replaced ? `${join(cwd, "lnk")} -> ${join(cwd, "existing.txt")}\n` : "");
});
});

function expectSortedOutput(expected: string) {
return (stdout: string, tempdir: string) =>
expect(sortedShellOutput(stdout).join("\n")).toEqual(
Expand Down