Debian Codegraph @

fs2/copy-dir.js

raw
1 "use strict";
2
3 const isCallable = require("es5-ext/object/is-callable")
4 , isValue = require("es5-ext/object/is-value")
5 , startsWith = require("es5-ext/string/#/starts-with")
6 , deferred = require("deferred")
7 , path = require("path")
8 , lstat = require("./lstat")
9 , mkdir = require("./mkdir")
10 , readdir = require("./readdir")
11 , readlink = require("./readlink")
12 , symlink = require("./symlink")
13 , copyFile = require("./copy").copy;
14
15 const copyDir = function (source, dest, options, sourceTop, destTop) {
16 return readdir(source, {
17 type: { directory: true, file: true, symbolicLink: true },
18 depth: Infinity
19 })(
20 files =>
21 deferred.map(files, relativePath => {
22 const filename = path.resolve(source, relativePath);
23 return lstat(filename)(stats => {
24 if (stats.isDirectory()) {
25 return mkdir(path.resolve(dest, relativePath), { intermediate: true });
26 }
27 if (stats.isFile()) {
28 return copyFile(filename, path.resolve(dest, relativePath), {
29 intermediate: true
30 });
31 }
32 if (!stats.isSymbolicLink()) return null;
33 return readlink(filename)(linkPath => {
34 linkPath = path.resolve(path.dirname(filename), linkPath);
35 const linkDirname = path.dirname(linkPath);
36 if (
37 linkDirname === sourceTop ||
38 startsWith.call(linkDirname, sourceTop + path.sep)
39 ) {
40 linkPath = path.resolve(destTop, linkPath.slice(sourceTop.length + 1));
41 }
42 return symlink(
43 path.relative(path.dirname(path.resolve(dest, relativePath)), linkPath),
44 path.resolve(dest, relativePath),
45 { intermediate: true }
46 );
47 });
48 });
49 }),
50 error => {
51 if (options.loose && error.code === "ENOENT") return false;
52 throw error;
53 }
54 )(true);
55 };
56 copyDir.returnsPromise = true;
57
58 module.exports = exports = function (source, dest, options = null, cb = null) {
59 if (!isValue(cb) && isCallable(options)) {
60 cb = options;
61 options = {};
62 }
63
64 source = path.resolve(String(source));
65 dest = path.resolve(String(dest));
66 return lstat(dest, { loose: true })(stats => {
67 if (stats && stats.isDirectory()) {
68 return readdir(dest).then(filenames => {
69 if (!filenames.length) return;
70 throw new Error("Destination path is not empty");
71 });
72 }
73 return null;
74 })(() => copyDir(source, dest, options, source, dest)).cb(cb);
75 };
76 exports.copyDir = copyDir;
77 exports.returnsPromise = true;