-
-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathindex.ts
295 lines (242 loc) · 7.45 KB
/
index.ts
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import { join, sep } from 'path';
import BlueBirdPromise from 'bluebird';
import File from './file';
import { Pattern, createSha1Hash } from 'hexo-util';
import { createReadStream, readdir, stat, watch } from 'hexo-fs';
import { magenta } from 'picocolors';
import { EventEmitter } from 'events';
import { isMatch, makeRe } from 'micromatch';
const defaultPattern = new Pattern(() => ({}));
interface Processor {
pattern: Pattern;
process: (file: File) => void;
}
class Box extends EventEmitter {
public options: any;
public context: any;
public base: any;
public processors: Processor[];
public _processingFiles: any;
public watcher: any;
public Cache: any;
// TODO: replace runtime class _File
public File: any;
public ignore: any;
public source: any;
public emit: any;
public ctx: any;
constructor(ctx, base, options?: object) {
super();
this.options = Object.assign({
persistent: true,
awaitWriteFinish: {
stabilityThreshold: 200
}
}, options);
if (!base.endsWith(sep)) {
base += sep;
}
this.context = ctx;
this.base = base;
this.processors = [];
this._processingFiles = {};
this.watcher = null;
this.Cache = ctx.model('Cache');
this.File = this._createFileClass();
let targets = this.options.ignored || [];
if (ctx.config.ignore && ctx.config.ignore.length) {
targets = targets.concat(ctx.config.ignore);
}
this.ignore = targets;
this.options.ignored = targets.map(s => toRegExp(ctx, s)).filter(x => x);
}
_createFileClass() {
const ctx = this.context;
class _File extends File {
public box: Box;
render(options) {
return ctx.render.render({
path: this.source
}, options);
}
renderSync(options) {
return ctx.render.renderSync({
path: this.source
}, options);
}
}
_File.prototype.box = this;
return _File;
}
addProcessor(pattern, fn) {
if (!fn && typeof pattern === 'function') {
fn = pattern;
pattern = defaultPattern;
}
if (typeof fn !== 'function') throw new TypeError('fn must be a function');
if (!(pattern instanceof Pattern)) pattern = new Pattern(pattern);
this.processors.push({
pattern,
process: fn
});
}
_readDir(base, prefix = '') {
const { context: ctx } = this;
const results = [];
return readDirWalker(ctx, base, results, this.ignore, prefix)
.return(results)
.map(path => this._checkFileStatus(path))
.map(file => this._processFile(file.type, file.path).return(file.path));
}
_checkFileStatus(path) {
const { Cache, context: ctx } = this;
const src = join(this.base, path);
return Cache.compareFile(
escapeBackslash(src.substring(ctx.base_dir.length)),
() => getHash(src),
() => stat(src)
).then(result => ({
type: result.type,
path
}));
}
process(callback?) {
const { base, Cache, context: ctx } = this;
return stat(base).then(stats => {
if (!stats.isDirectory()) return;
// Check existing files in cache
const relativeBase = escapeBackslash(base.substring(ctx.base_dir.length));
const cacheFiles = Cache.filter(item => item._id.startsWith(relativeBase)).map(item => item._id.substring(relativeBase.length));
// Handle deleted files
return this._readDir(base)
.then(files => cacheFiles.filter(path => !files.includes(path)))
.map(path => this._processFile(File.TYPE_DELETE, path));
}).catch(err => {
if (err && err.code !== 'ENOENT') throw err;
}).asCallback(callback);
}
_processFile(type, path) {
if (this._processingFiles[path]) {
return BlueBirdPromise.resolve();
}
this._processingFiles[path] = true;
const { base, File, context: ctx } = this;
this.emit('processBefore', {
type,
path
});
return BlueBirdPromise.reduce(this.processors, (count, processor) => {
const params = processor.pattern.match(path);
if (!params) return count;
const file = new File({
source: join(base, path),
path,
params,
type
});
return Reflect.apply(BlueBirdPromise.method(processor.process), ctx, [file])
.thenReturn(count + 1);
}, 0).then(count => {
if (count) {
ctx.log.debug('Processed: %s', magenta(path));
}
this.emit('processAfter', {
type,
path
});
}).catch(err => {
ctx.log.error({ err }, 'Process failed: %s', magenta(path));
}).finally(() => {
this._processingFiles[path] = false;
}).thenReturn(path);
}
watch(callback?) {
if (this.isWatching()) {
return BlueBirdPromise.reject(new Error('Watcher has already started.')).asCallback(callback);
}
const { base } = this;
function getPath(path) {
return escapeBackslash(path.substring(base.length));
}
return this.process().then(() => watch(base, this.options)).then(watcher => {
this.watcher = watcher;
watcher.on('add', path => {
this._processFile(File.TYPE_CREATE, getPath(path));
});
watcher.on('change', path => {
this._processFile(File.TYPE_UPDATE, getPath(path));
});
watcher.on('unlink', path => {
this._processFile(File.TYPE_DELETE, getPath(path));
});
watcher.on('addDir', path => {
let prefix = getPath(path);
if (prefix) prefix += '/';
this._readDir(path, prefix);
});
}).asCallback(callback);
}
unwatch() {
if (!this.isWatching()) return;
this.watcher.close();
this.watcher = null;
}
isWatching() {
return Boolean(this.watcher);
}
}
function escapeBackslash(path) {
// Replace backslashes on Windows
return path.replace(/\\/g, '/');
}
function getHash(path) {
const src = createReadStream(path);
const hasher = createSha1Hash();
const finishedPromise = new BlueBirdPromise((resolve, reject) => {
src.once('error', reject);
src.once('end', resolve);
});
src.on('data', chunk => { hasher.update(chunk); });
return finishedPromise.then(() => hasher.digest('hex'));
}
function toRegExp(ctx, arg) {
if (!arg) return null;
if (typeof arg !== 'string') {
ctx.log.warn('A value of "ignore:" section in "_config.yml" is not invalid (not a string)');
return null;
}
const result = makeRe(arg);
if (!result) {
ctx.log.warn('A value of "ignore:" section in "_config.yml" can not be converted to RegExp:' + arg);
return null;
}
return result;
}
function isIgnoreMatch(path, ignore) {
return path && ignore && ignore.length && isMatch(path, ignore);
}
function readDirWalker(ctx, base, results, ignore, prefix) {
if (isIgnoreMatch(base, ignore)) return BlueBirdPromise.resolve();
return BlueBirdPromise.map(readdir(base).catch(err => {
ctx.log.error({ err }, 'Failed to read directory: %s', base);
if (err && err.code === 'ENOENT') return [];
throw err;
}), async path => {
const fullpath = join(base, path);
const stats = await stat(fullpath).catch(err => {
ctx.log.error({ err }, 'Failed to stat file: %s', fullpath);
if (err && err.code === 'ENOENT') return null;
throw err;
});
const prefixPath = `${prefix}${path}`;
if (stats) {
if (stats.isDirectory()) {
return readDirWalker(ctx, fullpath, results, ignore, `${prefixPath}/`);
}
if (!isIgnoreMatch(fullpath, ignore)) {
results.push(prefixPath);
}
}
});
}
export = Box;