/
move.ts
95 lines (85 loc) · 1.97 KB
/
move.ts
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import { isSubdir } from "./_util.ts";
const EXISTS_ERROR = new Deno.errors.AlreadyExists("dest already exists.");
interface MoveOptions {
overwrite?: boolean;
}
/**
* Moves a file or directory.
*
* @example
* ```ts
* import { move } from "https://deno.land/std@$STD_VERSION/fs/mod.ts";
*
* move("./foo", "./bar"); // returns a promise
* ```
*/
export async function move(
src: string | URL,
dest: string | URL,
{ overwrite = false }: MoveOptions = {},
) {
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 (overwrite) {
try {
await Deno.remove(dest, { recursive: true });
} catch (error) {
if (!(error instanceof Deno.errors.NotFound)) {
throw error;
}
}
} else {
try {
await Deno.lstat(dest);
return Promise.reject(EXISTS_ERROR);
} catch {
// Do nothing...
}
}
await Deno.rename(src, dest);
}
/**
* Moves a file or directory synchronously.
* @example
* ```ts
* import { moveSync } from "https://deno.land/std@$STD_VERSION/fs/mod.ts";
*
* moveSync("./foo", "./bar"); // void
* ```
*/
export function moveSync(
src: string | URL,
dest: string | URL,
{ overwrite = false }: MoveOptions = {},
) {
const srcStat = Deno.statSync(src);
if (srcStat.isDirectory && isSubdir(src, dest)) {
throw new Error(
`Cannot move '${src}' to a subdirectory of itself, '${dest}'.`,
);
}
if (overwrite) {
try {
Deno.removeSync(dest, { recursive: true });
} catch (error) {
if (!(error instanceof Deno.errors.NotFound)) {
throw error;
}
}
} else {
try {
Deno.lstatSync(dest);
throw EXISTS_ERROR;
} catch (error) {
if (error === EXISTS_ERROR) {
throw error;
}
}
}
Deno.renameSync(src, dest);
}