forked from jackiealex/nobone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkit.coffee
1380 lines (1232 loc) · 33.7 KB
/
kit.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
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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
colors = require 'colors'
_ = require 'lodash'
Promise = require 'bluebird'
fs = require 'fs-more'
###*
* All the async functions in `kit` return promise object.
* Most time I use it to handle files and system staffs.
* @type {Object}
###
kit = {}
###*
* kit extends all the promise functions of [fs-more][fs-more].
* [fs-more]: https://github.com/ysmood/fs-more
* @example
* ```coffeescript
* kit.readFile('test.txt').done (str) ->
* console.log str
*
* kit.outputFile('a.txt', 'test').done()
* ```
###
kit_extends_fs_promise = 'promise'
for k, v of fs
if k.slice(-1) == 'P'
kit[k.slice(0, -1)] = fs[k]
_.extend kit, {
###*
* The lodash lib.
* @type {Object}
###
_: _
require_cache: {}
###*
* An throttle version of `Promise.all`, it runs all the tasks under
* a concurrent limitation.
* @param {Int} limit The max task to run at the same time. It's optional.
* Default is Infinity.
* @param {Array | Function} list
* If the list is an array, it should be a list of functions or promises, and each function will return a promise.
* If the list is a function, it should be a iterator that returns a promise,
* when it returns `undefined`, the iteration ends.
* @param {Boolean} save_resutls Whether to save each promise's result or not. Default is true.
* @param {Function} progress If a task ends, the resolve value will be passed to this function.
* @return {Promise}
* @example
* ```coffeescript
* urls = [
* 'http://a.com'
* 'http://b.com'
* 'http://c.com'
* 'http://d.com'
* ]
* tasks = [
* -> kit.request url[0]
* -> kit.request url[1]
* -> kit.request url[2]
* -> kit.request url[3]
* ]
*
* kit.async(tasks).then ->
* kit.log 'all done!'
*
* kit.async(2, tasks).then ->
* kit.log 'max concurrent limit is 2'
*
* kit.async 3, ->
* url = urls.pop()
* if url
* kit.request url
* .then ->
* kit.log 'all done!'
* ```
###
async: (limit, list, save_resutls = true, progress = ->) ->
from = 0
resutls = []
iter_index = 0
running = 0
is_iter_done = false
if not _.isNumber limit
save_resutls = list
list = limit
limit = Infinity
if _.isArray list
list_len = list.length - 1
iter = (i) ->
return if i > list_len
if _.isFunction list[i]
list[i](i)
else
list[i]
else if _.isFunction list
iter = list
else
Promise.reject new Error('unknown list type: ' + typeof list)
new Promise (resolve, reject) ->
add_task = ->
task = iter(iter_index++)
if is_iter_done or task == undefined
is_iter_done = true
all_done() if running == 0
return false
if _.isFunction(task.then)
p = task
else
p = Promise.resolve task
running++
p.then (ret) ->
running--
if save_resutls
resutls.push ret
progress ret
add_task()
.catch (err) ->
running--
reject err
return true
all_done = ->
if save_resutls
resolve resutls
else
resolve()
for i in [0 ... limit]
break if not add_task()
###*
* Creates a function that is the composition of the provided functions.
* Besides it can also accept async function that returns promise.
* It's more powerful than `_.compose`.
* @param {Function | Array} fns Functions that return promise or any value.
* And the array can also contains promises.
* @return {Function} A composed function that will return a promise.
* @example
* ```coffeescript
* # It helps to decouple sequential pipeline code logic.
*
* create_url = (name) ->
* return "http://test.com/" + name
*
* curl = (url) ->
* kit.request(url).then ->
* kit.log 'get'
*
* save = (str) ->
* kit.outputFile('a.txt', str).then ->
* kit.log 'saved'
*
* download = kit.compose create_url, curl, save
* # same as "download = kit.compose [create_url, curl, save]"
*
* download 'home'
* ```
###
compose: (fns...) -> (val) ->
fns = fns[0] if _.isArray fns[0]
fns.reduce (pre_fn, fn) ->
if _.isFunction fn.then
pre_fn.then -> fn
else
pre_fn.then fn
, Promise.resolve(val)
###*
* Daemonize a program.
* @param {Object} opts Defaults:
* {
* bin: 'node'
* args: ['app.js']
* stdout: 'stdout.log'
* stderr: 'stderr.log'
* }
* @return {Porcess} The daemonized process.
###
daemonize: (opts = {}) ->
_.defaults opts, {
bin: 'node'
args: ['app.js']
stdout: 'stdout.log'
stderr: 'stderr.log'
}
out_log = os.openSync(opts.stdout, 'a')
err_log = os.openSync(opts.stderr, 'a')
p = kit.spawn(opts.bin, opts.args, {
detached: true
stdio: [ 'ignore', out_log, err_log ]
}).process
p.unref()
kit.log "Run as background daemon, PID: #{p.pid}".yellow
p
###*
* A simple decrypt helper
* @param {Any} data
* @param {String | Buffer} password
* @param {String} algorithm Default is 'aes128'.
* @return {Buffer}
###
decrypt: (data, password, algorithm = 'aes128') ->
crypto = kit.require 'crypto'
decipher = crypto.createDecipher algorithm, password
if kit.node_version() < 0.10
if Buffer.isBuffer data
data = data.toString 'binary'
new Buffer(
decipher.update(data, 'binary') + decipher.final()
'binary'
)
else
if not Buffer.isBuffer data
data = new Buffer(data)
Buffer.concat [decipher.update(data), decipher.final()]
###*
* A simple encrypt helper
* @param {Any} data
* @param {String | Buffer} password
* @param {String} algorithm Default is 'aes128'.
* @return {Buffer}
###
encrypt: (data, password, algorithm = 'aes128') ->
crypto = kit.require 'crypto'
cipher = crypto.createCipher algorithm, password
if kit.node_version() < 0.10
if Buffer.isBuffer data
data = data.toString 'binary'
new Buffer(
cipher.update(data, 'binary') + cipher.final()
'binary'
)
else
if not Buffer.isBuffer data
data = new Buffer(data)
Buffer.concat [cipher.update(data), cipher.final()]
###*
* A shortcut to set process option with specific mode,
* and keep the current env variables.
* @param {String} mode 'development', 'production', etc.
* @return {Object} `process.env` object.
###
env_mode: (mode) ->
{
env: _.defaults(
{ NODE_ENV: mode }
process.env
)
}
###*
* A log error shortcut for `kit.log(msg, 'error', opts)`
* @param {Any} msg
* @param {Object} opts
###
err: (msg, opts = {}) ->
kit.log msg, 'error', opts
###*
* A better `child_process.exec`.
* @param {String} cmd Shell commands.
* @param {String} shell Shell name. Such as `bash`, `zsh`. Optinal.
* @return {Promise} Resolves when the process's stdio is drained.
* @example
* ```coffeescript
* kit.exec """
* a=10
* echo $a
* """
*
* # Bash doesn't support "**" recusive match pattern.
* kit.exec """
* echo **\/*.css
* """, 'zsh'
* ```
###
exec: (cmd, shell) ->
stream = kit.require 'stream'
shell = process.env.SHELL or
process.env.ComSpec or
process.env.COMSPEC
cmd_stream = new stream.Transform
cmd_stream.push cmd
cmd_stream.end()
stdout = ''
out_stream = new stream.Writable
out_stream._write = (chunk) ->
stdout += chunk
stderr = ''
err_stream = new stream.Writable
err_stream._write = (chunk) ->
stderr += chunk
p = kit.spawn shell, [], {
stdio: 'pipe'
}
cmd_stream.pipe p.process.stdin
p.process.stdout.pipe out_stream
p.process.stderr.pipe err_stream
p.then (msg) ->
_.extend msg, { stdout, stderr }
###*
* See my project [fs-more][fs-more].
* [fs-more]: https://github.com/ysmood/fs-more
###
fs: fs
###*
* A scaffolding helper to generate template project.
* The `lib/cli.coffee` used it as an example.
* @param {Object} opts Defaults:
* ```coffeescript
* {
* src_dir: null
* patterns: '**'
* dest_dir: null
* data: {}
* compile: (str, data, path) ->
* compile str
* }
* ```
* @return {Promise}
###
generate_bone: (opts) ->
###
It will treat all the files in the path as an ejs file
###
_.defaults opts, {
src_dir: null
patterns: ['**', '**/.*']
dest_dir: null
data: {}
compile: (str, data, path) ->
data.filename = path
_.template str, data
}
kit.glob(opts.patterns, { cwd: opts.src_dir })
.then (paths) ->
Promise.all paths.map (path) ->
src_path = kit.path.join opts.src_dir, path
dest_path = kit.path.join opts.dest_dir, path
kit.readFile(src_path, 'utf8')
.then (str) ->
opts.compile str, opts.data, src_path
.then (code) ->
kit.outputFile dest_path, code
.catch (err) ->
if err.cause.code != 'EISDIR'
Promise.reject err
###*
* See the https://github.com/isaacs/node-glob
* @param {String | Array} patterns Minimatch pattern.
* @param {Object} opts The glob options.
* @return {Promise} Contains the path list.
###
glob: (patterns, opts) ->
if _.isString patterns
patterns = [patterns]
all_paths = []
stat_cache = {}
Promise.all patterns.map (p) ->
kit._glob p, opts
.then (paths) ->
_.extend stat_cache, paths.glob.statCache
all_paths = _.union all_paths, paths
.then ->
all_paths.stat_cache = stat_cache
all_paths
_glob: (pattern, opts) ->
glob = kit.require 'glob'
new Promise (resolve, reject) ->
g = glob pattern, opts, (err, paths) ->
paths.glob = g
if err
reject err
else
resolve paths
###*
* See my [jhash][jhash] project.
* [jhash]: https://github.com/ysmood/jhash
###
jhash: require 'jhash'
###*
* It will find the right `key/value` pair in your defined `kit.lang_set`.
* If it cannot find the one, it will output the key directly.
* @param {String} cmd The original text.
* @param {String} name The target language name.
* @param {String} lang_set Specific a language collection.
* @return {String}
* @example
* ```coffeescript
* lang_set =
* cn:
* China: '中国'
* open:
* formal: '开启' # Formal way to say 'open'.
* casual: '打开' # Casual way to say 'open'.
* jp:
* human: '人間'
* 'find %s men': '%sっ人が見付かる'
*
* kit.lang('China', 'cn', lang_set) # -> '中国'
* kit.lang('open|casual', 'cn', lang_set) # -> '打开'
* kit.lang('find %s men', [10], 'jp', lang_set) # -> '10っ人が見付かる'
* ```
* @example
* Supports we have two json file in `langs_dir_path` folder.
* - cn.js, content: `module.exports = { China: '中国' }`
* - jp.coffee, content: `module.exports = 'Good weather.': '日和。'`
*
* ```coffeescript
* kit.lang_load 'langs_dir_path'
*
* kit.lang_current = 'cn'
* 'China'.l # '中国'
* 'Good weather.'.lang('jp') # '日和。'
*
* kit.lang_current = 'en'
* 'China'.l # 'China'
* 'Good weather.'.lang('jp') # 'Good weather.'
* ```
###
lang: (cmd, args = [], name, lang_set) ->
if _.isString args
lang_set = name
name = args
args = []
name ?= kit.lang_current
lang_set ?= kit.lang_set
i = cmd.lastIndexOf '|'
if i > -1
key = cmd[...i]
cat = cmd[i + 1 ..]
else
key = cmd
out = if lang_set[name]
if lang_set[name][key] == undefined
key
else
if cat == undefined
lang_set[name][key]
else if _.isObject lang_set[name][key]
lang_set[name][key][cat]
else
key
else
key
if args.length > 0
util = kit.require 'util'
args.unshift out
util.format.apply util, args
else
out
###*
* Language collections.
* @type {Object}
* @example
* ```coffeescript
* kit.lang_set = {
* 'cn': { 'China': '中国' }
* }
* ```
###
lang_set: {}
###*
* Current default language.
* @type {String}
* @default 'en'
###
lang_current: 'en'
###*
* Load language set directory and save them into
* the `kit.lang_set`.
* @param {String} dir_path The directory path that contains
* js or coffee files.
* @example
* ```coffeescript
* kit.lang_load 'assets/lang'
* kit.lang_current = 'cn'
* kit.log 'test'.l # -> '测试'.
* kit.log '%s persons'.lang([10]) # -> '10 persons'
* ```
###
lang_load: (dir_path) ->
return if not _.isString dir_path
dir_path = kit.fs.realpathSync dir_path
paths = kit.fs.readdirSync dir_path
for p in paths
ext = kit.path.extname p
continue if _.isEmpty ext
name = kit.path.basename p, ext
kit.lang_set[name] = require kit.path.join(dir_path, name)
Object.defineProperty String.prototype, 'l', {
get: -> kit.lang this + ''
}
String.prototype.lang = (args...) ->
args.unshift this + ''
kit.lang.apply null, args
###*
* For debugging use. Dump a colorful object.
* @param {Object} obj Your target object.
* @param {Object} opts Options. Default:
* { colors: true, depth: 5 }
* @return {String}
###
inspect: (obj, opts) ->
util = kit.require 'util'
_.defaults opts, {
colors: kit.is_development()
depth: 5
}
str = util.inspect obj, opts
###*
* Nobone use it to check the running mode of the app.
* Overwrite it if you want to control the check logic.
* By default it returns the `rocess.env.NODE_ENV == 'development'`.
* @return {Boolean}
###
is_development: ->
process.env.NODE_ENV == 'development'
###*
* Nobone use it to check the running mode of the app.
* Overwrite it if you want to control the check logic.
* By default it returns the `rocess.env.NODE_ENV == 'production'`.
* @return {Boolean}
###
is_production: ->
process.env.NODE_ENV == 'production'
###*
* A better log for debugging, it uses the `kit.inspect` to log.
*
* You can use terminal command like `log_reg='pattern' node app.js` to
* filter the log info.
*
* You can use `log_trace='on' node app.js` to force each log end with a
* stack trace.
* @param {Any} msg Your log message.
* @param {String} action 'log', 'error', 'warn'.
* @param {Object} opts Default is same with `kit.inspect`
###
log: (msg, action = 'log', opts = {}) ->
if not kit.last_log_time
kit.last_log_time = new Date
if process.env.log_reg
kit.log_reg = new RegExp(process.env.log_reg)
time = new Date()
time_delta = (+time - +kit.last_log_time).toString().magenta + 'ms'
kit.last_log_time = time
time = [
[
kit.pad time.getFullYear(), 4
kit.pad time.getMonth() + 1, 2
kit.pad time.getDate(), 2
].join('-')
[
kit.pad time.getHours(), 2
kit.pad time.getMinutes(), 2
kit.pad time.getSeconds(), 2
].join(':')
].join(' ').grey
log = ->
str = _.toArray(arguments).join ' '
if kit.log_reg and not kit.log_reg.test(str)
return
console[action] str.replace /\n/g, '\n '
if process.env.log_trace == 'on'
console.log (new Error).stack.replace(/.+\n.+\n.+/, '\nStack trace:').grey
if _.isObject msg
log "[#{time}] ->\n" + kit.inspect(msg, opts), time_delta
else
log "[#{time}]", msg, time_delta
if action == 'error'
process.stdout.write "\u0007"
###*
* Monitor an application and automatically restart it when file changed.
* When the monitored app exit with error, the monitor itself will also exit.
* It will make sure your app crash properly.
* @param {Object} opts Defaults:
* ```coffeescript
* {
* bin: 'node'
* args: ['app.js']
* watch_list: ['app.js']
* mode: 'development'
* }
* ```
* @return {Process} The child process.
###
monitor_app: (opts) ->
_.defaults opts, {
bin: 'node'
args: ['app.js']
watch_list: ['app.js']
mode: 'development'
}
sep_line = ->
console.log _.times(process.stdout.columns, -> '*').join('').yellow
child_ps = null
start = ->
sep_line()
child_ps = kit.spawn(
opts.bin
opts.args
kit.env_mode opts.mode
).process
child_ps.on 'close', (code, sig) ->
child_ps.is_closed = true
kit.log 'EXIT'.yellow + " code: #{(code + '').cyan} signal: #{(sig + '').cyan}"
if code != null and code != 0
kit.log 'Process closed. Edit and save the watched file to restart.'.red
process.on 'SIGINT', ->
child_ps.kill 'SIGINT'
process.exit()
kit.watch_files opts.watch_list, (path, curr, prev) ->
if curr.mtime != prev.mtime
kit.log "Reload app, modified: ".yellow + path
if child_ps.is_closed
start()
else
child_ps.on 'close', start
child_ps.kill 'SIGINT'
kit.log "Monitor: ".yellow + opts.watch_list
start()
child_ps
###*
* Node version. Such as `v0.10.23` is `0.1023`, `v0.10.1` is `0.1001`.
* @type {Float}
###
node_version: ->
ms = process.versions.node.match /(\d+)\.(\d+)\.(\d+)/
str = ms[1] + '.' + kit.pad(ms[2], 2) + kit.pad(ms[3], 2)
+str
###*
* Open a thing that your system can recognize.
* Now only support Windows, OSX or system that installed 'xdg-open'.
* @param {String} cmd The thing you want to open.
* @param {Object} opts The options of the node native `child_process.exec`.
* @return {Promise} When the child process exits.
* @example
* ```coffeescript
* # Open a webpage with the default browser.
* kit.open 'http://ysmood.org'
* ```
###
open: (cmd, opts = {}) ->
{ exec } = kit.require 'child_process'
switch process.platform
when 'darwin'
cmds = ['open']
when 'win32'
cmds = ['start']
else
which = kit.require 'which'
try
cmds = [which.sync('xdg-open')]
catch
cmds = []
cmds.push cmd
new Promise (resolve, reject) ->
exec cmds.join(' '), opts, (err, stdout, stderr) ->
if err
reject err
else
resolve { stdout, stderr }
###*
* String padding helper.
* @param {Sting | Number} str
* @param {Number} width
* @param {String} char Padding char. Default is '0'.
* @return {String}
* @example
* ```coffeescript
* kit.pad '1', 3 # '001'
* ```
###
pad: (str, width, char = '0') ->
str = str + ''
if str.length >= width
str
else
new Array(width - str.length + 1).join(char) + str
###*
* A comments parser for coffee-script. Used to generate documentation automatically.
* It will traverse through all the comments.
* @param {String} module_name The name of the module it belongs to.
* @param {String} code Coffee source code.
* @param {String} path The path of the source code.
* @param {Object} opts Parser options:
* ```coffeescript
* {
* comment_reg: RegExp
* split_reg: RegExp
* tag_name_reg: RegExp
* type_reg: RegExp
* name_reg: RegExp
* name_tags: ['param', 'property']
* description_reg: RegExp
* }
* ```
* @return {Array} The parsed comments. Each item is something like:
* ```coffeescript
* {
* module: 'nobone'
* name: 'parse_comment'
* description: 'A comments parser for coffee-script.'
* tags: [
* {
* tag_name: 'param'
* type: 'string'
* name: 'code'
* description: 'The name of the module it belongs to.'
* path: 'http://the_path_of_source_code'
* index: 256 # The target char index in the file.
* line: 32 # The line number of the target in the file.
* }
* ]
* }
* ```
###
parse_comment: (module_name, code, path = '', opts = {}) ->
_.defaults opts, {
comment_reg: /###\*([\s\S]+?)###\s+([\w\.]+)/g
split_reg: /^\s+\* @/m
tag_name_reg: /^([\w\.]+)\s*/
type_reg: /^\{(.+?)\}\s*/
name_reg: /^(\w+)\s*/
name_tags: ['param', 'property']
description_reg: /^([\s\S]*)/
}
parse_info = (block) ->
# Unescape '\/'
block = block.replace /\\\//g, '/'
# Clean the prefix '*'
arr = block.split(opts.split_reg).map (el) ->
el.replace(/^[ \t]+\*[ \t]?/mg, '').trim()
{
description: arr[0] or ''
tags: arr[1..].map (el) ->
parse_tag = (reg) ->
m = el.match reg
if m and m[1]
el = el[m[0].length..]
m[1]
else
null
tag = {}
tag.tag_name = parse_tag opts.tag_name_reg
type = parse_tag opts.type_reg
if type
tag.type = type
if tag.tag_name in opts.name_tags
tag.name = parse_tag opts.name_reg
tag.description = parse_tag(opts.description_reg) or ''
else
tag.description = parse_tag(opts.description_reg) or ''
tag
}
comments = []
m = null
while (m = opts.comment_reg.exec(code)) != null
info = parse_info m[1]
comments.push {
module: module_name
name: m[2]
description: info.description
tags: info.tags
path
index: opts.comment_reg.lastIndex
line: _.reduce(code[...opts.comment_reg.lastIndex]
, (count, char) ->
count++ if char == '\n'
count
, 1)
}
return comments
###*
* Node native module
###
path: require 'path'
###*
* Block terminal and wait for user inputs. Useful when you need
* in-terminal user interaction.
* @param {Object} opts See the https://github.com/flatiron/prompt
* @return {Promise} Contains the results of prompt.
###
prompt_get: (opts) ->
prompt = kit.require 'prompt', (prompt) ->
prompt.message = '>> '
prompt.delimiter = ''
new Promise (resolve, reject) ->
prompt.get opts, (err, res) ->
if err
reject err
else
resolve res
###*
* The promise lib.
* @type {Object}
###
Promise: Promise
###*
* Much much faster than the native require of node, but
* you should follow some rules to use it safely.
* @param {String} module_name Moudle path is not allowed!
* @param {Function} done Run only the first time after the module loaded.
* @return {Module} The module that you require.
###
require: (module_name, done) ->
if not kit.require_cache[module_name]
if module_name[0] == '.'
throw new Error('Only module name is allowed: ' + module_name)
kit.require_cache[module_name] = require module_name
done? kit.require_cache[module_name]
kit.require_cache[module_name]
###*
* A powerful extended combination of `http.request` and `https.request`.
* @param {Object} opts The same as the [http.request][http.request], but with
* some extra options:
* ```coffeescript
* {
* url: 'It is not optional, String or Url Object.'
* body: true # Other than return `res` with `res.body`, return `body` directly.
* redirect: 0 # Max times of auto redirect. If 0, no auto redirect.
*
* # Set null to use buffer, optional.
* # It supports GBK, Shift_JIS etc.
* # For more info, see https://github.com/ashtuchkin/iconv-lite
* res_encoding: 'auto'
*
* # It's string, object or buffer, optional. When it's an object,
* # The request will be 'application/x-www-form-urlencoded'.
* req_data: null
*
* auto_end_req: true # auto end the request.
* req_pipe: Readable Stream.
* res_pipe: Writable Stream.
* }
* ```
* And if set opts as string, it will be treated as the url.
* [http.request]: http://nodejs.org/api/http.html#http_http_request_options_callback
* @return {Promise} Contains the http response object,
* it has an extra `body` property.
* You can also get the request object by using `Promise.req`, for example:
* ```coffeescript
* p = kit.request 'http://test.com'
* p.req.on 'response', (res) ->
* kit.log res.headers['content-length']
* p.done (body) ->
* kit.log body # html or buffer
*
* kit.request {
* url: 'https://test.com'
* body: false
* }
* .done (res) ->
* kit.log res.body
* kit.log res.headers
* ```
###
request: (opts) ->
if _.isString opts
opts = { url: opts }
if _.isObject opts.url
opts.url.protocol ?= 'http:'
opts.url = kit.url.format opts.url
else
if opts.url.indexOf('http') != 0
opts.url = 'http://' + opts.url
url = kit.url.parse opts.url
url.protocol ?= 'http:'
request = null
switch url.protocol
when 'http:'
{ request } = kit.require 'http'
when 'https:'
{ request } = kit.require 'https'
else
Promise.reject new Error('Protocol not supported: ' + url.protocol)
_.defaults opts, url
_.defaults opts, {
body: true
res_encoding: 'auto'
req_data: null
auto_end_req: true
auto_unzip: true
}
opts.headers ?= {}
if Buffer.isBuffer(opts.req_data)
req_buf = opts.req_data
else if _.isString opts.req_data
req_buf = new Buffer(opts.req_data)
else if _.isObject opts.req_data
opts.headers['content-type'] ?= 'application/x-www-form-urlencoded; charset=utf-8'
req_buf = new Buffer(
_.map opts.req_data, (v, k) ->
[encodeURIComponent(k), encodeURIComponent(v)].join '='
.join '&'
)
else
req_buf = new Buffer(0)
if req_buf.length > 0
opts.headers['content-length'] ?= req_buf.length