| 1 |
"use strict"; |
| 2 |
|
| 3 |
const isCallable = require("es5-ext/object/is-callable") |
| 4 |
, isValue = require("es5-ext/object/is-value") |
| 5 |
, deferred = require("deferred") |
| 6 |
, path = require("path") |
| 7 |
, original = require("fs").rename |
| 8 |
, mkdir = require("./mkdir") |
| 9 |
, stat = require("./stat") |
| 10 |
, copy = require("./copy") |
| 11 |
, copyDir = require("./copy-dir") |
| 12 |
, rmdir = require("./rmdir") |
| 13 |
, unlink = require("./unlink") |
| 14 |
, { dirname } = path |
| 15 |
, { resolve } = path; |
| 16 |
|
| 17 |
const crossDeviceRename = function (oldPath, newPath) { |
| 18 |
return stat.then(stats => { |
| 19 |
if (stats.isDirectory()) { |
| 20 |
return copyDir(oldPath, newPath).then(() => |
| 21 |
rmdir(oldPath, { recursive: true, force: true }) |
| 22 |
); |
| 23 |
} |
| 24 |
return copy(oldPath, newPath).then(() => unlink(oldPath)); |
| 25 |
}); |
| 26 |
}; |
| 27 |
|
| 28 |
const rename = function (oldPath, newPath) { |
| 29 |
const def = deferred(); |
| 30 |
original(oldPath, newPath, err => { |
| 31 |
if (err) { |
| 32 |
if (err.code === "EXDEV") { |
| 33 |
def.resolve(crossDeviceRename(oldPath, newPath)); |
| 34 |
return; |
| 35 |
} |
| 36 |
def.reject(err); |
| 37 |
} else { |
| 38 |
def.resolve(); |
| 39 |
} |
| 40 |
}); |
| 41 |
return def.promise; |
| 42 |
}; |
| 43 |
rename.returnsPromise = true; |
| 44 |
|
| 45 |
module.exports = exports = function (oldPath, newPath, options = {}, cb = null) { |
| 46 |
if (!isValue(cb) && isCallable(options)) { |
| 47 |
cb = options; |
| 48 |
options = {}; |
| 49 |
} |
| 50 |
oldPath = resolve(String(oldPath)); |
| 51 |
newPath = resolve(String(newPath)); |
| 52 |
if (options.intermediate) { |
| 53 |
return mkdir(dirname(newPath), { intermediate: true })(() => rename(oldPath, newPath)).cb( |
| 54 |
cb |
| 55 |
); |
| 56 |
} |
| 57 |
|
| 58 |
return rename(oldPath, resolve(String(newPath))).cb(cb); |
| 59 |
}; |
| 60 |
exports.returnsPromise = true; |
| 61 |
exports.rename = rename; |