This repository has been archived by the owner on Dec 5, 2019. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 183
/
Runner.js
80 lines (69 loc) · 2.27 KB
/
Runner.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
import os from 'os';
import cacache from 'cacache';
import findCacheDir from 'find-cache-dir';
import workerFarm from 'worker-farm';
import serialize from 'serialize-javascript';
import minify from './minify';
let workerFile = require.resolve('./worker');
try {
// run test
workerFile = require.resolve('../../dist/uglify/worker');
} catch (e) { } // eslint-disable-line no-empty
export default class Runner {
constructor(options = {}) {
const { cache, parallel } = options;
this.cacheDir = cache === true ? findCacheDir({ name: 'uglifyjs-webpack-plugin' }) : cache;
this.maxConcurrentWorkers = parallel === true ? os.cpus().length - 1 : Math.min(Number(parallel) || 0, os.cpus().length - 1);
}
runTasks(tasks, callback) {
if (!tasks.length) {
callback(null, []);
return;
}
if (this.maxConcurrentWorkers > 1) {
const workerOptions = process.platform === 'win32' ? { maxConcurrentWorkers: this.maxConcurrentWorkers, maxConcurrentCallsPerWorker: 1 } : { maxConcurrentWorkers: this.maxConcurrentWorkers };
this.workers = workerFarm(workerOptions, workerFile);
this.boundWorkers = (options, cb) => this.workers(serialize(options), cb);
} else {
this.boundWorkers = (options, cb) => {
try {
cb(null, minify(options));
} catch (errors) {
cb(errors);
}
};
}
let toRun = tasks.length;
const results = [];
const step = (index, data) => {
toRun -= 1;
results[index] = data;
if (!toRun) {
callback(null, results);
}
};
tasks.forEach((task, index) => {
const enqueue = () => {
this.boundWorkers(task, (error, data) => {
const result = error ? { error } : data;
const done = () => step(index, result);
if (this.cacheDir && !result.error) {
cacache.put(this.cacheDir, serialize(task.cacheKeys), JSON.stringify(data)).then(done, done);
} else {
done();
}
});
};
if (this.cacheDir) {
cacache.get(this.cacheDir, serialize(task.cacheKeys)).then(({ data }) => step(index, JSON.parse(data)), enqueue);
} else {
enqueue();
}
});
}
exit() {
if (this.workers) {
workerFarm.end(this.workers);
}
}
}