2020-01-02 15:13:47 -05:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
2019-03-12 05:11:30 -04:00
|
|
|
import { exists, existsSync } from "./exists.ts";
|
2020-05-09 08:34:47 -04:00
|
|
|
import { isSubdir } from "./_util.ts";
|
2019-03-12 05:11:30 -04:00
|
|
|
|
|
|
|
interface MoveOptions {
|
|
|
|
overwrite?: boolean;
|
|
|
|
}
|
|
|
|
|
2019-03-14 10:24:54 -04:00
|
|
|
/** Moves a file or directory */
|
2019-03-12 05:11:30 -04:00
|
|
|
export async function move(
|
|
|
|
src: string,
|
|
|
|
dest: string,
|
2020-07-14 15:24:17 -04:00
|
|
|
{ overwrite = false }: MoveOptions = {},
|
2019-03-12 05:11:30 -04:00
|
|
|
): Promise<void> {
|
|
|
|
const srcStat = await Deno.stat(src);
|
|
|
|
|
2020-04-16 01:40:30 -04:00
|
|
|
if (srcStat.isDirectory && isSubdir(src, dest)) {
|
2019-03-12 05:11:30 -04:00
|
|
|
throw new Error(
|
2020-07-14 15:24:17 -04:00
|
|
|
`Cannot move '${src}' to a subdirectory of itself, '${dest}'.`,
|
2019-03-12 05:11:30 -04:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2020-03-10 12:08:58 -04:00
|
|
|
if (overwrite) {
|
2020-04-26 16:27:24 -04:00
|
|
|
if (await exists(dest)) {
|
|
|
|
await Deno.remove(dest, { recursive: true });
|
|
|
|
}
|
2019-03-12 05:11:30 -04:00
|
|
|
await Deno.rename(src, dest);
|
|
|
|
} else {
|
|
|
|
if (await exists(dest)) {
|
|
|
|
throw new Error("dest already exists.");
|
|
|
|
}
|
|
|
|
await Deno.rename(src, dest);
|
|
|
|
}
|
|
|
|
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2020-05-17 11:36:01 -04:00
|
|
|
/** Moves a file or directory synchronously */
|
2019-03-12 05:11:30 -04:00
|
|
|
export function moveSync(
|
|
|
|
src: string,
|
|
|
|
dest: string,
|
2020-07-14 15:24:17 -04:00
|
|
|
{ overwrite = false }: MoveOptions = {},
|
2019-03-12 05:11:30 -04:00
|
|
|
): void {
|
|
|
|
const srcStat = Deno.statSync(src);
|
|
|
|
|
2020-04-16 01:40:30 -04:00
|
|
|
if (srcStat.isDirectory && isSubdir(src, dest)) {
|
2019-03-12 05:11:30 -04:00
|
|
|
throw new Error(
|
2020-07-14 15:24:17 -04:00
|
|
|
`Cannot move '${src}' to a subdirectory of itself, '${dest}'.`,
|
2019-03-12 05:11:30 -04:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2020-03-10 12:08:58 -04:00
|
|
|
if (overwrite) {
|
2020-04-26 16:27:24 -04:00
|
|
|
if (existsSync(dest)) {
|
|
|
|
Deno.removeSync(dest, { recursive: true });
|
|
|
|
}
|
2019-03-12 05:11:30 -04:00
|
|
|
Deno.renameSync(src, dest);
|
|
|
|
} else {
|
|
|
|
if (existsSync(dest)) {
|
|
|
|
throw new Error("dest already exists.");
|
|
|
|
}
|
|
|
|
Deno.renameSync(src, dest);
|
|
|
|
}
|
|
|
|
}
|