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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
/**
* This script is for internal `react-boilerplate`'s usage.
* It will run all generators in order to be able to lint them and detect
* critical errors. Every generated component's name starts with 'RbGenerated'
* and any modified file is backed up by a file with the same name but with the
* 'rbgen' extension so it can be easily excluded from the test coverage reports.
*/
const chalk = require('chalk');
const fs = require('fs');
const nodePlop = require('node-plop');
const path = require('path');
const rimraf = require('rimraf');
const shell = require('shelljs');
const addCheckmark = require('./helpers/checkmark');
const xmark = require('./helpers/xmark');
/**
* Every generated component/container is preceded by this
* @type {string}
*/
const { BACKUPFILE_EXTENSION } = require('../generators/index');
process.chdir(path.join(__dirname, '../generators'));
const plop = nodePlop('./index.js');
const componentGen = plop.getGenerator('component');
const containerGen = plop.getGenerator('container');
const languageGen = plop.getGenerator('language');
/**
* Every generated component/container is preceded by this
* @type {string}
*/
const NAMESPACE = 'RbGenerated';
/**
* Return a prettified string
* @param {*} data
* @returns {string}
*/
function prettyStringify(data) {
return JSON.stringify(data, null, 2);
}
/**
* Handle results from Plop
* @param {array} changes
* @param {array} failures
* @returns {Promise<*>}
*/
function handleResult({ changes, failures }) {
return new Promise((resolve, reject) => {
if (Array.isArray(failures) && failures.length > 0) {
reject(new Error(prettyStringify(failures)));
}
resolve(changes);
});
}
/**
* Feedback to user
* @param {string} info
* @returns {Function}
*/
function feedbackToUser(info) {
return result => {
console.info(chalk.blue(info));
return result;
};
}
/**
* Report success
* @param {string} message
* @returns {Function}
*/
function reportSuccess(message) {
return result => {
addCheckmark(() => console.log(chalk.green(` ${message}`)));
return result;
};
}
/**
* Report errors
* @param {string} reason
* @returns {Function}
*/
function reportErrors(reason) {
// TODO Replace with our own helpers/log that is guaranteed to be blocking?
xmark(() => console.error(chalk.red(` ${reason}`)));
process.exit(1);
}
/**
* Run eslint on all js files in the given directory
* @param {string} relativePath
* @returns {Promise<string>}
*/
function runLintingOnDirectory(relativePath) {
return new Promise((resolve, reject) => {
shell.exec(
`npm run lint:eslint "app/${relativePath}/**/**.js"`,
{
silent: true,
},
code =>
code
? reject(new Error(`Linting error(s) in ${relativePath}`))
: resolve(relativePath),
);
});
}
/**
* Run eslint on the given file
* @param {string} filePath
* @returns {Promise<string>}
*/
function runLintingOnFile(filePath) {
return new Promise((resolve, reject) => {
shell.exec(
`npm run lint:eslint "${filePath}"`,
{
silent: true,
},
code => {
if (code) {
reject(new Error(`Linting errors in ${filePath}`));
} else {
resolve(filePath);
}
},
);
});
}
/**
* Remove a directory
* @param {string} relativePath
* @returns {Promise<any>}
*/
function removeDir(relativePath) {
return new Promise((resolve, reject) => {
try {
rimraf(path.join(__dirname, '/../../src/', relativePath), err => {
if (err) throw err;
});
resolve(relativePath);
} catch (err) {
reject(err);
}
});
}
/**
* Remove a given file
* @param {string} filePath
* @returns {Promise<any>}
*/
function removeFile(filePath) {
return new Promise((resolve, reject) => {
try {
fs.unlink(filePath, err => {
if (err) throw err;
});
resolve(filePath);
} catch (err) {
reject(err);
}
});
}
/**
* Overwrite file from copy
* @param {string} filePath
* @param {string} [backupFileExtension=BACKUPFILE_EXTENSION]
* @returns {Promise<*>}
*/
async function restoreModifiedFile(
filePath,
backupFileExtension = BACKUPFILE_EXTENSION,
) {
return new Promise((resolve, reject) => {
const targetFile = filePath.replace(`.${backupFileExtension}`, '');
try {
fs.copyFile(filePath, targetFile, err => {
if (err) throw err;
});
resolve(targetFile);
} catch (err) {
reject(err);
}
});
}
/**
* Test the component generator and rollback when successful
* @param {string} name - Component name
* @param {string} type - Plop Action type
* @returns {Promise<string>} - Relative path to the generated component
*/
async function generateComponent({ name, memo }) {
const targetFolder = 'components';
const componentName = `${NAMESPACE}Component${name}`;
const relativePath = `${targetFolder}/${componentName}`;
const component = `component/${memo ? 'Pure' : 'NotPure'}`;
await componentGen
.runActions({
name: componentName,
memo,
wantMessages: true,
wantLoadable: true,
})
.then(handleResult)
.then(feedbackToUser(`Generated '${component}'`))
.catch(reason => reportErrors(reason));
await runLintingOnDirectory(relativePath)
.then(reportSuccess(`Linting test passed for '${component}'`))
.catch(reason => reportErrors(reason));
await removeDir(relativePath)
.then(feedbackToUser(`Cleanup '${component}'`))
.catch(reason => reportErrors(reason));
return component;
}
/**
* Test the container generator and rollback when successful
* @param {string} name - Container name
* @param {string} type - Plop Action type
* @returns {Promise<string>} - Relative path to the generated container
*/
async function generateContainer({ name, memo }) {
const targetFolder = 'containers';
const componentName = `${NAMESPACE}Container${name}`;
const relativePath = `${targetFolder}/${componentName}`;
const container = `container/${memo ? 'Pure' : 'NotPure'}`;
await containerGen
.runActions({
name: componentName,
memo,
wantHeaders: true,
wantActionsAndReducer: true,
wantSagas: true,
wantMessages: true,
wantLoadable: true,
})
.then(handleResult)
.then(feedbackToUser(`Generated '${container}'`))
.catch(reason => reportErrors(reason));
await runLintingOnDirectory(relativePath)
.then(reportSuccess(`Linting test passed for '${container}'`))
.catch(reason => reportErrors(reason));
await removeDir(relativePath)
.then(feedbackToUser(`Cleanup '${container}'`))
.catch(reason => reportErrors(reason));
return container;
}
/**
* Generate components
* @param {array} components
* @returns {Promise<[string]>}
*/
async function generateComponents(components) {
const promises = components.map(async component => {
let result;
if (component.kind === 'component') {
result = await generateComponent(component);
} else if (component.kind === 'container') {
result = await generateContainer(component);
}
return result;
});
const results = await Promise.all(promises);
return results;
}
/**
* Test the language generator and rollback when successful
* @param {string} language
* @returns {Promise<*>}
*/
async function generateLanguage(language) {
// Run generator
const generatedFiles = await languageGen
.runActions({ language, test: true })
.then(handleResult)
.then(feedbackToUser(`Added new language: '${language}'`))
.then(changes =>
changes.reduce((acc, change) => {
const pathWithRemovedAnsiEscapeCodes = change.path.replace(
/* eslint-disable-next-line no-control-regex */
/(\u001b\[3(?:4|9)m)/g,
'',
);
const obj = {};
obj[pathWithRemovedAnsiEscapeCodes] = change.type;
return Object.assign(acc, obj);
}, {}),
)
.catch(reason => reportErrors(reason));
// Run eslint on modified and added JS files
const lintingTasks = Object.keys(generatedFiles)
.filter(
filePath =>
generatedFiles[filePath] === 'modify' ||
generatedFiles[filePath] === 'add',
)
.filter(filePath => filePath.endsWith('.js'))
.map(async filePath => {
const result = await runLintingOnFile(filePath)
.then(reportSuccess(`Linting test passed for '${filePath}'`))
.catch(reason => reportErrors(reason));
return result;
});
await Promise.all(lintingTasks);
// Restore modified files
const restoreTasks = Object.keys(generatedFiles)
.filter(filePath => generatedFiles[filePath] === 'backup')
.map(async filePath => {
const result = await restoreModifiedFile(filePath)
.then(
feedbackToUser(
`Restored file: '${filePath.replace(
`.${BACKUPFILE_EXTENSION}`,
'',
)}'`,
),
)
.catch(reason => reportErrors(reason));
return result;
});
await Promise.all(restoreTasks);
// Remove backup files and added files
const removalTasks = Object.keys(generatedFiles)
.filter(
filePath =>
generatedFiles[filePath] === 'backup' ||
generatedFiles[filePath] === 'add',
)
.map(async filePath => {
const result = await removeFile(filePath)
.then(feedbackToUser(`Removed '${filePath}'`))
.catch(reason => reportErrors(reason));
return result;
});
await Promise.all(removalTasks);
return language;
}
/**
* Run
*/
(async function () {
await generateComponents([
{ kind: 'component', name: 'Component', memo: false },
{ kind: 'component', name: 'MemoizedComponent', memo: true },
{ kind: 'container', name: 'Container', memo: false },
{ kind: 'container', name: 'MemoizedContainer', memo: true },
]).catch(reason => reportErrors(reason));
await generateLanguage('fr').catch(reason => reportErrors(reason));
})();