Press n or j to go to the next uncovered block, b, p or k for the previous block.
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 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 | 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 13586x 13586x 13586x 13586x 13586x 13586x 13586x 13586x 13586x 455x 13131x 2x 13131x 110588x 13131x 13131x 13131x 13007x 13131x 13131x 13131x 11343x 11343x 10906x 11343x 8551x 11343x 13131x 13131x 13021x 13131x 13131x 13131x 12993x 137x 137x 137x 137x 138x 108x 13131x 137x 137x 13131x 3x 13131x 25551x 25551x 25551x 30x 30x 25551x 12988x 2x 2x 2x 2x 1x 1x 1x 12987x 12489x 12987x 1497x 1497x 1493x 1497x 1497x 1497x 2x 2x 1x 1x 2x 12987x 1993x 1x 1992x 497x 1992x 1992x 1756x 1992x 8x 13130x 13130x 13130x 13023x 31901x 31901x 31901x 18362x 13539x 13130x 108x 13130x 14x 47x 47x 3x 47x 47x 2x 47x 47x 47x 3x 3x 47x 5x 5x 47x 47x 5x 47x 8x 34x 34x 34x 47x 47x 1x 47x 46x 46x 46x 46x 6x 46x 2x 46x 46x 5x 46x 46x 1x 1x 499x 499x 1x 1x 46x 2x 2x 998x 1996x 996x 2x 46x 2x 2x 996x 1992x 2x 46x 10568x 10568x 10568x 10566x 46x 10568x 1499x 499x 499x 46x 10566x 1497x 1497x 13473x 1417x 1497x 495x 495x 46x 2513x 1004x 2008x 46x 505x 505x 505x 505x 505x 505x 505x 3x 505x 505x 441x 505x 46x 13022x 2x 13022x 3x 13022x 13022x 499x 13022x 499x 3x 12523x 46x 46x 1x 46x 39x 7x 5x 503x 503x 503x 503x 503x 63x 7x 2x 2x 2x 2x 2x 2x 1x 46x 46x 1x 46x 46x 2x 46x 46x 2x 46x 1x 46x 44x 14x 2x 2x 1x 1x 2x 2x 14x 1x 14x 14x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14x 5x 5x 5x 14x 3x 3x 1x 499x 499x 1497x 2x 500x 500x 3x 14x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14x 14x 1x 13x 13x 12x 2x 14x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x | /* Copyright (c) 2013, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://yuilibrary.com/license/ */ const LICENSE_TITLE_UNKNOWN = 'UNKNOWN'; const LICENSE_TITLE_UNLICENSED = 'UNLICENSED'; const INITIAL_MODULE_INFO = { licenses: LICENSE_TITLE_UNKNOWN, }; const chalk = require('chalk'); const debug = require('debug'); const fs = require('node:fs'); const mkdirp = require('mkdirp'); const path = require('node:path'); const readInstalledPackages = require('read-installed-packages'); const spdxCorrect = require('spdx-correct'); const spdxSatisfies = require('spdx-satisfies'); const treeify = require('treeify'); const createHash = require('crypto').createHash; const getLicenseTitle = require('./getLicenseTitle'); const licenseFiles = require('./license-files'); const helpers = require('./indexHelpers'); // Set up debug logging // https://www.npmjs.com/package/debug#stderr-vs-stdout const debugError = debug('license-checker-rseidelsohn:error'); const debugLog = debug('license-checker-rseidelsohn:log'); debugLog.log = console.log.bind(console); // This function calls itself recursively. On the first iteration, it collects the data of the main program, during the // second iteration, it collects the data from all direct dependencies, then it collects their dependencies and so on. const recursivelyCollectAllDependencies = (options) => { const { color: colorize, deps: currentExtendedPackageJson, unknown } = options; const moduleInfo = { ...INITIAL_MODULE_INFO }; const currentPackageNameAndVersion = `${currentExtendedPackageJson.name}@${currentExtendedPackageJson.version}`; let { data } = options; let licenseFilesInCurrentModuleDirectory = []; let licenseData; let licenseFile; let noticeFiles = []; let clarification = options.clarifications?.[currentPackageNameAndVersion]; let passedClarificationCheck = clarification?.checksum ? false : true; if ( // If we have processed this currentPackageNameAndVersion already, just return the data object. // This was added so that we don't recurse forever if there was a circular // dependency in the dependency tree. data[currentPackageNameAndVersion] || (options.production && currentExtendedPackageJson.extraneous) || (options.development && !currentExtendedPackageJson.extraneous && !currentExtendedPackageJson.root) ) { return data; } if (currentExtendedPackageJson.private) { moduleInfo.private = true; } data[currentPackageNameAndVersion] = moduleInfo; // Include property in output unless custom format has set property explicitly to false: const mustInclude = (propertyName = '') => options?.customFormat?.[propertyName] !== false; Eif (mustInclude('repository')) { const repositoryUrl = helpers.getRepositoryUrl({ clarificationRepository: clarification?.repository, jsonRepository: currentExtendedPackageJson?.repository, }); if (repositoryUrl) { moduleInfo.repository = repositoryUrl; } } Eif (mustInclude('url')) { // TODO: Figure out where the check for currentExtendedPackageJson.url.web comes from. It's in the original license-checker, // but I can't find any documentation on it. let url = helpers.getFirstNotUndefinedOrUndefined(clarification?.url, currentExtendedPackageJson?.url?.web); /*istanbul ignore next*/ if (url) { moduleInfo.url = url; } } if (typeof currentExtendedPackageJson.author === 'object') { const { publisher, email, url } = helpers.getAuthorDetails({ clarification, author: currentExtendedPackageJson?.author, }); if (mustInclude('publisher') && publisher) { moduleInfo.publisher = publisher; } if (mustInclude('email') && email) { moduleInfo.email = email; } // moduleInfo.url can for some reason already be set to currentExtendedPackageJson.url.web further up in the code, // so we only set it if it's not already set. Iif (typeof moduleInfo.url !== 'undefined' && mustInclude('url') && url) { moduleInfo.url = url; } } /*istanbul ignore next*/ if (unknown) { moduleInfo.dependencyPath = currentExtendedPackageJson.path; } const modulePath = helpers.getFirstNotUndefinedOrUndefined(clarification?.path, currentExtendedPackageJson?.path); if (mustInclude('path') && typeof modulePath === 'string') { moduleInfo.path = modulePath; } // Eventually store the contents of the module's README.md in currentExtendedPackageJson.readme: helpers.storeReadmeInJsonIfExists(modulePath, currentExtendedPackageJson); // console.log('licenseData: %s', licenseData); // Try to get the license information from the clarification file or from the package.json file: licenseData = helpers.getFirstNotUndefinedOrUndefined( clarification?.licenses, currentExtendedPackageJson.license, currentExtendedPackageJson.licenses, ); if (licenseData) { // License information has been collected from either the clarifiation file or from the package.json file /*istanbul ignore else*/ if (Array.isArray(licenseData) && licenseData.length > 0) { moduleInfo.licenses = licenseData.map((moduleLicense) => { const moduleLicenseTypeOrName = helpers.getFirstNotUndefinedOrUndefined( moduleLicense.type, moduleLicense.name, ); Eif (typeof moduleLicenseTypeOrName === 'string') { return moduleLicenseTypeOrName; } if (typeof moduleLicense === 'string') { return moduleLicense; } }); } else if (typeof helpers.getFirstNotUndefinedOrUndefined(licenseData.type, licenseData.name) === 'string') { moduleInfo.licenses = getLicenseTitle( helpers.getFirstNotUndefinedOrUndefined(licenseData.type, licenseData.name), ); } else if (typeof licenseData === 'string') { moduleInfo.licenses = getLicenseTitle(licenseData); } } else if (getLicenseTitle(currentExtendedPackageJson.readme)) { // Try to get the license information from the README file if neither the clarification file nor the package.json // file contained any license information: moduleInfo.licenses = getLicenseTitle(currentExtendedPackageJson.readme); } if (Array.isArray(moduleInfo.licenses)) { /*istanbul ignore else*/ if (moduleInfo.licenses.length === 1) { moduleInfo.licenses = moduleInfo.licenses[0]; } } /*istanbul ignore else*/ if (clarification?.licenseFile) { licenseFilesInCurrentModuleDirectory = [clarification.licenseFile]; } else if (fs.existsSync(modulePath)) { const filesInModuleDirectory = fs.readdirSync(modulePath); licenseFilesInCurrentModuleDirectory = licenseFiles(filesInModuleDirectory); noticeFiles = filesInModuleDirectory.filter((filename) => { filename = filename.toUpperCase(); const name = path.basename(filename).replace(path.extname(filename), ''); return name === 'NOTICE'; }); } // console.log('licenseFilesInCurrentModuleDirectory before: %s', licenseFilesInCurrentModuleDirectory); licenseFilesInCurrentModuleDirectory.forEach(function findBetterLicenseData(filename, index) { licenseFile = path.join(modulePath, filename); // Checking that the file is in fact a normal file and not a directory for example. /*istanbul ignore else*/ if (fs.lstatSync(licenseFile).isFile()) { let currentLicenceFilesContent; if ( !moduleInfo.licenses || moduleInfo.licenses.indexOf(LICENSE_TITLE_UNKNOWN) > -1 // TODO: Should we override a custom license? // || moduleInfo.licenses.indexOf('Custom:') === 0 ) { //Only re-check the license if we didn't get it from elsewhere currentLicenceFilesContent = fs.readFileSync(licenseFile, { encoding: 'utf8' }); moduleInfo.licenses = getLicenseTitle(currentLicenceFilesContent); } if (index === 0) { // Treat the file with the highest precedence as licenseFile if (clarification !== undefined && !passedClarificationCheck) { /*istanbul ignore else*/ if (!currentLicenceFilesContent) { currentLicenceFilesContent = fs.readFileSync(licenseFile, { encoding: 'utf8' }); } let sha256 = createHash('sha256').update(currentLicenceFilesContent).digest('hex'); if (clarification.checksum !== sha256) { console.error( `Clarification checksum mismatch for ${currentPackageNameAndVersion} :(\nFile checked: ${licenseFile}`, ); process.exit(1); } else { passedClarificationCheck = true; } } /*istanbul ignore else*/ if (mustInclude('licenseFile')) { moduleInfo.licenseFile = helpers.getFirstNotUndefinedOrUndefined( clarification?.licenseFile, options.basePath ? path.relative(options.basePath, licenseFile) : licenseFile, ); } if (mustInclude('licenseText') && options.customFormat) { Iif (clarification?.licenseText) { moduleInfo.licenseText = clarification.licenseText; } else { if (!currentLicenceFilesContent) { currentLicenceFilesContent = fs.readFileSync(licenseFile, { encoding: 'utf8' }); } /*istanbul ignore else*/ if (options._args && !options._args.csv) { moduleInfo.licenseText = currentLicenceFilesContent.trim(); } else { moduleInfo.licenseText = currentLicenceFilesContent .replace(/"/g, "'") .replace(/\r?\n|\r/g, ' ') .trim(); } } if (clarification?.licenseStart) { let startIndex = moduleInfo.licenseText.indexOf(clarification.licenseStart); let endIndex; if (clarification?.licenseEnd) { endIndex = moduleInfo.licenseText.indexOf(clarification.licenseEnd, startIndex); } else { endIndex = moduleInfo.licenseText.length; } moduleInfo.licenseText = moduleInfo.licenseText.substring(startIndex, endIndex); } } if (mustInclude('copyright') && options.customFormat) { if (clarification?.copyright) { moduleInfo.copyright = clarification.copyright; } else { if (!currentLicenceFilesContent) { currentLicenceFilesContent = fs.readFileSync(licenseFile, { encoding: 'utf8' }); } const linesWithCopyright = helpers.getLinesWithCopyright(currentLicenceFilesContent); if (linesWithCopyright.length > 0) { moduleInfo.copyright = linesWithCopyright[0].replace(/\n/g, '. ').trim(); } // Mark files with multiple copyright statements. This might be // an indicator to take a closer look at the LICENSE file. if (linesWithCopyright.length > 1) { moduleInfo.copyright = `${moduleInfo.copyright}*`; } } } } } }); // console.log('moduleInfo.licenses after: %s', moduleInfo.licenses); Iif (!passedClarificationCheck) { console.error('All clarifications must come with a checksum'); process.exit(1); } // TODO: How do clarifications interact with notice files? noticeFiles.forEach((filename) => { const file = path.join(currentExtendedPackageJson.path, filename); /*istanbul ignore else*/ Iif (fs.lstatSync(file).isFile()) { moduleInfo.noticeFile = options.basePath ? path.relative(options.basePath, file) : file; } }); /*istanbul ignore else*/ if (currentExtendedPackageJson.dependencies) { Object.keys(currentExtendedPackageJson.dependencies).forEach((dependencyName) => { const childDependency = options.currentRecursionDepth > options._args.direct ? {} : currentExtendedPackageJson.dependencies[dependencyName]; const dependencyId = `${childDependency.name}@${childDependency.version}`; if (data[dependencyId]) { // already exists return; } data = recursivelyCollectAllDependencies({ _args: options._args, basePath: options.basePath, color: colorize, customFormat: options.customFormat, data, deps: childDependency, development: options.development, production: options.production, unknown, currentRecursionDepth: options.currentRecursionDepth + 1, clarifications: options.clarifications, }); }); } if (!currentExtendedPackageJson.name || !currentExtendedPackageJson.version) { delete data[currentPackageNameAndVersion]; } /*istanbul ignore next*/ if (options.customFormat) { Object.keys(options.customFormat).forEach((item) => { if (mustInclude(item) && moduleInfo[item] == null) { moduleInfo[item] = helpers.getFirstNotUndefinedOrUndefined( clarification?.[item], typeof currentExtendedPackageJson[item] === 'string' ? currentExtendedPackageJson[item] : options.customFormat[item], ); } }); } return data; }; exports.init = function init(args, callback) { debugLog('scanning %s', args.start); // customPath is a path to a JSON file that defined a custom format if (args.customPath) { args.customFormat = this.parseJson(args.customPath); } const optionsForReadingInstalledPackages = { depth: args.direct, // How deep to traverse the dependency tree nopeer: args.nopeer, // Whether or not to skip peerDependencies in output dev: true, // Whether or not to include devDependencies log: debugLog, // A function to log debug info }; if (args.production || args.development) { optionsForReadingInstalledPackages.dev = false; } const toCheckforFailOn = []; const toCheckforOnlyAllow = []; let checker; let pusher; if (args.onlyAllow) { checker = args.onlyAllow; pusher = toCheckforOnlyAllow; } if (args.failOn) { checker = args.failOn; pusher = toCheckforFailOn; } // An object mapping from Package name -> What contents it should have let clarifications = {}; if (args.clarificationsFile) { clarifications = this.parseJson(args.clarificationsFile); } if (checker && pusher) { checker.split(';').forEach((license) => { license = license.trim(); /*istanbul ignore else*/ if (license.length > 0) { pusher.push(license); } }); } readInstalledPackages(args.start, optionsForReadingInstalledPackages, (err, installedPackagesJson) => { // Good to know: // The json object returned by readInstalledPackages stores all direct (prod and dev) dependencies from // the package.json file in the property '_dependencies'. The property 'dependencies' contains all dependencies, // including the ones that are only required by other dependencies. if (optionsForReadingInstalledPackages.depth === 0) { helpers.deleteNonDirectDependenciesFromAllDependencies(installedPackagesJson, args); } // 'allWantedDepthDependenciesWithVersions' might be longer than 'installedPackagesJson.dependencies', as it appends the version numbers to each key (package name), // e.g. 'grunt@1' instead of 'grunt', and this way contains all different installed versions of each package: let allWantedDepthDependenciesWithVersions = recursivelyCollectAllDependencies({ _args: args, basePath: args.relativeLicensePath ? installedPackagesJson.path : null, color: args.color, customFormat: args.customFormat, data: {}, deps: installedPackagesJson, development: args.development, production: args.production, unknown: args.unknown, currentRecursionDepth: 0, clarifications, }); const colorize = args.color; const sorted = {}; // 'sorted' will store the same items as allWantedDepthDependenciesWithVersions, but sorted by package name and version let resultJson = {}; const excludeLicenses = args.excludeLicenses && args.excludeLicenses .match(/([^\\\][^,]|\\,)+/g) .map((license) => license.replace(/\\,/g, ',').replace(/^\s+|\s+$/g, '')); const includeLicenses = args.includeLicenses && args.includeLicenses .match(/([^\\\][^,]|\\,)+/g) .map((license) => license.replace(/\\,/g, ',').replace(/^\s+|\s+$/g, '')); let inputError = null; const colorizeString = (string) => /*istanbul ignore next*/ colorize ? chalk.bold.red(string) : string; const filterDeletePrivatePackages = (privatePackage) => { /*istanbul ignore next - I don't have access to private packages to test */ if (resultJson[privatePackage] && resultJson[privatePackage].private) { delete resultJson[privatePackage]; } }; const onlyIncludeWhitelist = (whitelist, filtered) => { const resultJson = {}; Object.keys(filtered).map((filteredPackage) => { // Whitelist packages by declaring: // 1. the package full name. Ex: `react` (we suffix an '@' to ensure we don't match packages like `react-native`) // 2. the package full name and the major version. Ex: `react@16` // 3. the package full name and full version. Ex: `react@16.0.2` if ( whitelist.findIndex((whitelistPackage) => filteredPackage.startsWith( whitelistPackage.lastIndexOf('@') > 0 ? whitelistPackage : `${whitelistPackage}@`, ), ) !== -1 ) { resultJson[filteredPackage] = filtered[filteredPackage]; } }); return resultJson; }; const excludeBlacklist = (blacklist, filtered) => { const resultJson = {}; Object.keys(filtered).map((filteredPackage) => { // Blacklist packages by declaring: // 1. the package full name. Ex: `react` (we suffix an '@' to ensure we don't match packages like `react-native`) // 2. the package full name and the major version. Ex: `react@16` // 3. the package full name and full version. Ex: `react@16.0.2` if ( blacklist.findIndex((blacklistPackage) => filteredPackage.startsWith( blacklistPackage.lastIndexOf('@') > 0 ? blacklistPackage : `${blacklistPackage}@`, ), ) === -1 ) { resultJson[filteredPackage] = filtered[filteredPackage]; } }); return resultJson; }; const excludePackagesStartingWith = (blacklist, currentResult) => { const resultJson = { ...currentResult }; for (const pkgName in resultJson) { for (const denyPrefix of blacklist) { if (pkgName.startsWith(denyPrefix)) delete resultJson[pkgName]; } } return resultJson; }; const exitIfCheckHits = (packageName) => { const currentLicense = resultJson[packageName]?.licenses; Eif (currentLicense) { checkForFailOn(currentLicense); checkForOnlyAllow(currentLicense, packageName); } }; const checkForFailOn = (currentLicense) => { if (toCheckforFailOn.length > 0) { if (toCheckforFailOn.indexOf(currentLicense) > -1) { console.error(`Found license defined by the --failOn flag: "${currentLicense}". Exiting.`); process.exit(1); } } }; const checkForOnlyAllow = (currentLicense, packageName) => { if (toCheckforOnlyAllow.length > 0) { let hasOnlyAllowedPackages = false; toCheckforOnlyAllow.forEach((allowedLicense) => { if (currentLicense.indexOf(allowedLicense) >= 0) { hasOnlyAllowedPackages = true; } }); if (!hasOnlyAllowedPackages) { console.error( `Package "${packageName}" is licensed under "${currentLicense}" which is not permitted by the --onlyAllow flag. Exiting.`, ); process.exit(1); } } }; const transformBSD = (spdx) => spdx === 'BSD' ? '(0BSD OR BSD-2-Clause OR BSD-3-Clause OR BSD-4-Clause)' : spdx; const invertResultOf = (fn) => (spdx) => !fn(spdx); const spdxIsValid = (spdx) => spdxCorrect(spdx) === spdx; const getLicenseMatch = (licensesArr, filtered, packageName, packageData, compareLicenses) => { const validSPDXLicenses = compareLicenses.map(transformBSD).filter(spdxIsValid); const invalidSPDXLicenses = compareLicenses.map(transformBSD).filter(invertResultOf(spdxIsValid)); const spdxExcluder = `( ${validSPDXLicenses.join(' OR ')} )`; let match = false; licensesArr.forEach((license) => { /*istanbul ignore if - just for protection*/ if (license.indexOf(LICENSE_TITLE_UNKNOWN) >= 0) { // Necessary due to colorization: filtered[packageName] = packageData; } else { if (license.endsWith('*')) { license = license.slice(0, -1); } license = transformBSD(license); if ( invalidSPDXLicenses.indexOf(license) >= 0 || (spdxCorrect(license) && validSPDXLicenses.length > 0 && spdxSatisfies(spdxCorrect(license), spdxExcluder)) ) { match = true; } } }); return match; }; // This following block stores the licenses in the sorted object (before, the sorted object is the empty object): Object.keys(allWantedDepthDependenciesWithVersions) .sort() .forEach((item) => { if (allWantedDepthDependenciesWithVersions[item].private) { allWantedDepthDependenciesWithVersions[item].licenses = colorizeString(LICENSE_TITLE_UNLICENSED); } /*istanbul ignore next*/ if (!allWantedDepthDependenciesWithVersions[item].licenses) { allWantedDepthDependenciesWithVersions[item].licenses = colorizeString(LICENSE_TITLE_UNKNOWN); } if ( args.unknown && allWantedDepthDependenciesWithVersions[item].licenses && allWantedDepthDependenciesWithVersions[item].licenses !== LICENSE_TITLE_UNKNOWN && allWantedDepthDependenciesWithVersions[item].licenses.indexOf('*') > -1 ) { /*istanbul ignore if*/ allWantedDepthDependenciesWithVersions[item].licenses = colorizeString(LICENSE_TITLE_UNKNOWN); } /*istanbul ignore else*/ if (allWantedDepthDependenciesWithVersions[item]) { if (args.relativeModulePath && allWantedDepthDependenciesWithVersions[item].path != null) { allWantedDepthDependenciesWithVersions[item].path = path.relative( args.start, allWantedDepthDependenciesWithVersions[item].path, ); } if (args.onlyunknown) { if ( allWantedDepthDependenciesWithVersions[item].licenses.indexOf('*') > -1 || allWantedDepthDependenciesWithVersions[item].licenses.indexOf(LICENSE_TITLE_UNKNOWN) > -1 ) { sorted[item] = allWantedDepthDependenciesWithVersions[item]; } } else { sorted[item] = allWantedDepthDependenciesWithVersions[item]; } } }); // 'allWantedDepthDependenciesWithVersions' is not needed anymore: allWantedDepthDependenciesWithVersions = null; if (!Object.keys(sorted).length) { err = new Error('No packages found in this path...'); } // This following block stores the entries from the 'sorted' object in the // resultJson object (before, the resultJson object is the empty object): if ( (!Array.isArray(excludeLicenses) || excludeLicenses.length === 0) && (!Array.isArray(includeLicenses) || includeLicenses.length === 0) ) { resultJson = { ...sorted }; } else { if (Array.isArray(excludeLicenses) && excludeLicenses.length > 0) { Object.entries(sorted).forEach(([packageName, packageData]) => { let { licenses } = packageData; /*istanbul ignore if - just for protection*/ if (!licenses) { resultJson[packageName] = packageData; } else { const licensesArr = Array.isArray(licenses) ? licenses : [licenses]; const licenseMatch = getLicenseMatch( licensesArr, resultJson, packageName, packageData, excludeLicenses, ); if (!licenseMatch) { resultJson[packageName] = packageData; } } }); } if (Array.isArray(includeLicenses) && includeLicenses.length > 0) { Object.entries(sorted).forEach(([packageName, packageData]) => { let { licenses } = packageData; /*istanbul ignore if - just for protection*/ if (!licenses) { resultJson[packageName] = packageData; } else { const licensesArr = Array.isArray(licenses) ? licenses : [licenses]; const licenseMatch = getLicenseMatch( licensesArr, resultJson, packageName, packageData, includeLicenses, ); if (licenseMatch) { resultJson[packageName] = packageData; } } }); } } // package whitelist const whitelist = helpers.getOptionArray(args.includePackages); if (whitelist) { resultJson = onlyIncludeWhitelist(whitelist, resultJson); } // package blacklist const blacklist = helpers.getOptionArray(args.excludePackages); if (blacklist) { resultJson = excludeBlacklist(blacklist, resultJson); } // exclude by package name starting with a string const excludeStartStringsArr = helpers.getOptionArray(args.excludePackagesStartingWith); if (excludeStartStringsArr) { resultJson = excludePackagesStartingWith(excludeStartStringsArr, resultJson); } if (args.excludePrivatePackages) { Object.keys(resultJson).forEach(filterDeletePrivatePackages); } Object.keys(resultJson).forEach(exitIfCheckHits); /*istanbul ignore next*/ if (err) { debugError(err); inputError = err; } // Return the callback and variables nicely callback(inputError, resultJson); }); }; exports.filterAttributes = (attributes, json) => { let filteredJson = json; if (attributes) { filteredJson = {}; attributes.forEach((attribute) => { filteredJson[attribute] = json[attribute]; }); } return filteredJson; }; exports.print = (sorted) => { console.log(exports.asTree(sorted)); }; exports.asTree = (sorted) => treeify.asTree(sorted, true); exports.asSummary = (sorted) => { const licenseCountMap = new global.Map(); const licenseCountArray = []; const sortedLicenseCountObj = {}; Object.values(sorted).forEach(({ licenses }) => { /*istanbul ignore else*/ if (licenses) { licenseCountMap.set(licenses, licenseCountMap.get(licenses) + 1 || 1); } }); licenseCountMap.forEach((count, license) => { licenseCountArray.push({ license, count }); }); /*istanbul ignore next*/ licenseCountArray .sort((a, b) => b.count - a.count) .forEach(({ license, count }) => { sortedLicenseCountObj[license] = count; }); return treeify.asTree(sortedLicenseCountObj, true); }; exports.asCSV = (sorted, customFormat, csvComponentPrefix) => { const csvHeaders = helpers.getCsvHeaders(customFormat, csvComponentPrefix); const csvDataArr = helpers.getCsvData(sorted, customFormat, csvComponentPrefix); return [csvHeaders, ...csvDataArr].join('\n'); }; /** * Exports data as markdown (*.md) file which has it's own syntax. * @method * @param {JSON} sorted The sorted JSON data from all packages. * @param {JSON} customFormat The custom format with information about the needed keys. * @return {String} The returning plain text. */ exports.asMarkDown = (sorted, customFormat) => { let text = []; if (customFormat && Object.keys(customFormat).length > 0) { Object.keys(sorted).forEach((sortedItem) => { text.push(`- **[${sortedItem}](${sorted[sortedItem].repository})**`); Object.keys(customFormat).forEach((customItem) => { text.push(` - ${customItem}: ${sorted[sortedItem][customItem]}`); }); }); } else { Object.keys(sorted).forEach((key) => { const module = sorted[key]; text.push(`- [${key}](${module.repository}) - ${module.licenses}`); }); } return text.join('\n'); }; /** * Output data in plain vertical format like Angular CLI does: https://angular.io/3rdpartylicenses.txt */ exports.asPlainVertical = (sorted) => Object.entries(sorted) .map(([moduleName, moduleData]) => { let licenseText = helpers.getModuleNameForLicenseTextHeader(moduleName); Iif (Array.isArray(moduleData.licenses) && moduleData.licenses.length > 0) { licenseText += moduleData.licenses.map((moduleLicense) => { /*istanbul ignore else*/ Iif (typeof moduleLicense === 'object') { /*istanbul ignore next*/ return moduleLicense.type || moduleLicense.name; } /*istanbul ignore next*/ if (typeof moduleLicense === 'string') { return moduleLicense; } }); } else Iif ( typeof moduleData.licenses === 'object' && (moduleData.licenses.type || moduleData.licenses.name) ) { licenseText += getLicenseTitle(moduleData.licenses.type || moduleData.licenses.name); } else Eif (typeof moduleData.licenses === 'string') { licenseText += getLicenseTitle(moduleData.licenses); } licenseText += '\n'; Iif (Array.isArray(moduleData.licenseFile) && moduleData.licenseFile.length > 0) { licenseText += moduleData.licenseFile.map((moduleLicense) => { /*istanbul ignore else*/ Iif (typeof moduleLicense === 'object') { /*istanbul ignore next*/ return moduleLicense.type || moduleLicense.name; } if (typeof moduleLicense === 'string') { return moduleLicense; } }); } else Iif ( typeof moduleData.licenseFile === 'object' && (moduleData.licenseFile.type || moduleData.licenseFile.name) ) { licenseText += moduleData.licenseFile.type || moduleData.licenseFile.name; } else Iif (typeof moduleData.licenseFile === 'string') { licenseText += fs.readFileSync(moduleData.licenseFile, { encoding: 'utf8' }); } return licenseText; }) .join('\n\n'); exports.parseJson = (jsonPath) => { if (typeof jsonPath !== 'string') { return new Error('The path was not specified for the JSON file to parse.'); } try { const jsonFileContents = fs.readFileSync(jsonPath, { encoding: 'utf8' }); return JSON.parse(jsonFileContents); } catch (err) { return err; } }; exports.asFiles = (json, outDir) => { mkdirp.sync(outDir); Object.keys(json).forEach((moduleName) => { const licenseFile = json[moduleName].licenseFile; if (licenseFile && fs.existsSync(licenseFile)) { const fileContents = fs.readFileSync(licenseFile); const outPath = path.join(outDir, `${moduleName}-LICENSE.txt`); const baseDir = path.dirname(outPath); mkdirp.sync(baseDir); fs.writeFileSync(outPath, fileContents, 'utf8'); } else { console.warn(`No license file found for module '${moduleName}'`); } }); }; |