-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathtasks.js
More file actions
91 lines (85 loc) · 1.65 KB
/
Copy pathtasks.js
File metadata and controls
91 lines (85 loc) · 1.65 KB
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
/**
* @typedef {() => void | Promise<void>} Task
*/
/**
* @param {string} name
* @param {Task} task
* @returns {Task}
*/
function wrapTask (name, task) {
return async function $ () {
console.log(`[Starting: ${name}]`);
const start = Date.now();
await task();
const duration = (Date.now() - start) / 1000;
console.log(`[Done: ${name} (${duration.toFixed(2)}s)]`);
};
}
/**
* @param {Task} task
* @returns {Task}
*/
function wrapUnnamedTask (task) {
const name = task.name;
if (!name.startsWith('$')) {
task = wrapTask(name, task);
}
return task;
}
/**
* @param {...Task} tasks
* @returns {Task}
*/
export function series (...tasks) {
return async function $ () {
for (const task of tasks.map(wrapUnnamedTask)) {
await task();
}
};
}
/**
* @param {...Task} tasks
* @returns {Task}
*/
export function parallel (...tasks) {
return async function $ () {
await Promise.all(
tasks.map(async task => {
await wrapUnnamedTask(task)();
})
);
};
}
/**
* Given a record of tasks, it will run the task as dictated by the CLI arguments.
*
* To run a specific task, run `node path/to/script.js taskName`.
*
* @param {object} tasks
*/
export function run (tasks) {
const selected = String(process.argv[2]);
/** @type {Task | undefined} */
const task = tasks[selected];
if (!task) {
console.error(
`No such task ${selected}. Available tasks: ${Object.keys(tasks).join(', ')}`
);
}
else {
runTask(task);
}
}
/**
* Runs the given task.
*
* @param {Task} tasks
*/
export function runTask (tasks) {
Promise.resolve()
.then(() => tasks())
.catch(reason => {
console.error('Error:');
console.error(reason);
});
}