-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfigure-package.js
710 lines (590 loc) · 20.5 KB
/
configure-package.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
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
/**
* configures a package created from the template.
*/
const { basename } = require('path');
const cp = require('child_process');
const fs = require('fs');
const https = require('https');
const readline = require('readline');
const util = require('util');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const question = util.promisify(rl.question).bind(rl);
const basePath = __dirname;
const packageInfo = {
name: '',
description: '',
vendor: {
github: '',
name: '',
},
author: {
email: '',
github: '',
name: '',
},
};
const runCommand = str => {
cp.execSync(str, { cwd: __dirname, encoding: 'utf-8', stdio: 'inherit' });
};
const gitCommand = command => {
return cp.execSync(`git ${command}`, { env: process.env, cwd: __dirname, encoding: 'utf-8', stdio: 'pipe' }) || '';
};
const installDependencies = () => {
cp.execSync('npm install', { cwd: __dirname, encoding: 'utf-8', stdio: 'inherit' });
};
const askQuestion = async (prompt, defaultValue = '') => {
let result = '';
try {
result = await question(`${prompt} ${defaultValue.length ? '(' + defaultValue + ') ' : ''}`);
} catch (err) {
result = false;
}
return new Promise(resolve => {
if (!result || result.trim().length === 0) {
result = defaultValue;
}
resolve(result);
});
};
async function getGithubApiEndpoint(endpoint) {
const url = `https://api.github.com/${endpoint}`.replace('//', '/');
const requestJson = async url => {
const options = {
headers: {
'User-Agent': 'permafrost-dev-template-configure/1.0',
Accept: 'application/json, */*',
},
};
return new Promise((resolve, reject) => {
const req = https.get(url, options);
req.on('response', async res => {
let body = '';
res.setEncoding('utf-8');
for await (const chunk of res) {
body += chunk;
}
resolve(JSON.parse(body));
});
req.on('error', err => {
throw new err();
reject(err);
});
});
};
const response = {
exists: true,
data: {},
};
try {
response.data = await requestJson(url);
response.exists = true;
} catch (e) {
response.exists = false;
response.data = {};
}
if (response.exists && response.data['message'] === 'Not Found') {
response.exists = false;
response.data = {};
}
return response;
}
function getGithubUsernameFromGitRemote() {
const remoteUrlParts = gitCommand('config remote.origin.url').trim().replace(':', '/').split('/');
return remoteUrlParts[1];
}
function searchCommitsForGithubUsername() {
const authorName = gitCommand(`config user.name`).trim().toLowerCase();
const committers = gitCommand(`log --author='@users.noreply.github.com' --pretty='%an:%ae' --reverse`)
.split('\n')
.map(line => line.trim())
.map(line => ({ name: line.split(':')[0], email: line.split(':')[1] }))
.filter(item => !item.name.includes('[bot]'))
.filter(item => item.name.toLowerCase().localeCompare(authorName.toLowerCase()) === 0);
if (!committers.length) {
return '';
}
return committers[0].email.split('@')[0];
}
function guessGithubUsername() {
const username = searchCommitsForGithubUsername();
if (username.length) {
return username;
}
return getGithubUsernameFromGitRemote();
}
function rescue(func, defaultValue = null) {
try {
return func();
} catch (e) {
return defaultValue;
}
}
function is_dir(path) {
try {
const stat = fs.lstatSync(path);
return stat.isDirectory();
} catch (e) {
// lstatSync throws an error if path doesn't exist
return false;
}
}
function is_file(path) {
return rescue(() => fs.lstatSync(path).isFile(), false);
}
const replaceVariablesInFile = (filename, packageInfo) => {
let content = fs.readFileSync(filename, { encoding: 'utf-8' }).toString();
const originalContent = content.slice();
content = content
.replace(/package-skeleton/g, packageInfo.name)
.replace(/\{\{vendor\.name\}\}/g, packageInfo.vendor.name)
.replace(/\{\{vendor\.github\}\}/g, packageInfo.vendor.github)
.replace(/\{\{package\.name\}\}/g, packageInfo.name)
.replace(/\{\{package\.description\}\}/g, packageInfo.description)
.replace(/\{\{package\.author\.name\}\}/g, packageInfo.author.name)
.replace(/\{\{package\.author\.email\}\}/g, packageInfo.author.email)
.replace(/\{\{package\.author\.github\}\}/g, packageInfo.author.github)
.replace(/\{\{date\.year\}\}/g, new Date().getFullYear())
.replace('Template Setup: run `node configure-package.js` to configure.\n', '');
if (originalContent != content) {
fs.writeFileSync(filename, content, { encoding: 'utf-8' });
}
};
const processFiles = (directory, packageInfo) => {
const files = fs.readdirSync(directory).filter(f => {
return ![
'.',
'..',
'.editorconfig',
'.eslintignore',
'.eslintrc.js',
'.git',
'.gitattributes',
'.gitignore',
'.prettierignore',
'.prettierrc',
'build-library.js',
'build.js',
'configure-package.js',
'node_modules',
'package-lock.json',
'prettier.config.js',
'yarn.lock',
].includes(basename(f));
});
files.forEach(fn => {
const fqName = `${directory}/${fn}`;
const relativeName = fqName.replace(basePath + '/', '');
const isPath = is_dir(fqName);
const kind = isPath ? 'directory' : 'file';
console.log(`processing ${kind} ./${relativeName}`);
if (isPath) {
processFiles(fqName, packageInfo);
return;
}
if (is_file(fqName)) {
try {
replaceVariablesInFile(fqName, packageInfo);
} catch (err) {
console.log(`error processing file ${relativeName}`);
}
}
});
};
const conditionalAsk = async (obj, propName, onlyEmpty, prompt, allowEmpty = false, alwaysAsk = true) => {
const value = obj[propName];
if (!onlyEmpty || !value.length || alwaysAsk) {
while (obj[propName].length === 0 || alwaysAsk) {
obj[propName] = await askQuestion(prompt, value);
if (allowEmpty && obj[propName].length === 0) {
break;
}
if (obj[propName].length > 0) {
break;
}
}
}
return new Promise(resolve => resolve());
};
const populatePackageInfo = async (onlyEmpty = false) => {
const remoteUrlParts = gitCommand('config remote.origin.url').trim().replace(':', '/').split('/');
console.log();
packageInfo.name = basename(__dirname);
packageInfo.author.name = gitCommand('config user.name').trim();
packageInfo.author.email = gitCommand('config user.email').trim();
packageInfo.vendor.name = packageInfo.author.name;
packageInfo.author.github = guessGithubUsername();
packageInfo.vendor.github = remoteUrlParts[1];
const orgResponse = await getGithubApiEndpoint(`orgs/${packageInfo.vendor.github}`);
if (orgResponse.exists) {
packageInfo.vendor.name = orgResponse.data.name;
}
await conditionalAsk(packageInfo, 'name', onlyEmpty, 'package name?', false);
await conditionalAsk(packageInfo, 'description', onlyEmpty, 'package description?');
await conditionalAsk(packageInfo.author, 'name', onlyEmpty, 'author name?');
await conditionalAsk(packageInfo.author, 'email', onlyEmpty, 'author email?');
await conditionalAsk(packageInfo.author, 'github', onlyEmpty, 'author github username?');
await conditionalAsk(packageInfo.vendor, 'name', onlyEmpty, 'vendor name (default is author name)?', true);
await conditionalAsk(packageInfo.vendor, 'github', onlyEmpty, 'vendor github org/user name (default is author github)?', true);
if (packageInfo.vendor.name.length === 0) {
packageInfo.vendor.name = packageInfo.author.name;
}
if (packageInfo.vendor.github.length === 0) {
packageInfo.vendor.github = packageInfo.author.github;
}
};
const safeUnlink = path => fs.existsSync(path) && fs.unlinkSync(path);
const getWorkflowFilename = name => `${__dirname}/.github/workflows/${name}.yml`;
const getGithubConfigFilename = name => `${__dirname}/.github/${name}.yml`;
const writeFormattedJson = (filename, data) => fs.writeFileSync(filename, JSON.stringify(data, null, 4), { encoding: 'utf-8' });
class PackageFile {
pkg = {};
constructor() {
this.pkg = {};
this.load();
}
load() {
this.pkg = require(`${__dirname}/package.json`);
return this;
}
save() {
writeFormattedJson(`${__dirname}/package.json`, this.pkg);
return this;
}
replaceScript(name, script) {
this.pkg.scripts[name] = script;
return this;
}
deleteScripts(...names) {
for (const name of names) {
if (typeof this.pkg.scripts[name] !== 'undefined') {
delete this.pkg.scripts[name];
}
}
return this;
}
delete(...keys) {
for (const key of keys) {
if (typeof this.pkg[key] !== 'undefined') {
delete this.pkg[key];
}
}
return this;
}
}
class Features {
codecov = {
name: 'codecov',
prompt: 'Use code coverage service codecov?',
enabled: true,
dependsOn: [],
disable: () => {
const testsWorkflowFn = getWorkflowFilename('run-tests');
const contents = fs.readFileSync(testsWorkflowFn, { encoding: 'utf-8' });
fs.writeFileSync(testsWorkflowFn, contents.replace('USE_CODECOV_SERVICE: yes', 'USE_CODECOV_SERVICE: no'), {
encoding: 'utf-8',
});
safeUnlink(getGithubConfigFilename('codecov'));
},
};
autoformat = {
name: 'autoformat',
prompt: 'Automatically lint & format code on push?',
enabled: true,
default: true,
dependsOn: [],
disable: () => {
safeUnlink(getWorkflowFilename('format-code'));
},
};
dependabot = {
name: 'dependabot',
prompt: 'Use Dependabot?',
enabled: true,
default: true,
dependsOn: [],
disable: () => {
safeUnlink(getGithubConfigFilename('dependabot'));
this.automerge.disable();
},
};
automerge = {
name: 'automerge',
prompt: 'Automerge Dependabot PRs?',
enabled: true,
default: true,
dependsOn: ['dependabot'],
disable: () => {
safeUnlink(getWorkflowFilename('dependabot-auto-merge'));
},
};
codeql = {
name: 'codeql',
prompt: 'Use CodeQL Quality Analysis?',
enabled: true,
default: true,
dependsOn: [],
disable: () => {
safeUnlink(getWorkflowFilename('codeql-analysis'));
},
};
updateChangelog = {
name: 'updateChangelog',
prompt: 'Use Changelog Updater Workflow?',
enabled: true,
dependsOn: [],
disable: () => {
safeUnlink(getWorkflowFilename('update-changelog'));
},
};
useMadgePackage = {
name: 'useMadgePackage',
prompt: 'Use madge package for code analysis?',
enabled: true,
dependsOn: [],
disable: () => {
runCommand('npm rm madge');
safeUnlink(`${__dirname}/.madgerc`);
const pkg = new PackageFile();
pkg.deleteScripts('analyze:deps:circular', 'analyze:deps:list', 'analyze:deps:graph').save();
},
};
useJestPackage = {
name: 'useJestPackage',
prompt: 'Use jest for js/ts unit testing?',
enabled: true,
default: true,
dependsOn: [],
disable: () => {
runCommand('npm rm jest @types/jest ts-jest');
safeUnlink(`${__dirname}/jest.config.js`);
const pkg = new PackageFile();
pkg.deleteScripts('test:coverage').replaceScript('test', 'echo "no tests defined" && exit 0').save();
// remove tsconfig jest types reference
let tsConfigContent = fs.readFileSync('${__dirname}/tsconfig.json').toString();
tsConfigContent = tsConfigContent.replace(/"jest",?\s*/, '');
fs.writeFileSync(`${__dirname}/tsconfig.json`, tsConfigContent, { encoding: 'utf-8' });
},
};
useEslintPackage = {
name: 'useEslintPackage',
prompt: 'Use ESLint for js/ts code linting?',
enabled: true,
default: true,
dependsOn: [],
disable: () => {
runCommand('npm rm eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser');
safeUnlink(`${__dirname}/.eslintrc.js`);
const pkg = new PackageFile();
pkg.deleteScripts('lint', 'lint:fix').replaceScript('fix', pkg.pkg.scripts['fix'].replace('&& npm run lint:fix', ''));
for (const key of Object.keys(pkg.pkg['lint-staged'])) {
pkg.pkg['lint-staged'][key] = pkg.pkg['lint-staged'].filter(cmd => !cmd.includes('eslint'));
}
pkg.save();
},
};
isPackageCommandLineApp = {
name: 'isPackageCommandLineApp',
prompt: 'Is this package a command line application?',
enabled: true,
default: false,
dependsOn: [],
disable: () => {
const pkg = new PackageFile();
pkg.delete('bin').save();
},
};
features = [
this.codecov,
this.autoformat,
this.dependabot,
this.automerge,
this.codeql,
this.updateChangelog,
this.useMadgePackage,
this.useJestPackage,
this.useEslintPackage,
this.isPackageCommandLineApp,
];
async run() {
const state = {};
for (let feature of this.features) {
if (feature.dependsOn.length > 0) {
const dependencies = feature.dependsOn.map(dep => state[dep]);
feature.enabled = dependencies.every(dep => dep);
}
if (feature.enabled) {
feature.enabled = await askBooleanQuestion(feature.prompt, feature.default);
}
state[feature.name] = feature.enabled;
if (!feature.enabled) {
feature.disable();
}
}
}
}
/**
* Removes the template README text from the README.md file
*/
function removeTemplateReadmeText() {
const END_BLOCK_STR = '<!-- ==END TEMPLATE README== -->';
const START_BLOCK_STR = '<!-- ==START TEMPLATE README== -->';
const content = fs.readFileSync(`${__dirname}/README.md`).toString();
if (content.includes(START_BLOCK_STR) && content.includes(END_BLOCK_STR)) {
const startBlockPos = content.indexOf(START_BLOCK_STR);
const endBlockPos = content.lastIndexOf(END_BLOCK_STR);
const newContent = content.replace(content.substring(startBlockPos, endBlockPos + END_BLOCK_STR.length), '');
if (newContent.length) {
fs.writeFileSync('./README.md', newContent);
}
}
}
function removeAssetsDirectory() {
try {
for (const fn of fs.readdirSync(`${__dirname}/assets`)) {
fs.unlinkSync(`${__dirname}/assets/${fn}`);
}
fs.rmdirSync(`${__dirname}/assets`);
} catch (e) {
//
}
}
class OptionalPackages {
config = {
prompt: 'Use a yaml config file?',
enabled: true,
default: false,
dependsOn: [],
name: 'conf',
add: () => {
cp.execSync('npm install conf js-yaml', { cwd: __dirname, stdio: 'inherit' });
if (!fs.existsSync(path.join(__dirname, 'dist'))) {
fs.mkdirSync(path.join(__dirname, 'dist', { recursive: true }));
}
fs.writeFileSync(`${__dirname}/dist/config.yaml`, '', { encoding: 'utf-8' });
fs.writeFileSync(
`${__dirname}/src/config.ts`,
`
import Conf from 'conf';
import yaml from 'js-yaml';
const ConfBaseConfig = {
cwd: __dirname,
deserialize: (text: string) => yaml.load(text),
serialize: value => yaml.dump(value, { indent: 2 }),
fileExtension: 'yml',
};
export function createConf(name: string, options: Record<string, any> = {}): Conf {
return new Conf(<any>{
configName: name,
...Object.assign({}, ConfBaseConfig, options),
});
}
`.trim(),
{ encoding: 'utf-8' },
);
},
};
dotenv = {
prompt: 'Use a .env file?',
enabled: true,
default: false,
dependsOn: [],
name: 'dotenv',
add: () => {
runCommand('npm', ['install', 'dotenv'], { cwd: __dirname, stdio: 'inherit' });
fs.mkdirSync(`${__dirname}/dist`, { recursive: true });
fs.writeFileSync(`${__dirname}/dist/.env`, 'TEST_VALUE=1\n', { encoding: 'utf-8' });
fs.writeFileSync(
`${__dirname}/src/init.ts`,
`
require('dotenv').config({ path: \`\${__dirname}/.env' })
`.trim(),
{ encoding: 'utf-8' },
);
},
};
otherPackages = {
prompt: 'Comma-separated list of packages to install:',
enabled: true,
default: '',
dependsOn: [],
name: 'otherPackages',
add: values => {
cp.execSync('npm install ' + values.join(' '), { cwd: __dirname, stdio: 'inherit' });
},
};
optionalPackages = [this.config, this.dotenv];
async run() {
for (let pkg of this.optionalPackages) {
const result = await askBooleanQuestion(pkg.prompt, pkg.default);
if (result) {
pkg.add();
}
}
const packageList = await askQuestion(this.otherPackages.prompt, this.otherPackages.default);
if (packageList.length > 0) {
this.otherPackages.add(packageList.split(',').map(pkg => pkg.trim()));
}
}
}
async function configureOptionalFeatures() {
await new Features().run();
}
const askBooleanQuestion = async str => {
let resultStr = await askQuestion(`${str} [Y/n] `);
resultStr = resultStr.toString().trim();
if (resultStr.length === 0) {
resultStr = 'yes';
}
const result = resultStr.toLowerCase().replace(/ /g, '').replace(/[^yn]/g, '').slice(0, 1);
return result === 'y';
};
const lintAndFormatSourceFiles = () => {
cp.execSync('node ./node_modules/.bin/prettier --write ./src', { cwd: __dirname, stdio: 'inherit' });
cp.execSync('node ./node_modules/.bin/eslint --fix ./src', { cwd: __dirname, stdio: 'inherit' });
};
const run = async function () {
await populatePackageInfo();
await configureOptionalFeatures();
const confirm = (await askQuestion('Process files (this will modify files) [y/N]? '))
.toString()
.toLowerCase()
.replace(/ /g, '')
.replace(/[^yn]/g, '')
.slice(0, 1);
if (confirm !== 'y') {
console.log('Not processing files: action canceled. Exiting.');
rl.close();
return;
}
try {
removeTemplateReadmeText();
removeAssetsDirectory();
} catch (e) {
console.log('Error removing template assets: ', e);
}
try {
processFiles(__dirname, packageInfo);
installDependencies();
await new OptionalPackages().run();
lintAndFormatSourceFiles();
} catch (err) {
console.log('Error: ', err);
}
rl.close();
try {
console.log('Done, removing this script.');
fs.unlinkSync(__filename);
} catch (e) {
console.log('Error removing script: ', e);
}
try {
runCommand('git add .');
runCommand('git commit -m"commit configured package files"');
} catch (e) {
console.log('Error committing files: ', e);
}
};
run();