-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
112 lines (94 loc) · 2.52 KB
/
index.js
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
const path = require("path");
const linkOrCopyFolders = require("./source/linkOrCopyFolders");
const watchFolders = require("./source/watchFolders");
const { isDirectory } = require("./source/helpers")
const defaultOptions = {
type: "hardlink",
ignore: undefined,
watch: false,
bail: false,
quiet: true, // defaults to false from CLI
verbose: false,
onSync: () => {},
onUpdate: () => {},
};
const wrappedOnSync = (onSync) => (info) => {
console.log(`Copied ${info.relativePath}`);
return onSync(info)
}
const wrappedOnUpdate = (onUpdate) => (info) => {
switch (info.type) {
case "add":
console.log(`Added ${info.path}`);
break;
case "change":
console.log(`Updated ${info.path}`);
break;
case "unlink":
console.log(`Removed ${info.path}`);
break;
case "unlinkDir":
console.log(`Removed directory ${info.path}`);
break;
}
return onUpdate(info)
}
function ensureUniqueFolders(sourceDirs) {
const folderNames = {};
sourceDirs.forEach((sourceDir) => {
if (!isDirectory(sourceDir)) {
throw new Error(
`${sourceDir} is not a directory.`
);
}
const folderName = path.parse(sourceDir).name;
if (folderNames[folderName]) {
throw new Error(
`All folder names must be unique. Multiple sources share the folder name ${folderName}.`
);
}
folderNames[folderName] = true;
});
}
function logOutput(sourceDirs, targetDir, watch) {
const folderNames = sourceDirs.map(dir => path.parse(dir).name);
console.log(`Synchronized the following folders to ${targetDir}`);
console.log(folderNames.map(x => `* ${x}`).join("\n"));
if (watch) {
console.log("Now watching for any file changes to sync.")
}
}
module.exports = function syncFolders(sourceDirs, targetDir, options = {}) {
const {
bail,
type,
ignore,
quiet,
watch,
verbose,
onSync,
onUpdate,
} = Object.assign({}, defaultOptions, options);
const arrSourceDirs = Array.isArray(sourceDirs) ? sourceDirs : [sourceDirs];
ensureUniqueFolders(arrSourceDirs);
if (!quiet) {
logOutput(sourceDirs, targetDir, watch);
}
linkOrCopyFolders(arrSourceDirs, targetDir, {
type,
quiet,
ignore,
bail,
onSync: verbose && !quiet ? wrappedOnSync(onSync) : onSync,
});
if (watch) {
const watcher = watchFolders(arrSourceDirs, targetDir, {
type,
ignore,
bail,
quiet,
onUpdate: verbose && !quiet ? wrappedOnUpdate(onUpdate) : onUpdate,
});
return watcher;
}
};