UNPKG

2.1 kBJavaScriptView Raw
1// @flow
2
3const path = require('path');
4const fs = require('fs');
5const debug = require('debug')('embelish:license');
6const formatter = require('formatter');
7const { ContentGenerator } = require('./content');
8const { Package } = require('./package');
9const { isFilePresent, readFileContent } = require('./file-tools');
10
11const REGEX_LICENSE = /^licen(c|s)e$/i;
12
13async 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 // update the license file
26 await updateLicenseFile(basePath, licenseContent);
27 }
28}
29
30async 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
49function 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
61module.exports = {
62 insertLicense
63};