-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdrives.js
691 lines (623 loc) · 19.8 KB
/
drives.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
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
const kit = require('./kit');
const {
_,
Promise
} = kit;
const br = kit.require('brush');
let jhash = null;
/**
* The built-in plguins for warp. It's more like examples
* to show how to use nokit efficiently.
*/
const Overview = 'drives'; // eslint-disable-line
module.exports = {
/**
* clean-css
* @param {Object} opts
* @return {Function}
*/
cleanCss: _.extend(function (opts) {
if (opts == null) {
opts = {};
}
const clean = kit.requireOptional('clean-css', __dirname);
return function () {
this.deps = [this.path];
this.set((new clean(opts).minify(this.contents)).styles);
return kit.log(br.cyan('clean css: ') + this.dest);
};
}, {
compress: ['.css']
/**
* coffee-script compiler
* @param {Object} opts Default is `{ bare: true }`.
* @return {Function}
*/
}),
coffee: _.extend(function (opts) {
if (opts == null) {
opts = {};
}
_.defaults(opts, {
bare: true
});
const coffee = kit.requireOptional('coffee-script', __dirname, '>=1.8.0');
return function () {
opts.filename = this.path;
this.deps = [this.path];
this.dest.ext = '.js';
try {
this.set(coffee.compile(this.contents + '', opts));
return kit.log(br.cyan('coffee: ') + this.path);
} catch (err) {
kit.err(br.red(err.stack));
return Promise.reject('coffeescriptCompileError');
}
};
}, {
compile: ['.coffee']
/**
* coffeelint processor
* @param {Object} opts It extends the default config
* of coffeelint, properties:
* ```js
* {
* colorize: true,
* reporter: 'default',
*
* // The json of the "coffeelint.json".
* // If it's null, coffeelint will try to find
* // "coffeelint.json" as its content.
* config: null | JSON | JsonFilePath
* }
* ```
* @return {Function}
*/
}),
coffeelint: _.extend(function (opts) {
if (opts == null) {
opts = {};
}
_.defaults(opts, {
colorize: true,
reporter: 'default'
});
const coffeelint = kit.requireOptional('coffeelint', __dirname);
if (!opts.config) {
const configfinder = require('coffeelint/lib/configfinder');
opts.config = configfinder.getConfig();
}
if (_.isString(opts.config)) {
opts.config = kit.readJsonSync(opts.config);
}
const Reporter = require(`coffeelint/lib/reporters/${opts.reporter}`);
return function () {
this.deps = [this.path];
const errorReport = new coffeelint.getErrorReport();
errorReport.lint(this.path, this.contents, opts.config);
const reporter = new Reporter(errorReport, opts);
for (let path in errorReport.paths) {
const errors = errorReport.paths[path];
kit.log(br.cyan('coffeelint: ') + _.trim(reporter.reportPath(path, errors)));
if (errors.length > 0) {
return Promise.reject(errors[0]);
}
}
};
}, {
lint: ['.coffee']
/**
* Parse commment from a js, coffee, or livescript file,
* and output a markdown string.
* @param {String} path
* @param {Object} opts Defaults:
* ```js
* {
* // Output doc path.
* out: 'readme.md',
*
* // jst template path.
* tpl: 'readme.jst.md',
*
* // Init doc info.
* doc: {},
*
* // Header size.
* h: 3,
*
* parseComment: () => {},
* formatComment: () => {}
* }
* ```
* @return {Function}
* @example
* The nofile of nokit shows how to use it.
*/
}),
comment2md(opts) {
if (opts == null) {
opts = {};
}
_.defaults(opts, {
out: 'readme.md',
tpl: 'readme.jst.md',
doc: {},
h: 3,
parseComment: {},
formatComment: {}
});
return _.extend(function (file) {
const toc = [];
opts.formatComment.name = function ({
name,
line
}) {
name = name.replace('self.', '');
const tocName = name.toLowerCase()
.replace(/\s/g, '-')
.replace(/[^\w-]/g, '');
toc.push(` - [${name}](#${tocName})`);
const link = `${file.path}?source#L${line}`;
return `- ${_.repeat('#', opts.h)} **[${name}](${link})**\n\n`;
};
const comments = kit.parseComment(this.contents + '', opts.parseComment);
opts.doc[this.path] = kit.formatComment(comments, opts.formatComment);
return opts.doc[this.path + '-toc'] = toc.join('\n');
}
, {
isWriter: true,
onEnd(file) {
if (_.keys(opts.doc).length < this.list.length) {
return;
}
this.deps = _.map(this.list, 'path');
this.deps.push(opts.tpl);
this.dest = kit.path.join(this.to, opts.out);
return kit.readFile(opts.tpl, 'utf8')
.then(tpl => file.set(_.template(tpl)({
doc: opts.doc
})))
.then(function () {
kit.log(br.cyan('comment2md: ') +
kit.path.join(file.to, opts.out)
);
return file.super();
});
}
}
);
},
/**
* Auto-compiler file by extension. It will search through
* `kit.drives`, and find proper drive to run the task.
* You can extend `kit.drives` to let it support more.
* For example:
* ```js
* kit.drives.myCompiler = kit._.extend(() => {
* // your compile logic
* }), { compiler: ['.jsx'] })
* ```
* @param {String} action By default, it can be
* 'compile' or 'compress' or 'lint'
* @param {Object} opts
* ```js
* {
* // If no compiler match.
* onNotFound: (fileInfo) => {}
* }
* ```
* @return {Function}
*/
auto(action, opts) {
if (opts == null) {
opts = {};
}
_.defaults(opts, {
onNotFound() {}
});
const list = _(kit.drives).map(action)
.compact().flatten().value().join(' ');
kit.log(br.green(`${action}: `) + `[ ${list} ]`);
const compilers = {};
const auto = function () {
const ext = this.dest.ext.toLowerCase();
if (!compilers[ext]) {
const d = _.find(kit.drives, drive =>
drive[action] &&
(drive[action].indexOf(ext) > -1)
);
if (d) {
compilers[ext] = d(opts[ext]);
} else {
return opts.onNotFound.call(this, this);
}
}
return this.drives.unshift(compilers[ext]);
};
// For hash
const _str = auto.toString;
auto.toString = function () {
let hash = _str.call(auto);
return hash += JSON.stringify(opts);
};
return auto;
},
/**
* Change dest path with a filter.
* @param {String} dir
* @param {Function} filter `(fileInfo, dir) -> Boolean`
* @return {Function}
*/
changeDir(dir, filter) {
return function (f) {
if (filter != null) {
if (filter(f, dir)) {
f.dest.dir = dir;
}
return;
}
return f.dest.dir = dir;
};
},
/**
* a batch file concat helper
* @param {String} name The output file path.
* @param {String} dir Optional. Override the dest of warp's.
* @return {Function}
*/
concat(name, dir) {
const all = [];
return _.extend(function () {
all.push(this.contents);
return kit.log(br.cyan('concat: ') + this.path);
}, {
isWriter: true,
onEnd() {
if (all.length < this.list.length) {
return;
}
if (dir == null) {
dir = this.to;
}
this.dest = kit.path.join(dir, name);
this.deps = _.map(this.list, 'path');
this.set(all.join('\n'));
return this.super();
}
});
},
/**
* Suffix file name with the hash value of file content.
* @param {String} hashMapPath The output file name hash map.
* @return {Function}
*/
hashSuffix(hashMapPath) {
jhash = kit.require('jhash');
jhash.setSymbols(
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
);
const map = {};
return _.assign(function (f) {
const src = f.dest + '';
f.dest.name += `.${jhash.hash(f.contents)}`;
return map[src] = f.dest + '';
}, {
onEnd() {
return kit.outputJson(hashMapPath, map);
}
});
},
/**
* Lint js via `jshint`.
* @param {Object} opts Properties:
* ```js
* {
* global: null,
* config: null | JSON | JsonFilePath
* }
* ```
* @return {Function}
*/
jshint: _.extend(function (opts) {
if (opts == null) {
opts = {};
}
_.defaults(opts, {});
const {
JSHINT
} = kit.requireOptional('jshint', __dirname);
const jshint = function (file) {
this.deps = [this.path];
if (JSHINT(this.contents, opts.config, opts.global)) {
kit.log(br.cyan('jshint: ') + this.path);
return;
}
let errs = '';
JSHINT.errors.forEach(function (err) {
if (err) {
return errs += `\nJshint ${br.red(err.id)}: \
${file.path}:${err.line}:${err.character}
"${br.cyan(err.evidence)}"
${br.yellow(err.reason)}
------------------------------------\
`;
}
});
return Promise.reject(errs);
};
return Promise.resolve(_.isString(opts.config) ?
kit.prop(opts, 'config', kit.readJson(opts.config)) : undefined
).then(() => jshint);
}
, {
lint: ['.js']
/**
* Compile less.
* @param {Object}
* @return {Function}
*/
}
),
less: _.extend(function (opts) {
if (opts == null) {
opts = {};
}
const less = kit.requireOptional('less', __dirname, '>=2.5.1');
return function (file) {
this.dest.ext = '.css';
opts.filename = this.path;
return less.render(this.contents + '', opts)
.then(function (output) {
file.deps = [file.path].concat(output.imports);
file.set(output.css);
return kit.log(br.cyan('less: ') + file.path);
}, function (err) {
if ((err.line == null)) {
return Promise.reject(err);
}
// The error message of less is the worst.
err.message = err.filename +
`:${err.line}:${err.column}\n` +
(err.extract != null ? err.extract.join('\n') : undefined) + '\n--------\n' +
err.message;
return Promise.reject(err);
});
};
}, {
compile: ['.less']
/**
* LiveScript compiler.
* @param {Object} opts Default is `{ bare: true }`.
* @return {Function}
*/
}),
livescript: _.extend(function (opts) {
if (opts == null) {
opts = {};
}
_.defaults(opts, {
bare: true
});
const LiveScript = kit.requireOptional('LiveScript', __dirname, '>=1.2.0');
return function () {
this.deps = [this.path];
opts.filename = this.path;
this.dest.ext = '.js';
try {
this.set(LiveScript.compile(this.contents + '', opts));
return kit.log(br.cyan('livescript: ') + this.path);
} catch (err) {
kit.err(br.red(err));
return Promise.reject('livescriptCompileError');
}
};
}, {
compile: ['.ls']
/**
* read file and set `contents`
* @param {Object} opts Defaults:
* ```js
* {
* isCache: false,
* encoding: 'utf8',
* cacheDir: '.nokit/warp'
* }
* ```
* @return {Function}
*/
}),
reader(opts) {
if (opts == null) {
opts = {};
}
_.defaults(opts, {
isCache: false,
encoding: 'utf8',
cacheDir: '.nokit/warp'
});
if (jhash == null) {
jhash = new(kit.require('jhash').constructor);
}
// Create a unique id for each workflow.
const hashDrives = function (ds) {
const str = _.map(ds, d => d.toString()).join();
return jhash.hash(str, true) + '';
};
const read = function () {
return kit.readFile(this.path, opts.encoding)
.then(this.set);
};
return _.extend(function (file) {
if (!this.list.cacheDir) {
this.list.isCache = opts.isCache;
this.list.cacheDir = kit.path.join(opts.cacheDir,
hashDrives(this.driveList));
}
if (this.isDir) {
return;
}
if (opts.isCache) {
return kit.depsCache({
deps: [this.path],
cacheDir: this.list.cacheDir
}).then(function (cache) {
file.deps = cache.deps;
if (cache.isNewer) {
kit.log(br.green('reader cache: ') +
file.deps.join(br.grey(', '))
);
file.drives.length = 0;
return Promise.all(_.map(cache.dests, (cachePath, dest) =>
kit.mkdirs(kit.path.dirname(dest))
.then(() =>
kit.link(cachePath, dest)
.catch(function (err) {
if (err.code !== 'EEXIST') {
return Promise.reject(err);
}
})
)
));
} else {
return read.call(file);
}
});
} else {
return read.call(file);
}
}, {
isReader: true
});
},
/**
* Compile stylus.
* @param {Object} opts It will use `stylus.set` to
* iterate `opts` and set the key-value, is the value is
* not a function.
* ```js
* {
* config: (styl) => {}
* }
* ```
* @return {Function}
* @example
* ```js
* kit.drives.stylus({
* compress: true,
* config: (styl) =>
* styl.define('jack', 'a persion')
* });
* ```
*/
stylus: _.extend(function (opts) {
if (opts == null) {
opts = {};
}
_.defaults(opts, {
config() {}
});
const stylus = kit.requireOptional('stylus', __dirname);
return function (file) {
this.dest.ext = '.css';
const styl = stylus(this.contents)
.set('filename', this.path);
for (let k in opts) {
const v = opts[k];
if (_.isFunction(v)) {
continue;
}
styl.set(k, v);
}
opts.config.call(this, styl);
return kit.promisify(styl.render, styl)()
.then(function (css) {
file.deps = [file.path].concat(styl.deps());
file.set(css);
return kit.log(br.cyan('stylus: ') + file.path);
});
};
}, {
compile: ['.styl']
/**
* uglify-js processor
* @param {Object} opts Defaults:
* ```js
* {
* output: {
* comments: (node, comment) => {
* let text = comment.value;
* let type = comment.type;
* if (type === "comment2")
* return /@preserve|@license|@cc_on/i.test(text);
* }
* }
* }
* ```
* @return {Function}
*/
}),
uglifyjs: _.extend(function (opts) {
if (opts == null) {
opts = {};
}
const uglify = kit.requireOptional('uglify-js', __dirname, '>=3.0.0');
if (opts.output == null) {
opts.output = {
comments(node, comment) {
const text = comment.value;
const {
type
} = comment;
if (type === "comment2") {
return /@preserve|@license|@cc_on/i.test(text);
}
}
};
}
return function () {
this.deps = [this.path];
try {
kit.log(br.cyan('uglifyjs: ') + this.dest);
return this.set((uglify.minify(this.contents + '', opts)).code);
} catch (err) {
return kit.logs(br.cyan('uglifyjs err:'), this.path, err.message);
}
};
}, {
compress: ['.js']
/**
* Output file by `contents` and `dest`.
* If the 'ext' or 'name' is not null,
* the 'base' will be override by the 'ext' and 'name'.
* @return {Function}
*/
}),
writer() {
const write = function (file) {
const {
dest,
contents
} = this;
if ((dest == null) || (contents == null)) {
return;
}
kit.log(br.cyan('writer: ') + this.dest);
return kit.outputFile(dest + '', contents, this.opts)
.then(function () {
if (!file.list.isCache) {
return;
}
kit.log(br.cyan('writer cache: ') + file.dest);
return kit.depsCache({
dests: file.dests || [file.dest + ''],
deps: file.deps || [file.path],
cacheDir: file.list.cacheDir
});
});
};
return _.extend(write, {
isWriter: true,
onEnd: write
});
}
};