1 | "use strict";
|
2 |
|
3 | const pathUtil = require("path");
|
4 | const fs = require("./utils/fs");
|
5 | const validate = require("./utils/validate");
|
6 | const dir = require("./dir");
|
7 | const exists = require("./exists");
|
8 |
|
9 | const validateInput = (methodName, from, to) => {
|
10 | const methodSignature = `${methodName}(from, to)`;
|
11 | validate.argument(methodSignature, "from", from, ["string"]);
|
12 | validate.argument(methodSignature, "to", to, ["string"]);
|
13 | };
|
14 |
|
15 | const generateSourceDoesntExistError = path => {
|
16 | const err = new Error(`Path to move doesn't exist ${path}`);
|
17 | err.code = "ENOENT";
|
18 | return err;
|
19 | };
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 | const moveSync = (from, to) => {
|
26 | try {
|
27 | fs.renameSync(from, to);
|
28 | } catch (err) {
|
29 | if (err.code !== "ENOENT") {
|
30 |
|
31 | throw err;
|
32 | } else {
|
33 |
|
34 |
|
35 | if (!exists.sync(from)) {
|
36 | throw generateSourceDoesntExistError(from);
|
37 | }
|
38 | if (!exists.sync(to)) {
|
39 |
|
40 | dir.createSync(pathUtil.dirname(to));
|
41 |
|
42 | fs.renameSync(from, to);
|
43 | }
|
44 | }
|
45 | }
|
46 | };
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 | const ensureDestinationPathExistsAsync = to => {
|
53 | return new Promise((resolve, reject) => {
|
54 | const destDir = pathUtil.dirname(to);
|
55 | exists
|
56 | .async(destDir)
|
57 | .then(dstExists => {
|
58 | if (!dstExists) {
|
59 | dir.createAsync(destDir).then(resolve, reject);
|
60 | } else {
|
61 |
|
62 | reject();
|
63 | }
|
64 | })
|
65 | .catch(reject);
|
66 | });
|
67 | };
|
68 |
|
69 | const moveAsync = (from, to) => {
|
70 | return new Promise((resolve, reject) => {
|
71 | fs.rename(from, to)
|
72 | .then(resolve)
|
73 | .catch(err => {
|
74 | if (err.code !== "ENOENT") {
|
75 |
|
76 | reject(err);
|
77 | } else {
|
78 |
|
79 |
|
80 | exists
|
81 | .async(from)
|
82 | .then(srcExists => {
|
83 | if (!srcExists) {
|
84 | reject(generateSourceDoesntExistError(from));
|
85 | } else {
|
86 | ensureDestinationPathExistsAsync(to)
|
87 | .then(() => {
|
88 |
|
89 | return fs.rename(from, to);
|
90 | })
|
91 | .then(resolve, reject);
|
92 | }
|
93 | })
|
94 | .catch(reject);
|
95 | }
|
96 | });
|
97 | });
|
98 | };
|
99 |
|
100 |
|
101 |
|
102 |
|
103 |
|
104 | exports.validateInput = validateInput;
|
105 | exports.sync = moveSync;
|
106 | exports.async = moveAsync;
|