1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | 'use strict'
|
12 |
|
13 | const argx = require('argx')
|
14 | const os = require('os')
|
15 | const co = require('co')
|
16 | const stringcase = require('stringcase')
|
17 | const colorprint = require('colorprint')
|
18 |
|
19 |
|
20 | function runTasks (name, actions, exit) {
|
21 | let args = argx(arguments)
|
22 | name = args.shift('string') || 'task'
|
23 | actions = [].concat(args.shift('array|function') || [])
|
24 | exit = args.pop('boolean') || false
|
25 |
|
26 | let startAt = new Date()
|
27 | colorprint.notice('%s started...', stringcase.capitalcase(name))
|
28 |
|
29 | process.on('uncaughtException', (e) => {
|
30 | if (!runTasks.uncaughtException) {
|
31 | console.error(e)
|
32 | }
|
33 | runTasks.uncaughtException = e
|
34 | })
|
35 |
|
36 | function run () {
|
37 | return co(function * () {
|
38 | for (let action of actions) {
|
39 | yield new Promise((resolve, reject) => {
|
40 | let callback = (err) => err ? reject(err) : resolve()
|
41 | let promise = action(callback)
|
42 | if (promise) {
|
43 | promise.then(resolve, reject)
|
44 | }
|
45 | })
|
46 | }
|
47 | let took = new Date() - startAt
|
48 | colorprint.notice('...%s done!(%dms)' + os.EOL, name, took)
|
49 | if (exit) {
|
50 | runTasks.exit(0)
|
51 | }
|
52 | }).catch((err) => {
|
53 | colorprint.fatal('...%s failed.', name)
|
54 | colorprint.error(err.stack || err.msg || String(err))
|
55 | if (exit) {
|
56 | runTasks.exit(1)
|
57 | }
|
58 | return Promise.reject(err)
|
59 | })
|
60 | }
|
61 |
|
62 | let runner = { name, run }
|
63 | runTasks.rerun = run
|
64 | return run().then(() => runner)
|
65 | }
|
66 |
|
67 | Object.assign(runTasks, {
|
68 | rerun () {
|
69 | console.log('nothing to run')
|
70 | },
|
71 | exit (code) {
|
72 | process.nextTick(() => {
|
73 | process.exit(code)
|
74 | })
|
75 | }
|
76 | })
|
77 |
|
78 | module.exports = runTasks
|