summaryrefslogtreecommitdiff
path: root/std/fs/move.ts
blob: e87d59c6e642764ed2695615746118959ab1a275 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { exists, existsSync } from "./exists.ts";
import { isSubdir } from "./utils.ts";

interface MoveOptions {
  overwrite?: boolean;
}

/** Moves a file or directory */
export async function move(
  src: string,
  dest: string,
  options?: MoveOptions
): Promise<void> {
  const srcStat = await Deno.stat(src);

  if (srcStat.isDirectory() && isSubdir(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 function moveSync(
  src: string,
  dest: string,
  options?: MoveOptions
): void {
  const srcStat = Deno.statSync(src);

  if (srcStat.isDirectory() && isSubdir(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);
  }
}