action.py 11 KB

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