UNPKG

1.91 kBJavaScriptView Raw
1/**
2 * Run tasks.
3 * @memberof ape-tasking/lib
4 * @function runTasks
5 * @param {string} [name='task'] - Name of task.
6 * @param {function[]} actions - Tasks functions.
7 * @param {boolean} [exit=false] - Exit process when done.
8 * @returns {Promise}
9 */
10
11'use strict'
12
13const argx = require('argx')
14const os = require('os')
15const co = require('co')
16const stringcase = require('stringcase')
17const colorprint = require('colorprint')
18
19/** @lends runTasks */
20function 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
67Object.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
78module.exports = runTasks