index.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. var parse = require('spdx-expression-parse');
  2. var correct = require('spdx-correct');
  3. var genericWarning = (
  4. 'license should be ' +
  5. 'a valid SPDX license expression (without "LicenseRef"), ' +
  6. '"UNLICENSED", or ' +
  7. '"SEE LICENSE IN <filename>"'
  8. );
  9. var fileReferenceRE = /^SEE LICEN[CS]E IN (.+)$/;
  10. function startsWith(prefix, string) {
  11. return string.slice(0, prefix.length) === prefix;
  12. }
  13. function usesLicenseRef(ast) {
  14. if (ast.hasOwnProperty('license')) {
  15. var license = ast.license;
  16. return (
  17. startsWith('LicenseRef', license) ||
  18. startsWith('DocumentRef', license)
  19. );
  20. } else {
  21. return (
  22. usesLicenseRef(ast.left) ||
  23. usesLicenseRef(ast.right)
  24. );
  25. }
  26. }
  27. module.exports = function(argument) {
  28. var ast;
  29. try {
  30. ast = parse(argument);
  31. } catch (e) {
  32. var match
  33. if (
  34. argument === 'UNLICENSED' ||
  35. argument === 'UNLICENCED'
  36. ) {
  37. return {
  38. validForOldPackages: true,
  39. validForNewPackages: true,
  40. unlicensed: true
  41. };
  42. } else if (match = fileReferenceRE.exec(argument)) {
  43. return {
  44. validForOldPackages: true,
  45. validForNewPackages: true,
  46. inFile: match[1]
  47. };
  48. } else {
  49. var result = {
  50. validForOldPackages: false,
  51. validForNewPackages: false,
  52. warnings: [genericWarning]
  53. };
  54. if (argument.trim().length !== 0) {
  55. var corrected = correct(argument);
  56. if (corrected) {
  57. result.warnings.push(
  58. 'license is similar to the valid expression "' + corrected + '"'
  59. );
  60. }
  61. }
  62. return result;
  63. }
  64. }
  65. if (usesLicenseRef(ast)) {
  66. return {
  67. validForNewPackages: false,
  68. validForOldPackages: false,
  69. spdx: true,
  70. warnings: [genericWarning]
  71. };
  72. } else {
  73. return {
  74. validForNewPackages: true,
  75. validForOldPackages: true,
  76. spdx: true
  77. };
  78. }
  79. };