action.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. #
  2. # SPDX-License-Identifier: GPL-2.0-only
  3. #
  4. import fnmatch
  5. import logging
  6. import os
  7. import shutil
  8. import sys
  9. import tempfile
  10. import bb.utils
  11. from bblayers.common import LayerPlugin
  12. logger = logging.getLogger('bitbake-layers')
  13. def plugin_init(plugins):
  14. return ActionPlugin()
  15. class ActionPlugin(LayerPlugin):
  16. def do_add_layer(self, args):
  17. """Add one or more layers to bblayers.conf."""
  18. layerdirs = [os.path.abspath(ldir) for ldir in args.layerdir]
  19. for layerdir in layerdirs:
  20. if not os.path.exists(layerdir):
  21. sys.stderr.write("Specified layer directory %s doesn't exist\n" % layerdir)
  22. return 1
  23. layer_conf = os.path.join(layerdir, 'conf', 'layer.conf')
  24. if not os.path.exists(layer_conf):
  25. sys.stderr.write("Specified layer directory %s doesn't contain a conf/layer.conf file\n" % layerdir)
  26. return 1
  27. bblayers_conf = os.path.join('conf', 'bblayers.conf')
  28. if not os.path.exists(bblayers_conf):
  29. sys.stderr.write("Unable to find bblayers.conf\n")
  30. return 1
  31. # Back up bblayers.conf to tempdir before we add layers
  32. tempdir = tempfile.mkdtemp()
  33. backup = tempdir + "/bblayers.conf.bak"
  34. shutil.copy2(bblayers_conf, backup)
  35. try:
  36. notadded, _ = bb.utils.edit_bblayers_conf(bblayers_conf, layerdirs, None)
  37. if not (args.force or notadded):
  38. try:
  39. self.tinfoil.run_command('parseConfiguration')
  40. except bb.tinfoil.TinfoilUIException:
  41. # Restore the back up copy of bblayers.conf
  42. shutil.copy2(backup, bblayers_conf)
  43. bb.fatal("Parse failure with the specified layer added")
  44. else:
  45. for item in notadded:
  46. sys.stderr.write("Specified layer %s is already in BBLAYERS\n" % item)
  47. finally:
  48. # Remove the back up copy of bblayers.conf
  49. shutil.rmtree(tempdir)
  50. def do_remove_layer(self, args):
  51. """Remove one or more layers from bblayers.conf."""
  52. bblayers_conf = os.path.join('conf', 'bblayers.conf')
  53. if not os.path.exists(bblayers_conf):
  54. sys.stderr.write("Unable to find bblayers.conf\n")
  55. return 1
  56. layerdirs = []
  57. for item in args.layerdir:
  58. if item.startswith('*'):
  59. layerdir = item
  60. elif not '/' in item:
  61. layerdir = '*/%s' % item
  62. else:
  63. layerdir = os.path.abspath(item)
  64. layerdirs.append(layerdir)
  65. (_, notremoved) = bb.utils.edit_bblayers_conf(bblayers_conf, None, layerdirs)
  66. if notremoved:
  67. for item in notremoved:
  68. sys.stderr.write("No layers matching %s found in BBLAYERS\n" % item)
  69. return 1
  70. def do_flatten(self, args):
  71. """flatten layer configuration into a separate output directory.
  72. Takes the specified layers (or all layers in the current layer
  73. configuration if none are specified) and builds a "flattened" directory
  74. containing the contents of all layers, with any overlayed recipes removed
  75. and bbappends appended to the corresponding recipes. Note that some manual
  76. cleanup may still be necessary afterwards, in particular:
  77. * where non-recipe files (such as patches) are overwritten (the flatten
  78. command will show a warning for these)
  79. * where anything beyond the normal layer setup has been added to
  80. layer.conf (only the lowest priority number layer's layer.conf is used)
  81. * overridden/appended items from bbappends will need to be tidied up
  82. * when the flattened layers do not have the same directory structure (the
  83. flatten command should show a warning when this will cause a problem)
  84. Warning: if you flatten several layers where another layer is intended to
  85. be used "inbetween" them (in layer priority order) such that recipes /
  86. bbappends in the layers interact, and then attempt to use the new output
  87. layer together with that other layer, you may no longer get the same
  88. build results (as the layer priority order has effectively changed).
  89. """
  90. if len(args.layer) == 1:
  91. logger.error('If you specify layers to flatten you must specify at least two')
  92. return 1
  93. outputdir = args.outputdir
  94. if os.path.exists(outputdir) and os.listdir(outputdir):
  95. logger.error('Directory %s exists and is non-empty, please clear it out first' % outputdir)
  96. return 1
  97. layers = self.bblayers
  98. if len(args.layer) > 2:
  99. layernames = args.layer
  100. found_layernames = []
  101. found_layerdirs = []
  102. for layerdir in layers:
  103. layername = self.get_layer_name(layerdir)
  104. if layername in layernames:
  105. found_layerdirs.append(layerdir)
  106. found_layernames.append(layername)
  107. for layername in layernames:
  108. if not layername in found_layernames:
  109. logger.error('Unable to find layer %s in current configuration, please run "%s show-layers" to list configured layers' % (layername, os.path.basename(sys.argv[0])))
  110. return
  111. layers = found_layerdirs
  112. else:
  113. layernames = []
  114. # Ensure a specified path matches our list of layers
  115. def layer_path_match(path):
  116. for layerdir in layers:
  117. if path.startswith(os.path.join(layerdir, '')):
  118. return layerdir
  119. return None
  120. applied_appends = []
  121. for layer in layers:
  122. overlayed = []
  123. for f in self.tinfoil.cooker.collection.overlayed.keys():
  124. for of in self.tinfoil.cooker.collection.overlayed[f]:
  125. if of.startswith(layer):
  126. overlayed.append(of)
  127. logger.plain('Copying files from %s...' % layer )
  128. for root, dirs, files in os.walk(layer):
  129. if '.git' in dirs:
  130. dirs.remove('.git')
  131. if '.hg' in dirs:
  132. dirs.remove('.hg')
  133. for f1 in files:
  134. f1full = os.sep.join([root, f1])
  135. if f1full in overlayed:
  136. logger.plain(' Skipping overlayed file %s' % f1full )
  137. else:
  138. ext = os.path.splitext(f1)[1]
  139. if ext != '.bbappend':
  140. fdest = f1full[len(layer):]
  141. fdest = os.path.normpath(os.sep.join([outputdir,fdest]))
  142. bb.utils.mkdirhier(os.path.dirname(fdest))
  143. if os.path.exists(fdest):
  144. if f1 == 'layer.conf' and root.endswith('/conf'):
  145. logger.plain(' Skipping layer config file %s' % f1full )
  146. continue
  147. else:
  148. logger.warning('Overwriting file %s', fdest)
  149. bb.utils.copyfile(f1full, fdest)
  150. if ext == '.bb':
  151. for append in self.tinfoil.cooker.collection.get_file_appends(f1full):
  152. if layer_path_match(append):
  153. logger.plain(' Applying append %s to %s' % (append, fdest))
  154. self.apply_append(append, fdest)
  155. applied_appends.append(append)
  156. # Take care of when some layers are excluded and yet we have included bbappends for those recipes
  157. for b in self.tinfoil.cooker.collection.bbappends:
  158. (recipename, appendname) = b
  159. if appendname not in applied_appends:
  160. first_append = None
  161. layer = layer_path_match(appendname)
  162. if layer:
  163. if first_append:
  164. self.apply_append(appendname, first_append)
  165. else:
  166. fdest = appendname[len(layer):]
  167. fdest = os.path.normpath(os.sep.join([outputdir,fdest]))
  168. bb.utils.mkdirhier(os.path.dirname(fdest))
  169. bb.utils.copyfile(appendname, fdest)
  170. first_append = fdest
  171. # Get the regex for the first layer in our list (which is where the conf/layer.conf file will
  172. # have come from)
  173. first_regex = None
  174. layerdir = layers[0]
  175. for layername, pattern, regex, _ in self.tinfoil.cooker.bbfile_config_priorities:
  176. if regex.match(os.path.join(layerdir, 'test')):
  177. first_regex = regex
  178. break
  179. if first_regex:
  180. # Find the BBFILES entries that match (which will have come from this conf/layer.conf file)
  181. bbfiles = str(self.tinfoil.config_data.getVar('BBFILES')).split()
  182. bbfiles_layer = []
  183. for item in bbfiles:
  184. if first_regex.match(item):
  185. newpath = os.path.join(outputdir, item[len(layerdir)+1:])
  186. bbfiles_layer.append(newpath)
  187. if bbfiles_layer:
  188. # Check that all important layer files match BBFILES
  189. for root, dirs, files in os.walk(outputdir):
  190. for f1 in files:
  191. ext = os.path.splitext(f1)[1]
  192. if ext in ['.bb', '.bbappend']:
  193. f1full = os.sep.join([root, f1])
  194. entry_found = False
  195. for item in bbfiles_layer:
  196. if fnmatch.fnmatch(f1full, item):
  197. entry_found = True
  198. break
  199. if not entry_found:
  200. logger.warning("File %s does not match the flattened layer's BBFILES setting, you may need to edit conf/layer.conf or move the file elsewhere" % f1full)
  201. def get_file_layer(self, filename):
  202. layerdir = self.get_file_layerdir(filename)
  203. if layerdir:
  204. return self.get_layer_name(layerdir)
  205. else:
  206. return '?'
  207. def get_file_layerdir(self, filename):
  208. layer = bb.utils.get_file_layer(filename, self.tinfoil.config_data)
  209. return self.bbfile_collections.get(layer, None)
  210. def apply_append(self, appendname, recipename):
  211. with open(appendname, 'r') as appendfile:
  212. with open(recipename, 'a') as recipefile:
  213. recipefile.write('\n')
  214. recipefile.write('##### bbappended from %s #####\n' % self.get_file_layer(appendname))
  215. recipefile.writelines(appendfile.readlines())
  216. def register_commands(self, sp):
  217. parser_add_layer = self.add_command(sp, 'add-layer', self.do_add_layer, parserecipes=False)
  218. parser_add_layer.add_argument('layerdir', nargs='+', help='Layer directory/directories to add')
  219. parser_remove_layer = self.add_command(sp, 'remove-layer', self.do_remove_layer, parserecipes=False)
  220. parser_remove_layer.add_argument('layerdir', nargs='+', help='Layer directory/directories to remove (wildcards allowed, enclose in quotes to avoid shell expansion)')
  221. parser_remove_layer.set_defaults(func=self.do_remove_layer)
  222. parser_flatten = self.add_command(sp, 'flatten', self.do_flatten)
  223. parser_flatten.add_argument('layer', nargs='*', help='Optional layer(s) to flatten (otherwise all are flattened)')
  224. parser_flatten.add_argument('outputdir', help='Output directory')