1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-01-11 00:21:05 -05:00

fix(std/fs): move dest if not exists and overwrite (#4910)

This commit is contained in:
张超杰 2020-04-27 04:27:24 +08:00 committed by GitHub
parent 4f9bb11444
commit 49cad79fb1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 46 additions and 2 deletions

View file

@ -21,7 +21,9 @@ export async function move(
}
if (overwrite) {
await Deno.remove(dest, { recursive: true });
if (await exists(dest)) {
await Deno.remove(dest, { recursive: true });
}
await Deno.rename(src, dest);
} else {
if (await exists(dest)) {
@ -48,7 +50,9 @@ export function moveSync(
}
if (overwrite) {
Deno.removeSync(dest, { recursive: true });
if (existsSync(dest)) {
Deno.removeSync(dest, { recursive: true });
}
Deno.renameSync(src, dest);
} else {
if (existsSync(dest)) {

View file

@ -42,6 +42,27 @@ Deno.test(async function moveDirectoryIfDestNotExists(): Promise<void> {
await Deno.remove(destDir);
});
Deno.test(async function moveDirectoryIfDestNotExistsAndOverwrite(): Promise<
void
> {
const srcDir = path.join(testdataDir, "move_test_src_2");
const destDir = path.join(testdataDir, "move_test_dest_2");
await Deno.mkdir(srcDir, { recursive: true });
// if dest directory not exist
await assertThrowsAsync(
async (): Promise<void> => {
await move(srcDir, destDir, { overwrite: true });
throw new Error("should not throw error");
},
Error,
"should not throw error"
);
await Deno.remove(destDir);
});
Deno.test(async function moveFileIfSrcNotExists(): Promise<void> {
const srcFile = path.join(testdataDir, "move_test_src_3", "test.txt");
const destFile = path.join(testdataDir, "move_test_dest_3", "test.txt");
@ -208,6 +229,25 @@ Deno.test(function moveSyncDirectoryIfDestNotExists(): void {
Deno.removeSync(destDir);
});
Deno.test(function moveSyncDirectoryIfDestNotExistsAndOverwrite(): void {
const srcDir = path.join(testdataDir, "move_sync_test_src_2");
const destDir = path.join(testdataDir, "move_sync_test_dest_2");
Deno.mkdirSync(srcDir, { recursive: true });
// if dest directory not exist width overwrite
assertThrows(
(): void => {
moveSync(srcDir, destDir, { overwrite: true });
throw new Error("should not throw error");
},
Error,
"should not throw error"
);
Deno.removeSync(destDir);
});
Deno.test(function moveSyncFileIfSrcNotExists(): void {
const srcFile = path.join(testdataDir, "move_sync_test_src_3", "test.txt");
const destFile = path.join(testdataDir, "move_sync_test_dest_3", "test.txt");