create_npm.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. # Recipe creation tool - node.js NPM module support plugin
  2. #
  3. # Copyright (C) 2016 Intel Corporation
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License version 2 as
  7. # published by the Free Software Foundation.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License along
  15. # with this program; if not, write to the Free Software Foundation, Inc.,
  16. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  17. import os
  18. import logging
  19. import subprocess
  20. import tempfile
  21. import shutil
  22. import json
  23. from recipetool.create import RecipeHandler, split_pkg_licenses
  24. logger = logging.getLogger('recipetool')
  25. tinfoil = None
  26. def tinfoil_init(instance):
  27. global tinfoil
  28. tinfoil = instance
  29. class NpmRecipeHandler(RecipeHandler):
  30. lockdownpath = None
  31. def _handle_license(self, data):
  32. '''
  33. Handle the license value from an npm package.json file
  34. '''
  35. license = None
  36. if 'license' in data:
  37. license = data['license']
  38. if isinstance(license, dict):
  39. license = license.get('type', None)
  40. return license
  41. def _shrinkwrap(self, srctree, localfilesdir, extravalues, lines_before):
  42. try:
  43. runenv = dict(os.environ, PATH=tinfoil.config_data.getVar('PATH', True))
  44. bb.process.run('npm shrinkwrap', cwd=srctree, stderr=subprocess.STDOUT, env=runenv, shell=True)
  45. except bb.process.ExecutionError as e:
  46. logger.warn('npm shrinkwrap failed:\n%s' % e.stdout)
  47. return
  48. tmpfile = os.path.join(localfilesdir, 'npm-shrinkwrap.json')
  49. shutil.move(os.path.join(srctree, 'npm-shrinkwrap.json'), tmpfile)
  50. extravalues.setdefault('extrafiles', {})
  51. extravalues['extrafiles']['npm-shrinkwrap.json'] = tmpfile
  52. lines_before.append('NPM_SHRINKWRAP := "${THISDIR}/${PN}/npm-shrinkwrap.json"')
  53. def _lockdown(self, srctree, localfilesdir, extravalues, lines_before):
  54. runenv = dict(os.environ, PATH=tinfoil.config_data.getVar('PATH', True))
  55. if not NpmRecipeHandler.lockdownpath:
  56. NpmRecipeHandler.lockdownpath = tempfile.mkdtemp('recipetool-npm-lockdown')
  57. bb.process.run('npm install lockdown --prefix %s' % NpmRecipeHandler.lockdownpath,
  58. cwd=srctree, stderr=subprocess.STDOUT, env=runenv, shell=True)
  59. relockbin = os.path.join(NpmRecipeHandler.lockdownpath, 'node_modules', 'lockdown', 'relock.js')
  60. if not os.path.exists(relockbin):
  61. logger.warn('Could not find relock.js within lockdown directory; skipping lockdown')
  62. return
  63. try:
  64. bb.process.run('node %s' % relockbin, cwd=srctree, stderr=subprocess.STDOUT, env=runenv, shell=True)
  65. except bb.process.ExecutionError as e:
  66. logger.warn('lockdown-relock failed:\n%s' % e.stdout)
  67. return
  68. tmpfile = os.path.join(localfilesdir, 'lockdown.json')
  69. shutil.move(os.path.join(srctree, 'lockdown.json'), tmpfile)
  70. extravalues.setdefault('extrafiles', {})
  71. extravalues['extrafiles']['lockdown.json'] = tmpfile
  72. lines_before.append('NPM_LOCKDOWN := "${THISDIR}/${PN}/lockdown.json"')
  73. def process(self, srctree, classes, lines_before, lines_after, handled, extravalues):
  74. import bb.utils
  75. import oe
  76. from collections import OrderedDict
  77. if 'buildsystem' in handled:
  78. return False
  79. def read_package_json(fn):
  80. with open(fn, 'r', errors='surrogateescape') as f:
  81. return json.loads(f.read())
  82. files = RecipeHandler.checkfiles(srctree, ['package.json'])
  83. if files:
  84. data = read_package_json(files[0])
  85. if 'name' in data and 'version' in data:
  86. extravalues['PN'] = data['name']
  87. extravalues['PV'] = data['version']
  88. classes.append('npm')
  89. handled.append('buildsystem')
  90. if 'description' in data:
  91. extravalues['SUMMARY'] = data['description']
  92. if 'homepage' in data:
  93. extravalues['HOMEPAGE'] = data['homepage']
  94. # Shrinkwrap
  95. localfilesdir = tempfile.mkdtemp(prefix='recipetool-npm')
  96. self._shrinkwrap(srctree, localfilesdir, extravalues, lines_before)
  97. # Lockdown
  98. self._lockdown(srctree, localfilesdir, extravalues, lines_before)
  99. # Split each npm module out to is own package
  100. npmpackages = oe.package.npm_split_package_dirs(srctree)
  101. for item in handled:
  102. if isinstance(item, tuple):
  103. if item[0] == 'license':
  104. licvalues = item[1]
  105. break
  106. if licvalues:
  107. # Augment the license list with information we have in the packages
  108. licenses = {}
  109. license = self._handle_license(data)
  110. if license:
  111. licenses['${PN}'] = license
  112. for pkgname, pkgitem in npmpackages.items():
  113. _, pdata = pkgitem
  114. license = self._handle_license(pdata)
  115. if license:
  116. licenses[pkgname] = license
  117. # Now write out the package-specific license values
  118. # We need to strip out the json data dicts for this since split_pkg_licenses
  119. # isn't expecting it
  120. packages = OrderedDict((x,y[0]) for x,y in npmpackages.items())
  121. packages['${PN}'] = ''
  122. pkglicenses = split_pkg_licenses(licvalues, packages, lines_after, licenses)
  123. all_licenses = list(set([item for pkglicense in pkglicenses.values() for item in pkglicense]))
  124. # Go back and update the LICENSE value since we have a bit more
  125. # information than when that was written out (and we know all apply
  126. # vs. there being a choice, so we can join them with &)
  127. for i, line in enumerate(lines_before):
  128. if line.startswith('LICENSE = '):
  129. lines_before[i] = 'LICENSE = "%s"' % ' & '.join(all_licenses)
  130. break
  131. return True
  132. return False
  133. def register_recipe_handlers(handlers):
  134. handlers.append((NpmRecipeHandler(), 60))