-
-
Notifications
You must be signed in to change notification settings - Fork 109
/
index.js
119 lines (92 loc) · 2.47 KB
/
index.js
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import pMap from 'p-map';
import Task from './lib/task.js';
import TaskWrapper from './lib/task-wrapper.js';
import {getRenderer} from './lib/renderer.js';
import ListrError from './lib/listr-error.js';
const runTask = (task, context, errors) => {
if (!task.isEnabled()) {
return Promise.resolve();
}
return new TaskWrapper(task, errors).run(context);
};
class Listr {
constructor(tasks, options) {
if (tasks && !Array.isArray(tasks) && typeof tasks === 'object') {
if (typeof tasks.title === 'string' && typeof tasks.task === 'function') {
throw new TypeError('Expected an array of tasks or an options object, got a task object');
}
options = tasks;
tasks = [];
}
if (tasks && !Array.isArray(tasks)) {
throw new TypeError('Expected an array of tasks');
}
this._options = {
showSubtasks: true,
concurrent: false,
renderer: 'default',
nonTTYRenderer: 'verbose',
...options,
};
this._tasks = [];
this.concurrency = 1;
if (this._options.concurrent === true) {
this.concurrency = Number.POSITIVE_INFINITY;
} else if (typeof this._options.concurrent === 'number') {
this.concurrency = this._options.concurrent;
}
this._RendererClass = getRenderer(this._options.renderer, this._options.nonTTYRenderer);
this.exitOnError = this._options.exitOnError;
this.add(tasks || []);
}
_checkAll(context) {
for (const task of this._tasks) {
task.check(context);
}
}
get tasks() {
return this._tasks;
}
setRenderer(value) {
this._RendererClass = getRenderer(value);
}
add(task) {
const tasks = Array.isArray(task) ? task : [task];
for (const task of tasks) {
this._tasks.push(new Task(this, task, this._options));
}
return this;
}
render() {
if (!this._renderer) {
this._renderer = new this._RendererClass(this._tasks, this._options);
}
return this._renderer.render();
}
run(context) {
this.render();
context = context || Object.create(null);
const errors = [];
this._checkAll(context);
const tasks = pMap(this._tasks, task => {
this._checkAll(context);
return runTask(task, context, errors);
}, {concurrency: this.concurrency});
return tasks
.then(() => {
if (errors.length > 0) {
const error = new ListrError('Something went wrong');
error.errors = errors;
throw error;
}
this._renderer.end();
return context;
})
.catch(error => {
error.context = context;
this._renderer.end(error);
throw error;
});
}
}
export default Listr;