bitbake-layers 48 KB

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