Skip to content

Commit 9b3f1aa

Browse files
watildeaduh95
authored andcommitted
fs: throw on existing dir in cpSync with errorOnExist
cpSync() did not honor errorOnExist when the destination directory already existed, while the asynchronous cp() does (fixed in the commit that added test-fs-cp-async-dir-exists-error-on-exist). Mirror that guard in the synchronous onDir() so both APIs behave identically. Signed-off-by: Daijiro Wachi <daijiro.wachi@gmail.com> PR-URL: #64124 Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
1 parent 2a8b5d9 commit 9b3f1aa

2 files changed

Lines changed: 41 additions & 0 deletions

File tree

lib/internal/fs/cp/cp-sync.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,15 @@ function setDestTimestamps(src, dest) {
134134
// TODO(@anonrig): Move this function to C++.
135135
function onDir(srcStat, destStat, src, dest, opts) {
136136
if (!destStat) return copyDir(src, dest, opts, true, srcStat.mode);
137+
if (opts.errorOnExist && !opts.force) {
138+
throw new ERR_FS_CP_EEXIST({
139+
message: `${dest} already exists`,
140+
path: dest,
141+
syscall: 'cp',
142+
errno: EEXIST,
143+
code: 'EEXIST',
144+
});
145+
}
137146
return copyDir(src, dest, opts);
138147
}
139148

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// This tests that cpSync() throws if errorOnExist is true, force is false,
2+
// and the destination directory already exists (even if contents don't
3+
// conflict), matching the asynchronous cp() behavior.
4+
5+
import '../common/index.mjs';
6+
import { nextdir } from '../common/fs.js';
7+
import assert from 'node:assert';
8+
import { cpSync, mkdirSync, writeFileSync } from 'node:fs';
9+
import tmpdir from '../common/tmpdir.js';
10+
11+
tmpdir.refresh();
12+
13+
const src = nextdir();
14+
const dest = nextdir();
15+
16+
// Create source directory with a file
17+
mkdirSync(src);
18+
writeFileSync(`${src}/file.txt`, 'test');
19+
20+
// Create destination directory with a different (non-conflicting) file
21+
mkdirSync(dest);
22+
writeFileSync(`${dest}/other.txt`, 'existing');
23+
24+
// Should throw because dest directory already exists
25+
assert.throws(
26+
() => cpSync(src, dest, {
27+
recursive: true,
28+
errorOnExist: true,
29+
force: false,
30+
}),
31+
{ code: 'ERR_FS_CP_EEXIST' },
32+
);

0 commit comments

Comments
 (0)