From 8971c09c2bb2af2ec4067754b0fba5a6a4ed8307 Mon Sep 17 00:00:00 2001 From: zemse Date: Wed, 23 Sep 2020 03:59:00 +0530 Subject: [PATCH] Squash duplicate SPDX-License-Identifier lines This commit combines the licenses in multiple SPDX declarations as also reported in nomiclabs/truffle-flattener#55. --- index.js | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/index.js b/index.js index f088f52..ba9e4bc 100755 --- a/index.js +++ b/index.js @@ -234,13 +234,38 @@ async function main(args) { return; } - await flatten(filePaths, outputChunk => { - if (outputFilePath) { - fs.appendFileSync(outputFilePath, outputChunk); - } else { - process.stdout.write(outputChunk); - } + let outputFileContent = ''; + + await flatten(filePaths, (outputChunk) => { + outputFileContent += outputChunk; }); + + // fix duplicate SPDX license identifiers + const outputLinesArray = outputFileContent.split('\n'); + const licenses = []; // string[] + const regex = /SPDX-License-Identifier/; + for (const [index, line] of outputLinesArray.entries()) { + if (regex.test(line)) { + const words = line.split(':'); + const wordIndex = words.findIndex((word) => regex.test(word)); // Actual license idenfifier after this + + const licenseIdentifier = words[wordIndex + 1].replace(/ /g, ''); + licenses.push(licenseIdentifier); + outputLinesArray.splice(index, 1); + } + } + outputLinesArray.unshift( + '// SPDX-License-Identifier: ' + [...new Set(licenses)].join(' AND ') + ); + + outputFileContent = outputLinesArray.join('\n'); + + if (outputFilePath) { + fs.writeFileSync(outputFilePath, outputFileContent); + } else { + process.stdout.write(outputChunk); + } + } if (require.main === module) {