UNPKG

1.86 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 { capitalcase } = require('stringcase')
16const colorprint = require('colorprint')
17
18/** @lends runTasks */
19async 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
65Object.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
76module.exports = runTasks