-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsymlink-helper.js
98 lines (98 loc) · 3.34 KB
/
symlink-helper.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
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const path = require("path");
const child_process = require("child_process");
const config_1 = require("./config");
/**
* You can extend this class in your project
* Set Config.helperClass to use your own
*/
class SymlinkHelper {
constructor(rootDir) {
this.nestingLevel = 0;
let startsWithSlash = false;
if (rootDir.startsWith('./')) {
startsWithSlash = true;
}
else if (rootDir.startsWith('../')) {
startsWithSlash = true;
}
if (!startsWithSlash) {
throw new Error('Directory name has to start with any of: ./, ../');
}
this.nestingLevel = rootDir.split('/').length - 1;
}
/**
* Fetches all symlinks in given directory recursively
* @param dir start by ./
* @returns {Promise<T>}
*/
findSymlinks(dir) {
return new Promise((resolve, reject) => {
let symlinks = {};
fs.readdir(dir, (err, list) => {
if (err)
return reject(err);
let pending = list.length;
if (!pending)
return resolve(symlinks);
list.forEach((file) => {
file = dir + '/' + file;
fs.lstat(file, (error, stat) => {
if (stat.isSymbolicLink()) {
symlinks[file] = fs.readlinkSync(file);
}
if (stat && stat.isDirectory()) {
this.findSymlinks(file).then(childLinks => {
symlinks = Object.assign({}, symlinks, childLinks);
if (!--pending)
resolve(symlinks);
});
}
else {
if (!--pending)
resolve(symlinks);
}
});
});
});
});
}
;
saveSymlinks(content) {
let savedSymlinks = this.getSavedSymlinks();
if (savedSymlinks) {
content = Object.assign({}, savedSymlinks, content);
}
let stringified = JSON.stringify(content, null, '\t');
return new Promise(resolve => {
fs.writeFile(config_1.Config.rootDir + config_1.Config.symlinksFile, stringified, (err) => {
if (err)
return console.error(err);
resolve(true);
});
});
}
copyFile(source, target) {
child_process.execSync('rm ' + target);
child_process.execSync('mkdir -p ' + path.dirname(target));
child_process.execSync('cp -R ' + path.resolve(source) + ' ' + target);
}
getRelativePath(path) {
for (let i = 0; i < this.nestingLevel; i++) {
path = path.replace('../', '');
}
return path;
}
getSavedSymlinks() {
let savedSymlinks = null;
try {
savedSymlinks = require('../../' + config_1.Config.rootDir + config_1.Config.symlinksFile);
}
catch (e) { }
return savedSymlinks;
}
}
exports.SymlinkHelper = SymlinkHelper;
//# sourceMappingURL=symlink-helper.js.map