| 1 |
"use strict"; |
| 2 |
|
| 3 |
const isCallable = require("es5-ext/object/is-callable") |
| 4 |
, isValue = require("es5-ext/object/is-value") |
| 5 |
, isString = require("es5-ext/string/is-string") |
| 6 |
, deferred = require("deferred") |
| 7 |
, path = require("path") |
| 8 |
, original = require("fs").symlink |
| 9 |
, mkdir = require("./mkdir") |
| 10 |
, isSymlink = require("./is-symlink") |
| 11 |
, unlink = require("./unlink"); |
| 12 |
|
| 13 |
const symlink = function (src, dest, options) { |
| 14 |
const def = deferred(); |
| 15 |
original(src, dest, options.type, err => { |
| 16 |
if (err) { |
| 17 |
def.reject(err); |
| 18 |
return; |
| 19 |
} |
| 20 |
def.resolve(true); |
| 21 |
}); |
| 22 |
return def.promise.catch(error => { |
| 23 |
if (!options.loose && !options.force) throw error; |
| 24 |
if (error.code === "EEXIST") { |
| 25 |
return isSymlink(dest, { linkPath: src })(result => { |
| 26 |
if (result) return Promise.resolve(false); |
| 27 |
if (!options.force) throw error; |
| 28 |
return unlink(dest).then(() => symlink(src, dest, options), () => { throw error; }); |
| 29 |
}); |
| 30 |
} |
| 31 |
throw error; |
| 32 |
}); |
| 33 |
}; |
| 34 |
symlink.returnsPromise = true; |
| 35 |
|
| 36 |
module.exports = exports = function (src, dest, options = {}, cb = null) { |
| 37 |
src = String(src); |
| 38 |
dest = path.resolve(String(dest)); |
| 39 |
if (!isValue(cb) && isCallable(options)) { |
| 40 |
cb = options; |
| 41 |
options = {}; |
| 42 |
} else { |
| 43 |
options = isString(options) ? { type: options } : Object(options); |
| 44 |
} |
| 45 |
|
| 46 |
if (options.intermediate) { |
| 47 |
return mkdir(path.dirname(dest), { intermediate: true })(() => |
| 48 |
symlink(src, dest, options) |
| 49 |
).cb(cb); |
| 50 |
} |
| 51 |
|
| 52 |
return symlink(src, dest, options).cb(cb); |
| 53 |
}; |
| 54 |
exports.returnsPromise = true; |
| 55 |
exports.symlink = symlink; |