-
Notifications
You must be signed in to change notification settings - Fork 38
/
runner.js
241 lines (206 loc) · 5.73 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
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
const http = require('http');
const https = require('https');
const { writeFileSync } = require('fs');
const { join } = require('path').posix;
const { resolve, extname } = require('path');
const colors = require('colors/safe');
const globby = require('globby');
const ora = require('ora');
const queue = require('async-promise-queue');
const tmp = require('tmp');
const workerpool = require('workerpool');
tmp.setGracefulCleanup();
class NoFilesError extends Error {}
const silentLogger = {
info() {},
warning() {},
error() {},
spin() {},
updateSpinner() {},
stopSpinner() {},
};
/* eslint-disable no-console */
const verboseLogger = {
info(message) {
console.log(message);
},
warning(message) {
console.log(`${colors.white.bgYellow(' WARN ')} ${message}`);
},
error(message) {
console.log(`${colors.white.bgRed(' ERR ')} ${message}`);
},
spin(message) {
this.spinner = ora(message).start();
},
updateSpinner(message) {
if (this.spinner) {
this.spinner.text = message;
}
},
stopSpinner(persistentMessage) {
if (persistentMessage) {
this.spinner && this.spinner.stopAndPersist(persistentMessage);
} else {
this.spinner && this.spinner.stop();
}
},
};
/* eslint-enable no-console */
class StatsCollector {
constructor(logger) {
this.logger = logger;
this.changed = 0;
this.unchanged = 0;
this.skipped = 0;
this.errors = [];
}
update(message) {
switch (message.type) {
case 'update':
switch (message.status) {
case 'ok':
this.changed++;
break;
case 'skipped':
this.skipped++;
break;
default:
this.unchanged++;
break;
}
break;
case 'error':
this.errors.push(message);
break;
}
}
print() {
this.logger.info(`Ok: ${this.changed}`);
this.logger.info(`Unchanged: ${this.unchanged}`);
if (this.skipped) {
this.logger.info(`Skipped: ${this.skipped}`);
}
if (this.errors.length) {
this.logger.info(`Errored: ${this.errors.length}`);
this.errors.slice(0, 5).forEach(({ file, error }) => {
this.logger.error(`${file}`);
handleError(error, this.logger);
});
if (this.errors.length > 5) {
const more = this.errors.length - 5;
this.logger.error(`And ${more} more error${more !== 1 ? 's' : ''}`);
}
}
}
}
module.exports = async function run(transformFile, filePaths, options) {
const logger = options.silent ? silentLogger : verboseLogger;
const stats = new StatsCollector(logger);
try {
const [transformPath, files] = await Promise.all([
loadTransform(transformFile),
getAllFiles(filePaths),
]);
await spawnWorkers(transformPath, files, options, stats, logger);
logger.stopSpinner({
symbol: '🎉',
text: 'Complete!',
});
stats.print();
} catch (err) {
logger.stopSpinner();
handleError(err, logger);
}
};
/**
* Returns the location of the transform module on disk.
* @param {string} transformFile
* @returns {Promise<string>}
*/
async function loadTransform(transformFile) {
const isRemote = transformFile.startsWith('http');
if (!isRemote) {
return resolve(process.cwd(), transformFile);
}
const contents = await downloadFile(transformFile);
const filePath = tmp.fileSync();
writeFileSync(filePath.name, contents, 'utf8');
return filePath.name;
}
/**
* @param {string} url
* @returns {Promise<string>}
*/
function downloadFile(url) {
return new Promise((resolve, reject) => {
const transport = url.startsWith('https') ? https : http;
let contents = '';
transport
.get(url, res =>
res.on('data', data => (contents += data.toString())).on('end', () => resolve(contents))
)
.on('error', err => reject(err));
});
}
/**
* Convert array of paths into an array of absolute file paths. Uses globby
* under the hood so it respects .gitignore files.
* @param {string[]} paths
* @returns {Promise<string[]>}
*/
async function getAllFiles(paths) {
const patterns = paths.map(path => {
const ext = extname(path);
if (ext === '') {
path = join(path, '**', '*.{hbs,handlebars}');
}
return path;
});
const files = await globby(patterns, { absolute: true, gitignore: true });
if (files.length < 1) {
throw new NoFilesError();
}
return files;
}
/**
* Divides files into chunks and distributes them across worker processes.
* @param {string} transformPath
* @param {string[]} files
* @param {number} options.cpus
* @param {boolean} options.dry
* @param {StatsCollector} stats
* @param {Logger} logger
* @returns {Promise<void>}
*/
async function spawnWorkers(transformPath, files, { cpus, dry }, stats, logger) {
const processCount = Math.min(files.length, cpus);
logger.info(`Processing ${files.length} file${files.length !== 1 ? 's' : ''}…`);
logger.info(`Spawning ${processCount} worker${processCount !== 1 ? 's' : ''}…`);
logger.spin('Processed 0 files');
const pool = workerpool.pool(require.resolve('./worker.js'), { maxWorkers: cpus });
let i = 0;
const worker = queue.async.asyncify(async file => {
const message = await pool.exec('run', [transformPath, file, { dry }]);
stats.update(message);
logger.updateSpinner(`Processed ${i++} files`);
});
try {
await queue(worker, files, cpus);
} finally {
pool.terminate();
}
}
function handleError(err, logger) {
if (err.code === 'MODULE_NOT_FOUND') {
logger.error('Transform plugin not found');
} else if (err instanceof NoFilesError) {
logger.error('No files matched');
} else {
logger.error(err);
if (err.stack) {
logger.error(err.stack);
}
}
return 1;
}