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