forked from ysmood/nokit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdrives.coffee
526 lines (458 loc) · 15 KB
/
drives.coffee
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
kit = require './kit'
{ _, Promise } = kit
br = kit.require 'brush'
jhash = null
###*
* The built-in plguins for warp. It's more like examples
* to show how to use nokit efficiently.
###
Overview = 'drives'
module.exports =
###*
* clean-css
* @param {Object} opts
* @return {Function}
###
cleanCss: _.extend (opts = {}) ->
clean = kit.requireOptional 'clean-css', __dirname
->
@deps = [@path]
@set (new clean(opts).minify @contents).styles
kit.log br.cyan('clean css: ') + @dest
, compress: ['.css']
###*
* coffee-script compiler
* @param {Object} opts Default is `{ bare: true }`.
* @return {Function}
###
coffee: _.extend (opts = {}) ->
_.defaults opts,
bare: true
coffee = kit.requireOptional 'coffee-script', __dirname, '>=1.8.0'
->
opts.filename = @path
@deps = [@path]
@dest.ext = '.js'
try
@set coffee.compile @contents + '', opts
kit.log br.cyan('coffee: ') + @path
catch err
kit.err br.red err.stack
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 (opts = {}) ->
_.defaults opts,
colorize: true
reporter: 'default'
coffeelint = kit.requireOptional 'coffeelint', __dirname
if not opts.config
configfinder = require 'coffeelint/lib/configfinder'
opts.config = configfinder.getConfig()
if _.isString opts.config
opts.config = kit.readJsonSync opts.config
Reporter = require 'coffeelint/lib/reporters/' + opts.reporter
->
@deps = [@path]
errorReport = new coffeelint.getErrorReport()
errorReport.lint @path, @contents, opts.config
reporter = new Reporter errorReport, opts
for path, errors of errorReport.paths
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 = {}) ->
_.defaults opts,
out: 'readme.md'
tpl: 'readme.jst.md'
doc: {}
h: 3
parseComment: {}
formatComment: {}
_.extend (file) ->
toc = []
opts.formatComment.name = ({ name, line }) ->
name = name.replace 'self.', ''
tocName = name.toLowerCase()
.replace(/\s/g, '-')
.replace(/[^\w-]/g, '')
toc.push " - [#{name}](##{tocName})"
link = "#{file.path}?source#L#{line}"
"- #{_.repeat '#', opts.h} **[#{name}](#{link})**\n\n"
comments = kit.parseComment @contents + '', opts.parseComment
opts.doc[@path] = kit.formatComment comments, opts.formatComment
opts.doc[@path + '-toc'] = toc.join '\n'
, isWriter: true, onEnd: (file) ->
return if _.keys(opts.doc).length < @list.length
@deps = _.map @list, 'path'
@deps.push opts.tpl
@dest = kit.path.join @to, opts.out
kit.readFile opts.tpl, 'utf8'
.then (tpl) ->
file.set _.template(tpl) { doc: opts.doc }
.then ->
kit.log br.cyan('comment2md: ') +
kit.path.join(file.to, opts.out)
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 = {}) ->
_.defaults opts,
onNotFound: ->
list = _(kit.drives).map(action)
.compact().flatten().value().join ' '
kit.log br.green("#{action}: ") + "[ #{list} ]"
compilers = {}
auto = ->
ext = @dest.ext.toLowerCase()
if not compilers[ext]
d = _.find kit.drives, (drive) ->
drive[action] and
drive[action].indexOf(ext) > -1
if d
compilers[ext] = d opts[ext]
else
return opts.onNotFound.call @, @
@drives.unshift compilers[ext]
# For hash
_str = auto.toString
auto.toString = ->
hash = _str.call auto
hash += JSON.stringify opts
auto
###*
* Change dest path with a filter.
* @param {String} dir
* @param {Function} filter `(fileInfo, dir) -> Boolean`
* @return {Function}
###
changeDir: (dir, filter) ->
(f) ->
if filter?
if filter f, dir
f.dest.dir = dir
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) ->
all = []
_.extend ->
all.push @contents
kit.log br.cyan('concat: ') + @path
, isWriter: true, onEnd: ->
return if all.length < @list.length
dir ?= @to
@dest = kit.path.join dir, name
@deps = _.map @list, 'path'
@set all.join '\n'
@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'
)
map = {}
_.assign (f) ->
src = f.dest + ''
f.dest.name += '.' + jhash.hash(f.contents)
map[src] = f.dest + ''
, onEnd: ->
kit.outputJson hashMapPath, map
###*
* Lint js via `jshint`.
* @param {Object} opts Properties:
* ```js
* {
* global: null,
* config: null | JSON | JsonFilePath
* }
* ```
* @return {Function}
###
jshint: _.extend (opts = {}) ->
_.defaults opts, {}
{ JSHINT } = kit.requireOptional 'jshint', __dirname
jshint = (file) ->
@deps = [@path]
if JSHINT @contents, opts.config, opts.global
kit.log br.cyan('jshint: ') + @path
return
errs = ''
JSHINT.errors.forEach (err) ->
if err
errs += """\nJshint #{br.red err.id}: \
#{file.path}:#{err.line}:#{err.character}
"#{br.cyan err.evidence}"
#{br.yellow err.reason}
------------------------------------
"""
Promise.reject errs
Promise.resolve(if _.isString opts.config
kit.prop opts, 'config', kit.readJson opts.config
).then -> jshint
, lint: ['.js']
###*
* Compile less.
* @param {Object}
* @return {Function}
###
less: _.extend (opts = {}) ->
less = kit.requireOptional 'less', __dirname, '>=2.5.1'
(file) ->
@dest.ext = '.css'
opts.filename = @path
less.render @contents + '', opts
.then (output) ->
file.deps = [file.path].concat output.imports
file.set output.css
kit.log br.cyan('less: ') + file.path
, (err) ->
if not err.line?
return Promise.reject err
# The error message of less is the worst.
err.message = err.filename +
":#{err.line}:#{err.column}\n" +
err.extract?.join('\n') + '\n--------\n' +
err.message
Promise.reject err
, compile: ['.less']
###*
* LiveScript compiler.
* @param {Object} opts Default is `{ bare: true }`.
* @return {Function}
###
livescript: _.extend (opts = {}) ->
_.defaults opts, {
bare: true
}
LiveScript = kit.requireOptional 'LiveScript', __dirname, '>=1.2.0'
->
@deps = [@path]
opts.filename = @path
@dest.ext = '.js'
try
@set LiveScript.compile @contents + '', opts
kit.log br.cyan('livescript: ') + @path
catch err
kit.err br.red err
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 = {}) ->
_.defaults opts, {
isCache: false
encoding: 'utf8'
cacheDir: '.nokit/warp'
}
jhash ?= new (kit.require('jhash').constructor)
# Create a unique id for each workflow.
hashDrives = (ds) ->
str = _.map(ds, (d) -> d.toString()).join()
jhash.hash(str, true) + ''
read = ->
kit.readFile @path, opts.encoding
.then @set
_.extend (file) ->
if not @list.cacheDir
@list.isCache = opts.isCache
@list.cacheDir = kit.path.join opts.cacheDir,
hashDrives @driveList
return if @isDir
if opts.isCache
kit.depsCache
deps: [@path]
cacheDir: @list.cacheDir
.then (cache) ->
file.deps = cache.deps
if cache.isNewer
kit.log br.green('reader cache: ') +
file.deps.join br.grey ', '
file.drives.length = 0
Promise.all _.map cache.dests, (cachePath, dest) ->
kit.mkdirs kit.path.dirname dest
.then ->
kit.link cachePath, dest
.catch (err) ->
if err.code != 'EEXIST'
Promise.reject err
else
read.call file
else
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 (opts = {}) ->
_.defaults opts,
config: ->
stylus = kit.requireOptional 'stylus', __dirname
(file) ->
@dest.ext = '.css'
styl = stylus @contents
.set 'filename', @path
for k, v of opts
continue if _.isFunction v
styl.set k, v
opts.config.call @, styl
kit.promisify(styl.render, styl)()
.then (css) ->
file.deps = [file.path].concat styl.deps()
file.set css
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 (opts = {}) ->
uglify = kit.requireOptional 'uglify-js', __dirname, '>=2.0.0'
opts.fromString = true
opts.output ?=
comments: (node, comment) ->
text = comment.value
type = comment.type
if type == "comment2"
return /@preserve|@license|@cc_on/i.test text
->
@deps = [@path]
try
kit.log br.cyan('uglifyjs: ') + @dest
@set (uglify.minify @contents + '', opts).code
catch err
kit.logs br.cyan('uglifyjs err:'), @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: ->
write = (file) ->
{ dest, contents } = @
return if not dest? or not contents?
kit.log br.cyan('writer: ') + @dest
kit.outputFile dest + '', contents, @opts
.then ->
return if not file.list.isCache
kit.log br.cyan('writer cache: ') + file.dest
kit.depsCache
dests: file.dests or [file.dest + '']
deps: file.deps or [file.path]
cacheDir: file.list.cacheDir
_.extend write , { isWriter: true, onEnd: write }