@ohos/hpm-cli-notice
Version:
Combining the notice files in the project into 'Third Party Open Source Notice' file.
84 lines (76 loc) • 2.7 kB
JavaScript
const fs = require("fs");
const path = require('path');
const bundleJson = require("../bundle.json");
const NOTICE_NAME = 'Third Party Open Source Notice';
let hpmApi;
function generateNotice(cwd, api) {
hpmApi = api;
const noticeFiles = getNoticeFiles(cwd);
if (noticeFiles) {
const outputDir = hpmApi.getOutputDir(bundleJson.name);
writeToOutput(noticeFiles, path.join(outputDir, NOTICE_NAME), cwd);
hpmApi.shelljs.cp("-r", path.join(__dirname, "..", "ui"), outputDir);
}
}
function getNoticeFiles(cwd) {
var ohos_dir = path.join(cwd, 'ohos_bundles');
if (!fs.existsSync(ohos_dir)) {
hpmApi.i18n.log(`${bundleJson.name}.notFoundOhos`, { cwd });
return;
}
const dirs = fs.readdirSync(ohos_dir);
let files = [];
dirs.forEach((dir) => {
if (dir.startsWith('@')) {
const subdirs = fs
.readdirSync(path.join(ohos_dir, dir))
.map((subdir) => path.join(ohos_dir, dir, subdir));
files = files.concat(subdirs);
} else {
files.push(path.join(ohos_dir, dir));
}
});
const noticeFiles = [];
files.forEach((f) => {
const jsonPath = path.join(f, 'bundle.json');
let noticeFileName = "NOTICE";
if (fs.existsSync(jsonPath)) {
const manifestJson = JSON.parse(fs.readFileSync(jsonPath));
if (manifestJson.noticeFile) {
noticeFileName = manifestJson.noticeFile;
}
}
const filePath = path.join(f, noticeFileName);
if (fs.existsSync(filePath)) {
noticeFiles.push(filePath);
}
});
return noticeFiles;
}
function writeToOutput(noticeFiles, output, copyPath) {
hpmApi.i18n.log(`${bundleJson.name}.start`);
const noticeObject = {};
noticeFiles.forEach((nf) => {
const subNoticeArray = fs
.readFileSync(nf)
.toString()
.split('Software:');
subNoticeArray.forEach((notice, index) => {
if (index !== 0 && notice && notice.includes('\n')) {
const key = `Software: ${notice.substring(0, notice.indexOf('\n')).trim()}`;
const value = notice.substring(notice.indexOf('\n')).trim();
noticeObject[key] = value;
}
});
});
const prefix = fs.readFileSync(path.join(__dirname, "..", "asset", "notice-prefix"));
const noticeString = Object.keys(noticeObject).reduce((notice, key) => `${notice}\n\n${key}\n\n${noticeObject[key]}`, prefix || '');
const trimed = (noticeString && noticeString.trim && noticeString.trim()) || '';
fs.writeFileSync(output, trimed);
if (!fs.existsSync(copyPath)) {
fs.mkdirSync(copyPath, { recursive: true });
}
fs.writeFileSync(path.join(copyPath, NOTICE_NAME), trimed);
hpmApi.i18n.log(`${bundleJson.name}.success`);
}
module.exports = { generateNotice }