1 |
|
2 |
|
3 | const path = require('path');
|
4 | const fs = require('fs');
|
5 | const debug = require('debug')('embelish:license');
|
6 | const formatter = require('formatter');
|
7 | const { ContentGenerator } = require('./content');
|
8 | const { Package } = require('./package');
|
9 | const { isFilePresent, readFileContent } = require('./file-tools');
|
10 |
|
11 | const REGEX_LICENSE = /^licen(c|s)e$/i;
|
12 |
|
13 | async function insertLicense(ast, packageData /*: Package */, basePath /*: string */) {
|
14 | const licenseHeaderIndex = ast.findIndex((item) => {
|
15 | return item.type === 'heading' && REGEX_LICENSE.test(item.raw);
|
16 | });
|
17 |
|
18 | const licenseContent = await generateLicense(packageData, basePath);
|
19 | if (licenseContent) {
|
20 | debug(`license header index = ${licenseHeaderIndex}`);
|
21 | if (licenseHeaderIndex >= 0) {
|
22 | ast.splice(licenseHeaderIndex + 1, ast.length, ContentGenerator.paragraph(licenseContent));
|
23 | }
|
24 |
|
25 |
|
26 | await updateLicenseFile(basePath, licenseContent);
|
27 | }
|
28 | }
|
29 |
|
30 | async function generateLicense(packageData /*: Package */, basePath /*: string */) {
|
31 | if (packageData.license && packageData.author) {
|
32 | const licenseName = packageData.license.toLowerCase();
|
33 | const licenseTemplateFile = path.resolve(__dirname, '..', 'licenses', `${licenseName}.txt`);
|
34 | const haveLicenseTemplate = await isFilePresent(licenseTemplateFile);
|
35 | if (!haveLicenseTemplate) {
|
36 | throw new Error(`License template for ${packageData.license} not found. Consider submitting an embellish-readme PR`);
|
37 | }
|
38 |
|
39 | const templateContent = haveLicenseTemplate ? await readFileContent(licenseTemplateFile) : '';
|
40 | const template = formatter(templateContent);
|
41 |
|
42 | return template({
|
43 | year: new Date().getFullYear(),
|
44 | holder: packageData.author
|
45 | });
|
46 | }
|
47 | }
|
48 |
|
49 | function updateLicenseFile(basePath /*: string */, content /*: string */) /*: Promise<void> */ {
|
50 | return new Promise((resolve, reject) => {
|
51 | fs.writeFile(path.resolve(basePath, 'LICENSE'), content, 'utf-8', (err) => {
|
52 | if (err) {
|
53 | return reject(err);
|
54 | }
|
55 |
|
56 | resolve();
|
57 | });
|
58 | });
|
59 | }
|
60 |
|
61 | module.exports = {
|
62 | insertLicense
|
63 | };
|