forked from darkreader/darkreader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask.js
More file actions
93 lines (83 loc) · 2.02 KB
/
Copy pathtask.js
File metadata and controls
93 lines (83 loc) · 2.02 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
92
93
const {log} = require('./utils');
const watch = require('./watch');
/**
* @typedef TaskOptions
* @property {boolean} debug
* @property {boolean} watch
*/
class Task {
/**
* @param {string} name
* @param {(options: TaskOptions) => void | Promise<void>} run
*/
constructor(name, run) {
this.name = name;
this._run = run;
}
/**
* @param {string[] | (() => string[])} files
* @param {(changedFiles: string[], watcher: import('chokidar').FSWatcher) => void | Promise<void>} onChange
*/
addWatcher(files, onChange) {
this._watchFiles = files;
this._onChange = onChange;
return this;
}
/**
* @param {Promise<void>} promise
*/
async _measureTime(promise) {
const start = Date.now();
await promise;
const end = Date.now();
log(`${this.name} (${(end - start).toFixed(0)}ms)`);
}
/**
* @param {TaskOptions} options
*/
async run(options) {
await this._measureTime(
this._run(options)
);
}
watch() {
if (!this._watchFiles || !this._onChange) {
return;
}
const watcher = watch({
files: typeof this._watchFiles === 'function' ?
this._watchFiles() :
this._watchFiles,
onChange: async (files) => {
await this._measureTime(
this._onChange(files, watcher)
);
},
});
}
}
/**
* @param {string} name
* @param {(options: TaskOptions) => void | Promise<void>} run
*/
function createTask(name, run) {
return new Task(name, run);
}
/**
* @param {Task[]} tasks
* @param {TaskOptions} options
*/
async function runTasks(tasks, options) {
for (const task of tasks) {
try {
await task.run(options);
} catch (err) {
log.error(`${task.name} error\n${err.stack || err}`);
throw err;
}
}
}
module.exports = {
createTask,
runTasks,
};