-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
147 lines (125 loc) · 3.49 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import scanDirEachSync from '@iyowei/scan-dir-each-sync';
import scanDirEach from '@iyowei/scan-dir-each';
import isTrue from '@iyowei/is-true';
import notEmptyPlainObject from '@iyowei/not-empty-plain-object';
function registerFactory() {
return {
files: new Set(),
dirs: new Set(),
};
}
function syncCrawler({ from, worker, register }) {
scanDirEachSync(from, (cur, index) => {
const MAPPED = worker(cur, index);
// 保留
if (notEmptyPlainObject(MAPPED) || isTrue(MAPPED)) {
// 保留:寄存需要保留的文件夹
if (cur.dirent.isDirectory()) {
register.dirs.add(cur);
// 继续穷举需要保留的文件夹
syncCrawler({ from: cur.path, worker, register });
// 阅后即焚
return false;
}
// 保留:寄存需要保留的文件
register.files.add(cur);
// 阅后即焚
return false;
}
// 阅后即焚
return false;
});
}
function asyncCrawler({ from, worker, register }) {
let currentDepthFoundDirs = [];
return new Promise((resolveParent, rejectParent) => {
scanDirEach(from, (cur, index) => {
const MAPPED = worker(cur, index);
// 保留
if (notEmptyPlainObject(MAPPED) || isTrue(MAPPED)) {
// 保留:寄存需要保留的文件夹
if (cur.dirent.isDirectory()) {
register.dirs.add(cur);
currentDepthFoundDirs.push(cur);
// 阅后即焚
return false;
}
// 保留:寄存需要保留的文件
register.files.add(cur);
// 阅后即焚
return false;
}
// 阅后即焚
return false;
}).then(
() => {
// 继续穷举需要保留的文件夹
if (currentDepthFoundDirs.length !== 0) {
if (currentDepthFoundDirs.length === 1) {
asyncCrawler({
from: currentDepthFoundDirs[0].path,
worker,
register,
}).then(
() => {
resolveParent();
},
(err) => {
rejectParent(err);
},
);
return;
}
Promise.all(
currentDepthFoundDirs.map(
(cur) =>
new Promise((resolveChild, rejectChild) => {
asyncCrawler({ from: cur.path, worker, register }).then(
() => {
resolveChild();
},
(err) => {
rejectChild(err);
},
);
}),
),
).then(
() => {
currentDepthFoundDirs = [];
resolveParent();
},
(err) => {
currentDepthFoundDirs = [];
rejectParent(err);
},
);
currentDepthFoundDirs = [];
return;
}
resolveParent();
},
(err) => {
rejectParent(err);
},
);
});
}
export function fsDeepWalkSync({ from, worker = () => true }) {
const REGISTER = registerFactory();
syncCrawler({ from, worker, register: REGISTER });
return REGISTER;
}
export function fsDeepWalk({ from, worker = () => true }) {
const REGISTER = registerFactory();
return new Promise((resolve, reject) => {
asyncCrawler({ from, worker, register: REGISTER }).then(
() => {
resolve(REGISTER);
},
(err) => {
reject(err);
},
);
});
}