bitbake-layers 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  1. #!/usr/bin/env python
  2. # This script has subcommands which operate against your bitbake layers, either
  3. # displaying useful information, or acting against them.
  4. # See the help output for details on available commands.
  5. # Copyright (C) 2011 Mentor Graphics Corporation
  6. # Copyright (C) 2011-2015 Intel Corporation
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License version 2 as
  10. # published by the Free Software Foundation.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License along
  18. # with this program; if not, write to the Free Software Foundation, Inc.,
  19. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. import logging
  21. import os
  22. import sys
  23. import fnmatch
  24. from collections import defaultdict
  25. import argparse
  26. import re
  27. import httplib, urlparse, json
  28. import subprocess
  29. bindir = os.path.dirname(__file__)
  30. topdir = os.path.dirname(bindir)
  31. sys.path[0:0] = [os.path.join(topdir, 'lib')]
  32. import bb.cache
  33. import bb.cooker
  34. import bb.providers
  35. import bb.utils
  36. import bb.tinfoil
  37. def logger_create(name, output=sys.stderr):
  38. logger = logging.getLogger(name)
  39. console = logging.StreamHandler(output)
  40. format = bb.msg.BBLogFormatter("%(levelname)s: %(message)s")
  41. if output.isatty():
  42. format.enable_color()
  43. console.setFormatter(format)
  44. logger.addHandler(console)
  45. logger.setLevel(logging.INFO)
  46. return logger
  47. logger = logger_create('bitbake-layers', sys.stdout)
  48. class Commands():
  49. def __init__(self):
  50. self.bbhandler = None
  51. self.bblayers = []
  52. def init_bbhandler(self, config_only = False):
  53. if not self.bbhandler:
  54. self.bbhandler = bb.tinfoil.Tinfoil()
  55. self.bblayers = (self.bbhandler.config_data.getVar('BBLAYERS', True) or "").split()
  56. self.bbhandler.prepare(config_only)
  57. def do_show_layers(self, args):
  58. """show current configured layers"""
  59. self.init_bbhandler(config_only = True)
  60. logger.plain("%s %s %s" % ("layer".ljust(20), "path".ljust(40), "priority"))
  61. logger.plain('=' * 74)
  62. for layerdir in self.bblayers:
  63. layername = self.get_layer_name(layerdir)
  64. layerpri = 0
  65. for layer, _, regex, pri in self.bbhandler.cooker.recipecache.bbfile_config_priorities:
  66. if regex.match(os.path.join(layerdir, 'test')):
  67. layerpri = pri
  68. break
  69. logger.plain("%s %s %d" % (layername.ljust(20), layerdir.ljust(40), layerpri))
  70. def do_add_layer(self, args):
  71. """Add a layer to bblayers.conf
  72. Adds the specified layer to bblayers.conf
  73. """
  74. layerdir = os.path.abspath(args.layerdir)
  75. if not os.path.exists(layerdir):
  76. sys.stderr.write("Specified layer directory doesn't exist\n")
  77. return 1
  78. layer_conf = os.path.join(layerdir, 'conf', 'layer.conf')
  79. if not os.path.exists(layer_conf):
  80. sys.stderr.write("Specified layer directory doesn't contain a conf/layer.conf file\n")
  81. return 1
  82. bblayers_conf = os.path.join('conf', 'bblayers.conf')
  83. if not os.path.exists(bblayers_conf):
  84. sys.stderr.write("Unable to find bblayers.conf\n")
  85. return 1
  86. (notadded, _) = bb.utils.edit_bblayers_conf(bblayers_conf, layerdir, None)
  87. if notadded:
  88. for item in notadded:
  89. sys.stderr.write("Specified layer %s is already in BBLAYERS\n" % item)
  90. def do_remove_layer(self, args):
  91. """Remove a layer from bblayers.conf
  92. Removes the specified layer from bblayers.conf
  93. """
  94. bblayers_conf = os.path.join('conf', 'bblayers.conf')
  95. if not os.path.exists(bblayers_conf):
  96. sys.stderr.write("Unable to find bblayers.conf\n")
  97. return 1
  98. if args.layerdir.startswith('*'):
  99. layerdir = args.layerdir
  100. else:
  101. layerdir = os.path.abspath(args.layerdir)
  102. (_, notremoved) = bb.utils.edit_bblayers_conf(bblayers_conf, None, layerdir)
  103. if notremoved:
  104. for item in notremoved:
  105. sys.stderr.write("No layers matching %s found in BBLAYERS\n" % item)
  106. return 1
  107. def get_json_data(self, apiurl):
  108. proxy_settings = os.environ.get("http_proxy", None)
  109. conn = None
  110. _parsedurl = urlparse.urlparse(apiurl)
  111. path = _parsedurl.path
  112. query = _parsedurl.query
  113. def parse_url(url):
  114. parsedurl = urlparse.urlparse(url)
  115. if parsedurl.netloc[0] == '[':
  116. host, port = parsedurl.netloc[1:].split(']', 1)
  117. if ':' in port:
  118. port = port.rsplit(':', 1)[1]
  119. else:
  120. port = None
  121. else:
  122. if parsedurl.netloc.count(':') == 1:
  123. (host, port) = parsedurl.netloc.split(":")
  124. else:
  125. host = parsedurl.netloc
  126. port = None
  127. return (host, 80 if port is None else int(port))
  128. if proxy_settings is None:
  129. host, port = parse_url(apiurl)
  130. conn = httplib.HTTPConnection(host, port)
  131. conn.request("GET", path + "?" + query)
  132. else:
  133. host, port = parse_url(proxy_settings)
  134. conn = httplib.HTTPConnection(host, port)
  135. conn.request("GET", apiurl)
  136. r = conn.getresponse()
  137. if r.status != 200:
  138. raise Exception("Failed to read " + path + ": %d %s" % (r.status, r.reason))
  139. return json.loads(r.read())
  140. def get_layer_deps(self, layername, layeritems, layerbranches, layerdependencies, branchnum, selfname=False):
  141. def layeritems_info_id(items_name, layeritems):
  142. litems_id = None
  143. for li in layeritems:
  144. if li['name'] == items_name:
  145. litems_id = li['id']
  146. break
  147. return litems_id
  148. def layerbranches_info(items_id, layerbranches):
  149. lbranch = {}
  150. for lb in layerbranches:
  151. if lb['layer'] == items_id and lb['branch'] == branchnum:
  152. lbranch['id'] = lb['id']
  153. lbranch['vcs_subdir'] = lb['vcs_subdir']
  154. break
  155. return lbranch
  156. def layerdependencies_info(lb_id, layerdependencies):
  157. ld_deps = []
  158. for ld in layerdependencies:
  159. if ld['layerbranch'] == lb_id and not ld['dependency'] in ld_deps:
  160. ld_deps.append(ld['dependency'])
  161. if not ld_deps:
  162. logger.error("The dependency of layerDependencies is not found.")
  163. return ld_deps
  164. def layeritems_info_name_subdir(items_id, layeritems):
  165. litems = {}
  166. for li in layeritems:
  167. if li['id'] == items_id:
  168. litems['vcs_url'] = li['vcs_url']
  169. litems['name'] = li['name']
  170. break
  171. return litems
  172. if selfname:
  173. selfid = layeritems_info_id(layername, layeritems)
  174. lbinfo = layerbranches_info(selfid, layerbranches)
  175. if lbinfo:
  176. selfsubdir = lbinfo['vcs_subdir']
  177. else:
  178. logger.error("%s is not found in the specified branch" % layername)
  179. return
  180. selfurl = layeritems_info_name_subdir(selfid, layeritems)['vcs_url']
  181. if selfurl:
  182. return selfurl, selfsubdir
  183. else:
  184. logger.error("Cannot get layer %s git repo and subdir" % layername)
  185. return
  186. ldict = {}
  187. itemsid = layeritems_info_id(layername, layeritems)
  188. if not itemsid:
  189. return layername, None
  190. lbid = layerbranches_info(itemsid, layerbranches)
  191. if lbid:
  192. lbid = layerbranches_info(itemsid, layerbranches)['id']
  193. else:
  194. logger.error("%s is not found in the specified branch" % layername)
  195. return None, None
  196. for dependency in layerdependencies_info(lbid, layerdependencies):
  197. lname = layeritems_info_name_subdir(dependency, layeritems)['name']
  198. lurl = layeritems_info_name_subdir(dependency, layeritems)['vcs_url']
  199. lsubdir = layerbranches_info(dependency, layerbranches)['vcs_subdir']
  200. ldict[lname] = lurl, lsubdir
  201. return None, ldict
  202. def get_fetch_layer(self, fetchdir, url, subdir, fetch_layer):
  203. layername = self.get_layer_name(url)
  204. if os.path.splitext(layername)[1] == '.git':
  205. layername = os.path.splitext(layername)[0]
  206. repodir = os.path.join(fetchdir, layername)
  207. layerdir = os.path.join(repodir, subdir)
  208. if not os.path.exists(repodir):
  209. if fetch_layer:
  210. result = subprocess.call('git clone %s %s' % (url, repodir), shell = True)
  211. if result:
  212. logger.error("Failed to download %s" % url)
  213. return None, None
  214. else:
  215. return layername, layerdir
  216. else:
  217. logger.plain("Repository %s needs to be fetched" % url)
  218. return layername, layerdir
  219. elif os.path.exists(layerdir):
  220. return layername, layerdir
  221. else:
  222. logger.error("%s is not in %s" % (url, subdir))
  223. return None, None
  224. def do_layerindex_fetch(self, args):
  225. """Fetches a layer from a layer index along with its dependent layers, and adds them to conf/bblayers.conf.
  226. """
  227. self.init_bbhandler(config_only = True)
  228. apiurl = self.bbhandler.config_data.getVar('BBLAYERS_LAYERINDEX_URL', True)
  229. if not apiurl:
  230. logger.error("Cannot get BBLAYERS_LAYERINDEX_URL")
  231. return 1
  232. else:
  233. if apiurl[-1] != '/':
  234. apiurl += '/'
  235. apiurl += "api/"
  236. apilinks = self.get_json_data(apiurl)
  237. branches = self.get_json_data(apilinks['branches'])
  238. branchnum = 0
  239. for branch in branches:
  240. if branch['name'] == args.branch:
  241. branchnum = branch['id']
  242. break
  243. if branchnum == 0:
  244. validbranches = ', '.join([branch['name'] for branch in branches])
  245. logger.error('Invalid layer branch name "%s". Valid branches: %s' % (args.branch, validbranches))
  246. return 1
  247. ignore_layers = []
  248. for collection in self.bbhandler.config_data.getVar('BBFILE_COLLECTIONS', True).split():
  249. lname = self.bbhandler.config_data.getVar('BBLAYERS_LAYERINDEX_NAME_%s' % collection, True)
  250. if lname:
  251. ignore_layers.append(lname)
  252. if args.ignore:
  253. ignore_layers.extend(args.ignore.split(','))
  254. layeritems = self.get_json_data(apilinks['layerItems'])
  255. layerbranches = self.get_json_data(apilinks['layerBranches'])
  256. layerdependencies = self.get_json_data(apilinks['layerDependencies'])
  257. invaluenames = []
  258. repourls = {}
  259. printlayers = []
  260. def query_dependencies(layers, layeritems, layerbranches, layerdependencies, branchnum):
  261. depslayer = []
  262. for layername in layers:
  263. invaluename, layerdict = self.get_layer_deps(layername, layeritems, layerbranches, layerdependencies, branchnum)
  264. if layerdict:
  265. repourls[layername] = self.get_layer_deps(layername, layeritems, layerbranches, layerdependencies, branchnum, selfname=True)
  266. for layer in layerdict:
  267. if not layer in ignore_layers:
  268. depslayer.append(layer)
  269. printlayers.append((layername, layer, layerdict[layer][0], layerdict[layer][1]))
  270. if not layer in ignore_layers and not layer in repourls:
  271. repourls[layer] = (layerdict[layer][0], layerdict[layer][1])
  272. if invaluename and not invaluename in invaluenames:
  273. invaluenames.append(invaluename)
  274. return depslayer
  275. depslayers = query_dependencies(args.layername, layeritems, layerbranches, layerdependencies, branchnum)
  276. while depslayers:
  277. depslayer = query_dependencies(depslayers, layeritems, layerbranches, layerdependencies, branchnum)
  278. depslayers = depslayer
  279. if invaluenames:
  280. for invaluename in invaluenames:
  281. logger.error('Layer "%s" not found in layer index' % invaluename)
  282. return 1
  283. logger.plain("%s %s %s %s" % ("Layer".ljust(19), "Required by".ljust(19), "Git repository".ljust(54), "Subdirectory"))
  284. logger.plain('=' * 115)
  285. for layername in args.layername:
  286. layerurl = repourls[layername]
  287. logger.plain("%s %s %s %s" % (layername.ljust(20), '-'.ljust(20), layerurl[0].ljust(55), layerurl[1]))
  288. printedlayers = []
  289. for layer, dependency, gitrepo, subdirectory in printlayers:
  290. if dependency in printedlayers:
  291. continue
  292. logger.plain("%s %s %s %s" % (dependency.ljust(20), layer.ljust(20), gitrepo.ljust(55), subdirectory))
  293. printedlayers.append(dependency)
  294. if repourls:
  295. fetchdir = self.bbhandler.config_data.getVar('BBLAYERS_FETCH_DIR', True)
  296. if not fetchdir:
  297. logger.error("Cannot get BBLAYERS_FETCH_DIR")
  298. return 1
  299. if not os.path.exists(fetchdir):
  300. os.makedirs(fetchdir)
  301. addlayers = []
  302. for repourl, subdir in repourls.values():
  303. name, layerdir = self.get_fetch_layer(fetchdir, repourl, subdir, not args.show_only)
  304. if not name:
  305. # Error already shown
  306. return 1
  307. addlayers.append((subdir, name, layerdir))
  308. if not args.show_only:
  309. for subdir, name, layerdir in set(addlayers):
  310. if os.path.exists(layerdir):
  311. if subdir:
  312. logger.plain("Adding layer \"%s\" to conf/bblayers.conf" % subdir)
  313. else:
  314. logger.plain("Adding layer \"%s\" to conf/bblayers.conf" % name)
  315. localargs = argparse.Namespace()
  316. localargs.layerdir = layerdir
  317. self.do_add_layer(localargs)
  318. else:
  319. break
  320. def do_layerindex_show_depends(self, args):
  321. """Find layer dependencies from layer index.
  322. """
  323. args.show_only = True
  324. args.ignore = []
  325. self.do_layerindex_fetch(args)
  326. def version_str(self, pe, pv, pr = None):
  327. verstr = "%s" % pv
  328. if pr:
  329. verstr = "%s-%s" % (verstr, pr)
  330. if pe:
  331. verstr = "%s:%s" % (pe, verstr)
  332. return verstr
  333. def do_show_overlayed(self, args):
  334. """list overlayed recipes (where the same recipe exists in another layer)
  335. Lists the names of overlayed recipes and the available versions in each
  336. layer, with the preferred version first. Note that skipped recipes that
  337. are overlayed will also be listed, with a " (skipped)" suffix.
  338. """
  339. self.init_bbhandler()
  340. items_listed = self.list_recipes('Overlayed recipes', None, True, args.same_version, args.filenames, True)
  341. # Check for overlayed .bbclass files
  342. classes = defaultdict(list)
  343. for layerdir in self.bblayers:
  344. classdir = os.path.join(layerdir, 'classes')
  345. if os.path.exists(classdir):
  346. for classfile in os.listdir(classdir):
  347. if os.path.splitext(classfile)[1] == '.bbclass':
  348. classes[classfile].append(classdir)
  349. # Locating classes and other files is a bit more complicated than recipes -
  350. # layer priority is not a factor; instead BitBake uses the first matching
  351. # file in BBPATH, which is manipulated directly by each layer's
  352. # conf/layer.conf in turn, thus the order of layers in bblayers.conf is a
  353. # factor - however, each layer.conf is free to either prepend or append to
  354. # BBPATH (or indeed do crazy stuff with it). Thus the order in BBPATH might
  355. # not be exactly the order present in bblayers.conf either.
  356. bbpath = str(self.bbhandler.config_data.getVar('BBPATH', True))
  357. overlayed_class_found = False
  358. for (classfile, classdirs) in classes.items():
  359. if len(classdirs) > 1:
  360. if not overlayed_class_found:
  361. logger.plain('=== Overlayed classes ===')
  362. overlayed_class_found = True
  363. mainfile = bb.utils.which(bbpath, os.path.join('classes', classfile))
  364. if args.filenames:
  365. logger.plain('%s' % mainfile)
  366. else:
  367. # We effectively have to guess the layer here
  368. logger.plain('%s:' % classfile)
  369. mainlayername = '?'
  370. for layerdir in self.bblayers:
  371. classdir = os.path.join(layerdir, 'classes')
  372. if mainfile.startswith(classdir):
  373. mainlayername = self.get_layer_name(layerdir)
  374. logger.plain(' %s' % mainlayername)
  375. for classdir in classdirs:
  376. fullpath = os.path.join(classdir, classfile)
  377. if fullpath != mainfile:
  378. if args.filenames:
  379. print(' %s' % fullpath)
  380. else:
  381. print(' %s' % self.get_layer_name(os.path.dirname(classdir)))
  382. if overlayed_class_found:
  383. items_listed = True;
  384. if not items_listed:
  385. logger.plain('No overlayed files found.')
  386. def do_show_recipes(self, args):
  387. """list available recipes, showing the layer they are provided by
  388. Lists the names of recipes and the available versions in each
  389. layer, with the preferred version first. Optionally you may specify
  390. pnspec to match a specified recipe name (supports wildcards). Note that
  391. skipped recipes will also be listed, with a " (skipped)" suffix.
  392. """
  393. self.init_bbhandler()
  394. title = 'Available recipes:'
  395. self.list_recipes(title, args.pnspec, False, False, args.filenames, args.multiple)
  396. def list_recipes(self, title, pnspec, show_overlayed_only, show_same_ver_only, show_filenames, show_multi_provider_only):
  397. pkg_pn = self.bbhandler.cooker.recipecache.pkg_pn
  398. (latest_versions, preferred_versions) = bb.providers.findProviders(self.bbhandler.config_data, self.bbhandler.cooker.recipecache, pkg_pn)
  399. allproviders = bb.providers.allProviders(self.bbhandler.cooker.recipecache)
  400. # Ensure we list skipped recipes
  401. # We are largely guessing about PN, PV and the preferred version here,
  402. # but we have no choice since skipped recipes are not fully parsed
  403. skiplist = self.bbhandler.cooker.skiplist.keys()
  404. skiplist.sort( key=lambda fileitem: self.bbhandler.cooker.collection.calc_bbfile_priority(fileitem) )
  405. skiplist.reverse()
  406. for fn in skiplist:
  407. recipe_parts = os.path.splitext(os.path.basename(fn))[0].split('_')
  408. p = recipe_parts[0]
  409. if len(recipe_parts) > 1:
  410. ver = (None, recipe_parts[1], None)
  411. else:
  412. ver = (None, 'unknown', None)
  413. allproviders[p].append((ver, fn))
  414. if not p in pkg_pn:
  415. pkg_pn[p] = 'dummy'
  416. preferred_versions[p] = (ver, fn)
  417. def print_item(f, pn, ver, layer, ispref):
  418. if f in skiplist:
  419. skipped = ' (skipped)'
  420. else:
  421. skipped = ''
  422. if show_filenames:
  423. if ispref:
  424. logger.plain("%s%s", f, skipped)
  425. else:
  426. logger.plain(" %s%s", f, skipped)
  427. else:
  428. if ispref:
  429. logger.plain("%s:", pn)
  430. logger.plain(" %s %s%s", layer.ljust(20), ver, skipped)
  431. preffiles = []
  432. items_listed = False
  433. for p in sorted(pkg_pn):
  434. if pnspec:
  435. if not fnmatch.fnmatch(p, pnspec):
  436. continue
  437. if len(allproviders[p]) > 1 or not show_multi_provider_only:
  438. pref = preferred_versions[p]
  439. realfn = bb.cache.Cache.virtualfn2realfn(pref[1])
  440. preffile = realfn[0]
  441. # We only display once per recipe, we should prefer non extended versions of the
  442. # recipe if present (so e.g. in OpenEmbedded, openssl rather than nativesdk-openssl
  443. # which would otherwise sort first).
  444. if realfn[1] and realfn[0] in self.bbhandler.cooker.recipecache.pkg_fn:
  445. continue
  446. if preffile not in preffiles:
  447. preflayer = self.get_file_layer(preffile)
  448. multilayer = False
  449. same_ver = True
  450. provs = []
  451. for prov in allproviders[p]:
  452. provfile = bb.cache.Cache.virtualfn2realfn(prov[1])[0]
  453. provlayer = self.get_file_layer(provfile)
  454. provs.append((provfile, provlayer, prov[0]))
  455. if provlayer != preflayer:
  456. multilayer = True
  457. if prov[0] != pref[0]:
  458. same_ver = False
  459. if (multilayer or not show_overlayed_only) and (same_ver or not show_same_ver_only):
  460. if not items_listed:
  461. logger.plain('=== %s ===' % title)
  462. items_listed = True
  463. print_item(preffile, p, self.version_str(pref[0][0], pref[0][1]), preflayer, True)
  464. for (provfile, provlayer, provver) in provs:
  465. if provfile != preffile:
  466. print_item(provfile, p, self.version_str(provver[0], provver[1]), provlayer, False)
  467. # Ensure we don't show two entries for BBCLASSEXTENDed recipes
  468. preffiles.append(preffile)
  469. return items_listed
  470. def do_flatten(self, args):
  471. """flatten layer configuration into a separate output directory.
  472. Takes the specified layers (or all layers in the current layer
  473. configuration if none are specified) and builds a "flattened" directory
  474. containing the contents of all layers, with any overlayed recipes removed
  475. and bbappends appended to the corresponding recipes. Note that some manual
  476. cleanup may still be necessary afterwards, in particular:
  477. * where non-recipe files (such as patches) are overwritten (the flatten
  478. command will show a warning for these)
  479. * where anything beyond the normal layer setup has been added to
  480. layer.conf (only the lowest priority number layer's layer.conf is used)
  481. * overridden/appended items from bbappends will need to be tidied up
  482. * when the flattened layers do not have the same directory structure (the
  483. flatten command should show a warning when this will cause a problem)
  484. Warning: if you flatten several layers where another layer is intended to
  485. be used "inbetween" them (in layer priority order) such that recipes /
  486. bbappends in the layers interact, and then attempt to use the new output
  487. layer together with that other layer, you may no longer get the same
  488. build results (as the layer priority order has effectively changed).
  489. """
  490. if len(args.layer) == 1:
  491. logger.error('If you specify layers to flatten you must specify at least two')
  492. return 1
  493. outputdir = args.outputdir
  494. if os.path.exists(outputdir) and os.listdir(outputdir):
  495. logger.error('Directory %s exists and is non-empty, please clear it out first' % outputdir)
  496. return 1
  497. self.init_bbhandler()
  498. layers = self.bblayers
  499. if len(args.layer) > 2:
  500. layernames = args.layer
  501. found_layernames = []
  502. found_layerdirs = []
  503. for layerdir in layers:
  504. layername = self.get_layer_name(layerdir)
  505. if layername in layernames:
  506. found_layerdirs.append(layerdir)
  507. found_layernames.append(layername)
  508. for layername in layernames:
  509. if not layername in found_layernames:
  510. 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])))
  511. return
  512. layers = found_layerdirs
  513. else:
  514. layernames = []
  515. # Ensure a specified path matches our list of layers
  516. def layer_path_match(path):
  517. for layerdir in layers:
  518. if path.startswith(os.path.join(layerdir, '')):
  519. return layerdir
  520. return None
  521. applied_appends = []
  522. for layer in layers:
  523. overlayed = []
  524. for f in self.bbhandler.cooker.collection.overlayed.iterkeys():
  525. for of in self.bbhandler.cooker.collection.overlayed[f]:
  526. if of.startswith(layer):
  527. overlayed.append(of)
  528. logger.plain('Copying files from %s...' % layer )
  529. for root, dirs, files in os.walk(layer):
  530. for f1 in files:
  531. f1full = os.sep.join([root, f1])
  532. if f1full in overlayed:
  533. logger.plain(' Skipping overlayed file %s' % f1full )
  534. else:
  535. ext = os.path.splitext(f1)[1]
  536. if ext != '.bbappend':
  537. fdest = f1full[len(layer):]
  538. fdest = os.path.normpath(os.sep.join([outputdir,fdest]))
  539. bb.utils.mkdirhier(os.path.dirname(fdest))
  540. if os.path.exists(fdest):
  541. if f1 == 'layer.conf' and root.endswith('/conf'):
  542. logger.plain(' Skipping layer config file %s' % f1full )
  543. continue
  544. else:
  545. logger.warn('Overwriting file %s', fdest)
  546. bb.utils.copyfile(f1full, fdest)
  547. if ext == '.bb':
  548. for append in self.bbhandler.cooker.collection.get_file_appends(f1full):
  549. if layer_path_match(append):
  550. logger.plain(' Applying append %s to %s' % (append, fdest))
  551. self.apply_append(append, fdest)
  552. applied_appends.append(append)
  553. # Take care of when some layers are excluded and yet we have included bbappends for those recipes
  554. for b in self.bbhandler.cooker.collection.bbappends:
  555. (recipename, appendname) = b
  556. if appendname not in applied_appends:
  557. first_append = None
  558. layer = layer_path_match(appendname)
  559. if layer:
  560. if first_append:
  561. self.apply_append(appendname, first_append)
  562. else:
  563. fdest = appendname[len(layer):]
  564. fdest = os.path.normpath(os.sep.join([outputdir,fdest]))
  565. bb.utils.mkdirhier(os.path.dirname(fdest))
  566. bb.utils.copyfile(appendname, fdest)
  567. first_append = fdest
  568. # Get the regex for the first layer in our list (which is where the conf/layer.conf file will
  569. # have come from)
  570. first_regex = None
  571. layerdir = layers[0]
  572. for layername, pattern, regex, _ in self.bbhandler.cooker.recipecache.bbfile_config_priorities:
  573. if regex.match(os.path.join(layerdir, 'test')):
  574. first_regex = regex
  575. break
  576. if first_regex:
  577. # Find the BBFILES entries that match (which will have come from this conf/layer.conf file)
  578. bbfiles = str(self.bbhandler.config_data.getVar('BBFILES', True)).split()
  579. bbfiles_layer = []
  580. for item in bbfiles:
  581. if first_regex.match(item):
  582. newpath = os.path.join(outputdir, item[len(layerdir)+1:])
  583. bbfiles_layer.append(newpath)
  584. if bbfiles_layer:
  585. # Check that all important layer files match BBFILES
  586. for root, dirs, files in os.walk(outputdir):
  587. for f1 in files:
  588. ext = os.path.splitext(f1)[1]
  589. if ext in ['.bb', '.bbappend']:
  590. f1full = os.sep.join([root, f1])
  591. entry_found = False
  592. for item in bbfiles_layer:
  593. if fnmatch.fnmatch(f1full, item):
  594. entry_found = True
  595. break
  596. if not entry_found:
  597. 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)
  598. def get_file_layer(self, filename):
  599. for layer, _, regex, _ in self.bbhandler.cooker.recipecache.bbfile_config_priorities:
  600. if regex.match(filename):
  601. for layerdir in self.bblayers:
  602. if regex.match(os.path.join(layerdir, 'test')) and re.match(layerdir, filename):
  603. return self.get_layer_name(layerdir)
  604. return "?"
  605. def get_file_layerdir(self, filename):
  606. for layer, _, regex, _ in self.bbhandler.cooker.recipecache.bbfile_config_priorities:
  607. if regex.match(filename):
  608. for layerdir in self.bblayers:
  609. if regex.match(os.path.join(layerdir, 'test')) and re.match(layerdir, filename):
  610. return layerdir
  611. return "?"
  612. def remove_layer_prefix(self, f):
  613. """Remove the layer_dir prefix, e.g., f = /path/to/layer_dir/foo/blah, the
  614. return value will be: layer_dir/foo/blah"""
  615. f_layerdir = self.get_file_layerdir(f)
  616. prefix = os.path.join(os.path.dirname(f_layerdir), '')
  617. return f[len(prefix):] if f.startswith(prefix) else f
  618. def get_layer_name(self, layerdir):
  619. return os.path.basename(layerdir.rstrip(os.sep))
  620. def apply_append(self, appendname, recipename):
  621. with open(appendname, 'r') as appendfile:
  622. with open(recipename, 'a') as recipefile:
  623. recipefile.write('\n')
  624. recipefile.write('##### bbappended from %s #####\n' % self.get_file_layer(appendname))
  625. recipefile.writelines(appendfile.readlines())
  626. def do_show_appends(self, args):
  627. """list bbappend files and recipe files they apply to
  628. Lists recipes with the bbappends that apply to them as subitems.
  629. """
  630. self.init_bbhandler()
  631. logger.plain('=== Appended recipes ===')
  632. pnlist = list(self.bbhandler.cooker_data.pkg_pn.keys())
  633. pnlist.sort()
  634. appends = False
  635. for pn in pnlist:
  636. if self.show_appends_for_pn(pn):
  637. appends = True
  638. if self.show_appends_for_skipped():
  639. appends = True
  640. if not appends:
  641. logger.plain('No append files found')
  642. def show_appends_for_pn(self, pn):
  643. filenames = self.bbhandler.cooker_data.pkg_pn[pn]
  644. best = bb.providers.findBestProvider(pn,
  645. self.bbhandler.config_data,
  646. self.bbhandler.cooker_data,
  647. self.bbhandler.cooker_data.pkg_pn)
  648. best_filename = os.path.basename(best[3])
  649. return self.show_appends_output(filenames, best_filename)
  650. def show_appends_for_skipped(self):
  651. filenames = [os.path.basename(f)
  652. for f in self.bbhandler.cooker.skiplist.iterkeys()]
  653. return self.show_appends_output(filenames, None, " (skipped)")
  654. def show_appends_output(self, filenames, best_filename, name_suffix = ''):
  655. appended, missing = self.get_appends_for_files(filenames)
  656. if appended:
  657. for basename, appends in appended:
  658. logger.plain('%s%s:', basename, name_suffix)
  659. for append in appends:
  660. logger.plain(' %s', append)
  661. if best_filename:
  662. if best_filename in missing:
  663. logger.warn('%s: missing append for preferred version',
  664. best_filename)
  665. return True
  666. else:
  667. return False
  668. def get_appends_for_files(self, filenames):
  669. appended, notappended = [], []
  670. for filename in filenames:
  671. _, cls = bb.cache.Cache.virtualfn2realfn(filename)
  672. if cls:
  673. continue
  674. basename = os.path.basename(filename)
  675. appends = self.bbhandler.cooker.collection.get_file_appends(basename)
  676. if appends:
  677. appended.append((basename, list(appends)))
  678. else:
  679. notappended.append(basename)
  680. return appended, notappended
  681. def do_show_cross_depends(self, args):
  682. """Show dependencies between recipes that cross layer boundaries.
  683. Figure out the dependencies between recipes that cross layer boundaries.
  684. NOTE: .bbappend files can impact the dependencies.
  685. """
  686. ignore_layers = (args.ignore or '').split(',')
  687. self.init_bbhandler()
  688. pkg_fn = self.bbhandler.cooker_data.pkg_fn
  689. bbpath = str(self.bbhandler.config_data.getVar('BBPATH', True))
  690. self.require_re = re.compile(r"require\s+(.+)")
  691. self.include_re = re.compile(r"include\s+(.+)")
  692. self.inherit_re = re.compile(r"inherit\s+(.+)")
  693. global_inherit = (self.bbhandler.config_data.getVar('INHERIT', True) or "").split()
  694. # The bb's DEPENDS and RDEPENDS
  695. for f in pkg_fn:
  696. f = bb.cache.Cache.virtualfn2realfn(f)[0]
  697. # Get the layername that the file is in
  698. layername = self.get_file_layer(f)
  699. # The DEPENDS
  700. deps = self.bbhandler.cooker_data.deps[f]
  701. for pn in deps:
  702. if pn in self.bbhandler.cooker_data.pkg_pn:
  703. best = bb.providers.findBestProvider(pn,
  704. self.bbhandler.config_data,
  705. self.bbhandler.cooker_data,
  706. self.bbhandler.cooker_data.pkg_pn)
  707. self.check_cross_depends("DEPENDS", layername, f, best[3], args.filenames, ignore_layers)
  708. # The RDPENDS
  709. all_rdeps = self.bbhandler.cooker_data.rundeps[f].values()
  710. # Remove the duplicated or null one.
  711. sorted_rdeps = {}
  712. # The all_rdeps is the list in list, so we need two for loops
  713. for k1 in all_rdeps:
  714. for k2 in k1:
  715. sorted_rdeps[k2] = 1
  716. all_rdeps = sorted_rdeps.keys()
  717. for rdep in all_rdeps:
  718. all_p = bb.providers.getRuntimeProviders(self.bbhandler.cooker_data, rdep)
  719. if all_p:
  720. if f in all_p:
  721. # The recipe provides this one itself, ignore
  722. continue
  723. best = bb.providers.filterProvidersRunTime(all_p, rdep,
  724. self.bbhandler.config_data,
  725. self.bbhandler.cooker_data)[0][0]
  726. self.check_cross_depends("RDEPENDS", layername, f, best, args.filenames, ignore_layers)
  727. # The RRECOMMENDS
  728. all_rrecs = self.bbhandler.cooker_data.runrecs[f].values()
  729. # Remove the duplicated or null one.
  730. sorted_rrecs = {}
  731. # The all_rrecs is the list in list, so we need two for loops
  732. for k1 in all_rrecs:
  733. for k2 in k1:
  734. sorted_rrecs[k2] = 1
  735. all_rrecs = sorted_rrecs.keys()
  736. for rrec in all_rrecs:
  737. all_p = bb.providers.getRuntimeProviders(self.bbhandler.cooker_data, rrec)
  738. if all_p:
  739. if f in all_p:
  740. # The recipe provides this one itself, ignore
  741. continue
  742. best = bb.providers.filterProvidersRunTime(all_p, rrec,
  743. self.bbhandler.config_data,
  744. self.bbhandler.cooker_data)[0][0]
  745. self.check_cross_depends("RRECOMMENDS", layername, f, best, args.filenames, ignore_layers)
  746. # The inherit class
  747. cls_re = re.compile('classes/')
  748. if f in self.bbhandler.cooker_data.inherits:
  749. inherits = self.bbhandler.cooker_data.inherits[f]
  750. for cls in inherits:
  751. # The inherits' format is [classes/cls, /path/to/classes/cls]
  752. # ignore the classes/cls.
  753. if not cls_re.match(cls):
  754. classname = os.path.splitext(os.path.basename(cls))[0]
  755. if classname in global_inherit:
  756. continue
  757. inherit_layername = self.get_file_layer(cls)
  758. if inherit_layername != layername and not inherit_layername in ignore_layers:
  759. if not args.filenames:
  760. f_short = self.remove_layer_prefix(f)
  761. cls = self.remove_layer_prefix(cls)
  762. else:
  763. f_short = f
  764. logger.plain("%s inherits %s" % (f_short, cls))
  765. # The 'require/include xxx' in the bb file
  766. pv_re = re.compile(r"\${PV}")
  767. with open(f, 'r') as fnfile:
  768. line = fnfile.readline()
  769. while line:
  770. m, keyword = self.match_require_include(line)
  771. # Found the 'require/include xxxx'
  772. if m:
  773. needed_file = m.group(1)
  774. # Replace the ${PV} with the real PV
  775. if pv_re.search(needed_file) and f in self.bbhandler.cooker_data.pkg_pepvpr:
  776. pv = self.bbhandler.cooker_data.pkg_pepvpr[f][1]
  777. needed_file = re.sub(r"\${PV}", pv, needed_file)
  778. self.print_cross_files(bbpath, keyword, layername, f, needed_file, args.filenames, ignore_layers)
  779. line = fnfile.readline()
  780. # The "require/include xxx" in conf/machine/*.conf, .inc and .bbclass
  781. conf_re = re.compile(".*/conf/machine/[^\/]*\.conf$")
  782. inc_re = re.compile(".*\.inc$")
  783. # The "inherit xxx" in .bbclass
  784. bbclass_re = re.compile(".*\.bbclass$")
  785. for layerdir in self.bblayers:
  786. layername = self.get_layer_name(layerdir)
  787. for dirpath, dirnames, filenames in os.walk(layerdir):
  788. for name in filenames:
  789. f = os.path.join(dirpath, name)
  790. s = conf_re.match(f) or inc_re.match(f) or bbclass_re.match(f)
  791. if s:
  792. with open(f, 'r') as ffile:
  793. line = ffile.readline()
  794. while line:
  795. m, keyword = self.match_require_include(line)
  796. # Only bbclass has the "inherit xxx" here.
  797. bbclass=""
  798. if not m and f.endswith(".bbclass"):
  799. m, keyword = self.match_inherit(line)
  800. bbclass=".bbclass"
  801. # Find a 'require/include xxxx'
  802. if m:
  803. self.print_cross_files(bbpath, keyword, layername, f, m.group(1) + bbclass, args.filenames, ignore_layers)
  804. line = ffile.readline()
  805. def print_cross_files(self, bbpath, keyword, layername, f, needed_filename, show_filenames, ignore_layers):
  806. """Print the depends that crosses a layer boundary"""
  807. needed_file = bb.utils.which(bbpath, needed_filename)
  808. if needed_file:
  809. # Which layer is this file from
  810. needed_layername = self.get_file_layer(needed_file)
  811. if needed_layername != layername and not needed_layername in ignore_layers:
  812. if not show_filenames:
  813. f = self.remove_layer_prefix(f)
  814. needed_file = self.remove_layer_prefix(needed_file)
  815. logger.plain("%s %s %s" %(f, keyword, needed_file))
  816. def match_inherit(self, line):
  817. """Match the inherit xxx line"""
  818. return (self.inherit_re.match(line), "inherits")
  819. def match_require_include(self, line):
  820. """Match the require/include xxx line"""
  821. m = self.require_re.match(line)
  822. keyword = "requires"
  823. if not m:
  824. m = self.include_re.match(line)
  825. keyword = "includes"
  826. return (m, keyword)
  827. def check_cross_depends(self, keyword, layername, f, needed_file, show_filenames, ignore_layers):
  828. """Print the DEPENDS/RDEPENDS file that crosses a layer boundary"""
  829. best_realfn = bb.cache.Cache.virtualfn2realfn(needed_file)[0]
  830. needed_layername = self.get_file_layer(best_realfn)
  831. if needed_layername != layername and not needed_layername in ignore_layers:
  832. if not show_filenames:
  833. f = self.remove_layer_prefix(f)
  834. best_realfn = self.remove_layer_prefix(best_realfn)
  835. logger.plain("%s %s %s" % (f, keyword, best_realfn))
  836. def main():
  837. cmds = Commands()
  838. def add_command(cmdname, function, *args, **kwargs):
  839. # Convert docstring for function to help (one-liner shown in main --help) and description (shown in subcommand --help)
  840. docsplit = function.__doc__.splitlines()
  841. help = docsplit[0]
  842. if len(docsplit) > 1:
  843. desc = '\n'.join(docsplit[1:])
  844. else:
  845. desc = help
  846. subparser = subparsers.add_parser(cmdname, *args, help=help, description=desc, formatter_class=argparse.RawTextHelpFormatter, **kwargs)
  847. subparser.set_defaults(func=function)
  848. return subparser
  849. parser = argparse.ArgumentParser(description="BitBake layers utility",
  850. epilog="Use %(prog)s <subcommand> --help to get help on a specific command")
  851. parser.add_argument('-d', '--debug', help='Enable debug output', action='store_true')
  852. parser.add_argument('-q', '--quiet', help='Print only errors', action='store_true')
  853. subparsers = parser.add_subparsers(title='subcommands', metavar='<subcommand>')
  854. parser_show_layers = add_command('show-layers', cmds.do_show_layers)
  855. parser_add_layer = add_command('add-layer', cmds.do_add_layer)
  856. parser_add_layer.add_argument('layerdir', help='Layer directory to add')
  857. parser_remove_layer = add_command('remove-layer', cmds.do_remove_layer)
  858. parser_remove_layer.add_argument('layerdir', help='Layer directory to remove (wildcards allowed, enclose in quotes to avoid shell expansion)')
  859. parser_remove_layer.set_defaults(func=cmds.do_remove_layer)
  860. parser_show_overlayed = add_command('show-overlayed', cmds.do_show_overlayed)
  861. parser_show_overlayed.add_argument('-f', '--filenames', help='instead of the default formatting, list filenames of higher priority recipes with the ones they overlay indented underneath', action='store_true')
  862. parser_show_overlayed.add_argument('-s', '--same-version', help='only list overlayed recipes where the version is the same', action='store_true')
  863. parser_show_recipes = add_command('show-recipes', cmds.do_show_recipes)
  864. parser_show_recipes.add_argument('-f', '--filenames', help='instead of the default formatting, list filenames of higher priority recipes with the ones they overlay indented underneath', action='store_true')
  865. parser_show_recipes.add_argument('-m', '--multiple', help='only list where multiple recipes (in the same layer or different layers) exist for the same recipe name', action='store_true')
  866. parser_show_recipes.add_argument('pnspec', nargs='?', help='optional recipe name specification (wildcards allowed, enclose in quotes to avoid shell expansion)')
  867. parser_show_appends = add_command('show-appends', cmds.do_show_appends)
  868. parser_flatten = add_command('flatten', cmds.do_flatten)
  869. parser_flatten.add_argument('layer', nargs='*', help='Optional layer(s) to flatten (otherwise all are flattened)')
  870. parser_flatten.add_argument('outputdir', help='Output directory')
  871. parser_show_cross_depends = add_command('show-cross-depends', cmds.do_show_cross_depends)
  872. parser_show_cross_depends.add_argument('-f', '--filenames', help='show full file path', action='store_true')
  873. parser_show_cross_depends.add_argument('-i', '--ignore', help='ignore dependencies on items in the specified layer(s) (split multiple layer names with commas, no spaces)', metavar='LAYERNAME')
  874. parser_layerindex_fetch = add_command('layerindex-fetch', cmds.do_layerindex_fetch)
  875. parser_layerindex_fetch.add_argument('-n', '--show-only', help='show dependencies and do nothing else', action='store_true')
  876. parser_layerindex_fetch.add_argument('-b', '--branch', help='branch name to fetch (default %(default)s)', default='master')
  877. parser_layerindex_fetch.add_argument('-i', '--ignore', help='assume the specified layers do not need to be fetched/added (separate multiple layers with commas, no spaces)', metavar='LAYER')
  878. parser_layerindex_fetch.add_argument('layername', nargs='+', help='layer to fetch')
  879. parser_layerindex_show_depends = add_command('layerindex-show-depends', cmds.do_layerindex_show_depends)
  880. parser_layerindex_show_depends.add_argument('-b', '--branch', help='branch name to fetch (default %(default)s)', default='master')
  881. parser_layerindex_show_depends.add_argument('layername', nargs='+', help='layer to query')
  882. args = parser.parse_args()
  883. if args.debug:
  884. logger.setLevel(logging.DEBUG)
  885. elif args.quiet:
  886. logger.setLevel(logging.ERROR)
  887. ret = args.func(args)
  888. return ret
  889. if __name__ == "__main__":
  890. try:
  891. ret = main()
  892. except Exception:
  893. ret = 1
  894. import traceback
  895. traceback.print_exc(5)
  896. sys.exit(ret)