diff options
| author | Axetroy <troy450409405@gmail.com> | 2019-03-12 17:11:30 +0800 |
|---|---|---|
| committer | Ryan Dahl <ry@tinyclouds.org> | 2019-03-12 05:11:30 -0400 |
| commit | 511dbdde73bec2d7096e77e5a20fc697b007df3f (patch) | |
| tree | aa8dd3aa6e8aefbda737cbbf8faaa3e9ac899cf4 /fs/move.ts | |
| parent | 1bfc46bbd2d3cd362488034e4a2b8c4d5a4f1f16 (diff) | |
feat: add move/moveSync for fs modules (denoland/deno_std#266)
Original: https://github.com/denoland/deno_std/commit/a1fcfb2744a7a2c660bf03b8da03ca2c4d7753a8
Diffstat (limited to 'fs/move.ts')
| -rw-r--r-- | fs/move.ts | 88 |
1 files changed, 88 insertions, 0 deletions
diff --git a/fs/move.ts b/fs/move.ts new file mode 100644 index 000000000..f64509788 --- /dev/null +++ b/fs/move.ts @@ -0,0 +1,88 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. +import * as path from "./path/mod.ts"; +import { exists, existsSync } from "./exists.ts"; + +interface MoveOptions { + overwrite?: boolean; +} + +function isSrcSubdir(src: string, dest: string): boolean { + const srcArray = src.split(path.sep); + const destArray = dest.split(path.sep); + + return srcArray.reduce((acc, current, i) => { + return acc && destArray[i] === current; + }, true); +} + +/** + * Moves a file or directory + * @export + * @param {string} src + * @param {string} dest + * @param {MoveOptions} [options] + * @returns {Promise<void>} + */ +export async function move( + src: string, + dest: string, + options?: MoveOptions +): Promise<void> { + src = path.resolve(src); + dest = path.resolve(dest); + + const srcStat = await Deno.stat(src); + + if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { + 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; +} + +/** + * Moves a file or directory + * @export + * @param {string} src + * @param {string} dest + * @param {MoveOptions} [options] + * @returns {void} + */ +export function moveSync( + src: string, + dest: string, + options?: MoveOptions +): void { + src = path.resolve(src); + dest = path.resolve(dest); + + const srcStat = Deno.statSync(src); + + if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { + 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); + } +} |
