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";
|
2019-03-17 12:34:55 -04:00
|
|
|
import { isSubdir } from "./utils.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,
|
|
|
|
options?: MoveOptions
|
|
|
|
): Promise<void> {
|
|
|
|
const srcStat = await Deno.stat(src);
|
|
|
|
|
2019-03-17 12:34:55 -04:00
|
|
|
if (srcStat.isDirectory() && isSubdir(src, dest)) {
|
2019-03-12 05:11:30 -04:00
|
|
|
throw new Error(
|
|
|
|
`Cannot move '${src}' to a subdirectory of itself, '${dest}'.`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (options && options.overwrite) {
|
|
|
|
await Deno.remove(dest, { recursive: true });
|
|
|
|
await Deno.rename(src, dest);
|
|
|
|
} else {
|
|
|
|
if (await exists(dest)) {
|
|
|
|
throw new Error("dest already exists.");
|
|
|
|
}
|
|
|
|
await Deno.rename(src, dest);
|
|
|
|
}
|
|
|
|
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-03-14 10:24:54 -04:00
|
|
|
/** Moves a file or directory */
|
2019-03-12 05:11:30 -04:00
|
|
|
export function moveSync(
|
|
|
|
src: string,
|
|
|
|
dest: string,
|
|
|
|
options?: MoveOptions
|
|
|
|
): void {
|
|
|
|
const srcStat = Deno.statSync(src);
|
|
|
|
|
2019-03-17 12:34:55 -04:00
|
|
|
if (srcStat.isDirectory() && isSubdir(src, dest)) {
|
2019-03-12 05:11:30 -04:00
|
|
|
throw new Error(
|
|
|
|
`Cannot move '${src}' to a subdirectory of itself, '${dest}'.`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (options && options.overwrite) {
|
|
|
|
Deno.removeSync(dest, { recursive: true });
|
|
|
|
Deno.renameSync(src, dest);
|
|
|
|
} else {
|
|
|
|
if (existsSync(dest)) {
|
|
|
|
throw new Error("dest already exists.");
|
|
|
|
}
|
|
|
|
Deno.renameSync(src, dest);
|
|
|
|
}
|
|
|
|
}
|