action.py 12 KB

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