-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathread-dir-to-tree.js
81 lines (62 loc) · 2 KB
/
read-dir-to-tree.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
var fs = require('fs-extra');
var path = require('path');
var _rootDir, _level, _ignores;
function getRootDir (dir) {
_rootDir = path.join(process.cwd(), dir);
if (_rootDir.slice(-1) === '/') {
_rootDir = _rootDir.slice(0, -1);
}
return _rootDir;
}
function getLevel (dirPath) {
if (dirPath === _rootDir) return 1;
return dirPath.split(_rootDir)[1].split('/').length;
}
function ignoreHandle (dirPath, dirName, ignoreContent) {
if (Object.prototype.toString.call(ignoreContent) === '[object Array]') {
for (var i = 0; i < _ignores.length; i++) {
if (ignoreHandle(dirPath, dirName, _ignores[i])) {
return true;
}
}
return false;
}
ignoreContent = ignoreContent.trim();
if (!ignoreContent) return false;
if (ignoreContent.includes('/')) {
ignoreContent = ignoreContent.slice(-1) === '/' ? ignoreContent.slice(0, -1) : ignoreContent;
var name = ignoreContent.split('/').slice(-1)[0];
return dirPath.includes(ignoreContent) && name === dirName;
}
return ignoreContent === dirName;
}
function buildFileTree (dir, arr) {
if (!arr) arr = [];
var list = dir.split('/');
var dirName = list[list.length - 1];
var data = {
name: dirName,
level: getLevel(dir)
};
var isIgnore = ignoreHandle(dir, dirName, _ignores);
if (isIgnore) return;
if (_level && data.level > _level) return;
if (fs.statSync(dir).isDirectory()) {
data.children = [];
fs.readdirSync(dir).forEach((item) => {
item = path.join(dir, item);
buildFileTree(item, data.children);
});
}
arr.push(data);
}
var ReadDirToTree = {};
ReadDirToTree.getFileTree = function ({ dir, ignore, level }) {
_rootDir = getRootDir(dir);
_level = level || null;
_ignores = ignore ? ignore.split(',') : [];
var fileTree = [];
buildFileTree(_rootDir, fileTree);
return fileTree;
}
module.exports = ReadDirToTree;