query.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. import collections
  2. import fnmatch
  3. import logging
  4. import sys
  5. import os
  6. import re
  7. import bb.cache
  8. import bb.providers
  9. import bb.utils
  10. from bblayers.common import LayerPlugin
  11. logger = logging.getLogger('bitbake-layers')
  12. def plugin_init(plugins):
  13. return QueryPlugin()
  14. class QueryPlugin(LayerPlugin):
  15. def do_show_layers(self, args):
  16. """show current configured layers."""
  17. logger.plain("%s %s %s" % ("layer".ljust(20), "path".ljust(40), "priority"))
  18. logger.plain('=' * 74)
  19. for layer, _, regex, pri in self.tinfoil.cooker.recipecache.bbfile_config_priorities:
  20. layerdir = self.bbfile_collections.get(layer, None)
  21. layername = self.get_layer_name(layerdir)
  22. logger.plain("%s %s %d" % (layername.ljust(20), layerdir.ljust(40), pri))
  23. def version_str(self, pe, pv, pr = None):
  24. verstr = "%s" % pv
  25. if pr:
  26. verstr = "%s-%s" % (verstr, pr)
  27. if pe:
  28. verstr = "%s:%s" % (pe, verstr)
  29. return verstr
  30. def do_show_overlayed(self, args):
  31. """list overlayed recipes (where the same recipe exists in another layer)
  32. Lists the names of overlayed recipes and the available versions in each
  33. layer, with the preferred version first. Note that skipped recipes that
  34. are overlayed will also be listed, with a " (skipped)" suffix.
  35. """
  36. items_listed = self.list_recipes('Overlayed recipes', None, True, args.same_version, args.filenames, True, None)
  37. # Check for overlayed .bbclass files
  38. classes = collections.defaultdict(list)
  39. for layerdir in self.bblayers:
  40. classdir = os.path.join(layerdir, 'classes')
  41. if os.path.exists(classdir):
  42. for classfile in os.listdir(classdir):
  43. if os.path.splitext(classfile)[1] == '.bbclass':
  44. classes[classfile].append(classdir)
  45. # Locating classes and other files is a bit more complicated than recipes -
  46. # layer priority is not a factor; instead BitBake uses the first matching
  47. # file in BBPATH, which is manipulated directly by each layer's
  48. # conf/layer.conf in turn, thus the order of layers in bblayers.conf is a
  49. # factor - however, each layer.conf is free to either prepend or append to
  50. # BBPATH (or indeed do crazy stuff with it). Thus the order in BBPATH might
  51. # not be exactly the order present in bblayers.conf either.
  52. bbpath = str(self.tinfoil.config_data.getVar('BBPATH', True))
  53. overlayed_class_found = False
  54. for (classfile, classdirs) in classes.items():
  55. if len(classdirs) > 1:
  56. if not overlayed_class_found:
  57. logger.plain('=== Overlayed classes ===')
  58. overlayed_class_found = True
  59. mainfile = bb.utils.which(bbpath, os.path.join('classes', classfile))
  60. if args.filenames:
  61. logger.plain('%s' % mainfile)
  62. else:
  63. # We effectively have to guess the layer here
  64. logger.plain('%s:' % classfile)
  65. mainlayername = '?'
  66. for layerdir in self.bblayers:
  67. classdir = os.path.join(layerdir, 'classes')
  68. if mainfile.startswith(classdir):
  69. mainlayername = self.get_layer_name(layerdir)
  70. logger.plain(' %s' % mainlayername)
  71. for classdir in classdirs:
  72. fullpath = os.path.join(classdir, classfile)
  73. if fullpath != mainfile:
  74. if args.filenames:
  75. print(' %s' % fullpath)
  76. else:
  77. print(' %s' % self.get_layer_name(os.path.dirname(classdir)))
  78. if overlayed_class_found:
  79. items_listed = True;
  80. if not items_listed:
  81. logger.plain('No overlayed files found.')
  82. def do_show_recipes(self, args):
  83. """list available recipes, showing the layer they are provided by
  84. Lists the names of recipes and the available versions in each
  85. layer, with the preferred version first. Optionally you may specify
  86. pnspec to match a specified recipe name (supports wildcards). Note that
  87. skipped recipes will also be listed, with a " (skipped)" suffix.
  88. """
  89. inheritlist = args.inherits.split(',') if args.inherits else []
  90. if inheritlist or args.pnspec or args.multiple:
  91. title = 'Matching recipes:'
  92. else:
  93. title = 'Available recipes:'
  94. self.list_recipes(title, args.pnspec, False, False, args.filenames, args.multiple, inheritlist)
  95. def list_recipes(self, title, pnspec, show_overlayed_only, show_same_ver_only, show_filenames, show_multi_provider_only, inherits):
  96. if inherits:
  97. bbpath = str(self.tinfoil.config_data.getVar('BBPATH', True))
  98. for classname in inherits:
  99. classfile = 'classes/%s.bbclass' % classname
  100. if not bb.utils.which(bbpath, classfile, history=False):
  101. logger.error('No class named %s found in BBPATH', classfile)
  102. sys.exit(1)
  103. pkg_pn = self.tinfoil.cooker.recipecache.pkg_pn
  104. (latest_versions, preferred_versions) = bb.providers.findProviders(self.tinfoil.config_data, self.tinfoil.cooker.recipecache, pkg_pn)
  105. allproviders = bb.providers.allProviders(self.tinfoil.cooker.recipecache)
  106. # Ensure we list skipped recipes
  107. # We are largely guessing about PN, PV and the preferred version here,
  108. # but we have no choice since skipped recipes are not fully parsed
  109. skiplist = list(self.tinfoil.cooker.skiplist.keys())
  110. skiplist.sort( key=lambda fileitem: self.tinfoil.cooker.collection.calc_bbfile_priority(fileitem) )
  111. skiplist.reverse()
  112. for fn in skiplist:
  113. recipe_parts = os.path.splitext(os.path.basename(fn))[0].split('_')
  114. p = recipe_parts[0]
  115. if len(recipe_parts) > 1:
  116. ver = (None, recipe_parts[1], None)
  117. else:
  118. ver = (None, 'unknown', None)
  119. allproviders[p].append((ver, fn))
  120. if not p in pkg_pn:
  121. pkg_pn[p] = 'dummy'
  122. preferred_versions[p] = (ver, fn)
  123. def print_item(f, pn, ver, layer, ispref):
  124. if f in skiplist:
  125. skipped = ' (skipped)'
  126. else:
  127. skipped = ''
  128. if show_filenames:
  129. if ispref:
  130. logger.plain("%s%s", f, skipped)
  131. else:
  132. logger.plain(" %s%s", f, skipped)
  133. else:
  134. if ispref:
  135. logger.plain("%s:", pn)
  136. logger.plain(" %s %s%s", layer.ljust(20), ver, skipped)
  137. global_inherit = (self.tinfoil.config_data.getVar('INHERIT', True) or "").split()
  138. cls_re = re.compile('classes/')
  139. preffiles = []
  140. items_listed = False
  141. for p in sorted(pkg_pn):
  142. if pnspec:
  143. if not fnmatch.fnmatch(p, pnspec):
  144. continue
  145. if len(allproviders[p]) > 1 or not show_multi_provider_only:
  146. pref = preferred_versions[p]
  147. realfn = bb.cache.Cache.virtualfn2realfn(pref[1])
  148. preffile = realfn[0]
  149. # We only display once per recipe, we should prefer non extended versions of the
  150. # recipe if present (so e.g. in OpenEmbedded, openssl rather than nativesdk-openssl
  151. # which would otherwise sort first).
  152. if realfn[1] and realfn[0] in self.tinfoil.cooker.recipecache.pkg_fn:
  153. continue
  154. if inherits:
  155. matchcount = 0
  156. recipe_inherits = self.tinfoil.cooker_data.inherits.get(preffile, [])
  157. for cls in recipe_inherits:
  158. if cls_re.match(cls):
  159. continue
  160. classname = os.path.splitext(os.path.basename(cls))[0]
  161. if classname in global_inherit:
  162. continue
  163. elif classname in inherits:
  164. matchcount += 1
  165. if matchcount != len(inherits):
  166. # No match - skip this recipe
  167. continue
  168. if preffile not in preffiles:
  169. preflayer = self.get_file_layer(preffile)
  170. multilayer = False
  171. same_ver = True
  172. provs = []
  173. for prov in allproviders[p]:
  174. provfile = bb.cache.Cache.virtualfn2realfn(prov[1])[0]
  175. provlayer = self.get_file_layer(provfile)
  176. provs.append((provfile, provlayer, prov[0]))
  177. if provlayer != preflayer:
  178. multilayer = True
  179. if prov[0] != pref[0]:
  180. same_ver = False
  181. if (multilayer or not show_overlayed_only) and (same_ver or not show_same_ver_only):
  182. if not items_listed:
  183. logger.plain('=== %s ===' % title)
  184. items_listed = True
  185. print_item(preffile, p, self.version_str(pref[0][0], pref[0][1]), preflayer, True)
  186. for (provfile, provlayer, provver) in provs:
  187. if provfile != preffile:
  188. print_item(provfile, p, self.version_str(provver[0], provver[1]), provlayer, False)
  189. # Ensure we don't show two entries for BBCLASSEXTENDed recipes
  190. preffiles.append(preffile)
  191. return items_listed
  192. def get_file_layer(self, filename):
  193. layerdir = self.get_file_layerdir(filename)
  194. if layerdir:
  195. return self.get_layer_name(layerdir)
  196. else:
  197. return '?'
  198. def get_file_layerdir(self, filename):
  199. layer = bb.utils.get_file_layer(filename, self.tinfoil.config_data)
  200. return self.bbfile_collections.get(layer, None)
  201. def remove_layer_prefix(self, f):
  202. """Remove the layer_dir prefix, e.g., f = /path/to/layer_dir/foo/blah, the
  203. return value will be: layer_dir/foo/blah"""
  204. f_layerdir = self.get_file_layerdir(f)
  205. if not f_layerdir:
  206. return f
  207. prefix = os.path.join(os.path.dirname(f_layerdir), '')
  208. return f[len(prefix):] if f.startswith(prefix) else f
  209. def do_show_appends(self, args):
  210. """list bbappend files and recipe files they apply to
  211. Lists recipes with the bbappends that apply to them as subitems.
  212. """
  213. logger.plain('=== Appended recipes ===')
  214. pnlist = list(self.tinfoil.cooker_data.pkg_pn.keys())
  215. pnlist.sort()
  216. appends = False
  217. for pn in pnlist:
  218. if self.show_appends_for_pn(pn):
  219. appends = True
  220. if self.show_appends_for_skipped():
  221. appends = True
  222. if not appends:
  223. logger.plain('No append files found')
  224. def show_appends_for_pn(self, pn):
  225. filenames = self.tinfoil.cooker_data.pkg_pn[pn]
  226. best = bb.providers.findBestProvider(pn,
  227. self.tinfoil.config_data,
  228. self.tinfoil.cooker_data,
  229. self.tinfoil.cooker_data.pkg_pn)
  230. best_filename = os.path.basename(best[3])
  231. return self.show_appends_output(filenames, best_filename)
  232. def show_appends_for_skipped(self):
  233. filenames = [os.path.basename(f)
  234. for f in self.tinfoil.cooker.skiplist.keys()]
  235. return self.show_appends_output(filenames, None, " (skipped)")
  236. def show_appends_output(self, filenames, best_filename, name_suffix = ''):
  237. appended, missing = self.get_appends_for_files(filenames)
  238. if appended:
  239. for basename, appends in appended:
  240. logger.plain('%s%s:', basename, name_suffix)
  241. for append in appends:
  242. logger.plain(' %s', append)
  243. if best_filename:
  244. if best_filename in missing:
  245. logger.warning('%s: missing append for preferred version',
  246. best_filename)
  247. return True
  248. else:
  249. return False
  250. def get_appends_for_files(self, filenames):
  251. appended, notappended = [], []
  252. for filename in filenames:
  253. _, cls = bb.cache.Cache.virtualfn2realfn(filename)
  254. if cls:
  255. continue
  256. basename = os.path.basename(filename)
  257. appends = self.tinfoil.cooker.collection.get_file_appends(basename)
  258. if appends:
  259. appended.append((basename, list(appends)))
  260. else:
  261. notappended.append(basename)
  262. return appended, notappended
  263. def do_show_cross_depends(self, args):
  264. """Show dependencies between recipes that cross layer boundaries.
  265. Figure out the dependencies between recipes that cross layer boundaries.
  266. NOTE: .bbappend files can impact the dependencies.
  267. """
  268. ignore_layers = (args.ignore or '').split(',')
  269. pkg_fn = self.tinfoil.cooker_data.pkg_fn
  270. bbpath = str(self.tinfoil.config_data.getVar('BBPATH', True))
  271. self.require_re = re.compile(r"require\s+(.+)")
  272. self.include_re = re.compile(r"include\s+(.+)")
  273. self.inherit_re = re.compile(r"inherit\s+(.+)")
  274. global_inherit = (self.tinfoil.config_data.getVar('INHERIT', True) or "").split()
  275. # The bb's DEPENDS and RDEPENDS
  276. for f in pkg_fn:
  277. f = bb.cache.Cache.virtualfn2realfn(f)[0]
  278. # Get the layername that the file is in
  279. layername = self.get_file_layer(f)
  280. # The DEPENDS
  281. deps = self.tinfoil.cooker_data.deps[f]
  282. for pn in deps:
  283. if pn in self.tinfoil.cooker_data.pkg_pn:
  284. best = bb.providers.findBestProvider(pn,
  285. self.tinfoil.config_data,
  286. self.tinfoil.cooker_data,
  287. self.tinfoil.cooker_data.pkg_pn)
  288. self.check_cross_depends("DEPENDS", layername, f, best[3], args.filenames, ignore_layers)
  289. # The RDPENDS
  290. all_rdeps = self.tinfoil.cooker_data.rundeps[f].values()
  291. # Remove the duplicated or null one.
  292. sorted_rdeps = {}
  293. # The all_rdeps is the list in list, so we need two for loops
  294. for k1 in all_rdeps:
  295. for k2 in k1:
  296. sorted_rdeps[k2] = 1
  297. all_rdeps = sorted_rdeps.keys()
  298. for rdep in all_rdeps:
  299. all_p = bb.providers.getRuntimeProviders(self.tinfoil.cooker_data, rdep)
  300. if all_p:
  301. if f in all_p:
  302. # The recipe provides this one itself, ignore
  303. continue
  304. best = bb.providers.filterProvidersRunTime(all_p, rdep,
  305. self.tinfoil.config_data,
  306. self.tinfoil.cooker_data)[0][0]
  307. self.check_cross_depends("RDEPENDS", layername, f, best, args.filenames, ignore_layers)
  308. # The RRECOMMENDS
  309. all_rrecs = self.tinfoil.cooker_data.runrecs[f].values()
  310. # Remove the duplicated or null one.
  311. sorted_rrecs = {}
  312. # The all_rrecs is the list in list, so we need two for loops
  313. for k1 in all_rrecs:
  314. for k2 in k1:
  315. sorted_rrecs[k2] = 1
  316. all_rrecs = sorted_rrecs.keys()
  317. for rrec in all_rrecs:
  318. all_p = bb.providers.getRuntimeProviders(self.tinfoil.cooker_data, rrec)
  319. if all_p:
  320. if f in all_p:
  321. # The recipe provides this one itself, ignore
  322. continue
  323. best = bb.providers.filterProvidersRunTime(all_p, rrec,
  324. self.tinfoil.config_data,
  325. self.tinfoil.cooker_data)[0][0]
  326. self.check_cross_depends("RRECOMMENDS", layername, f, best, args.filenames, ignore_layers)
  327. # The inherit class
  328. cls_re = re.compile('classes/')
  329. if f in self.tinfoil.cooker_data.inherits:
  330. inherits = self.tinfoil.cooker_data.inherits[f]
  331. for cls in inherits:
  332. # The inherits' format is [classes/cls, /path/to/classes/cls]
  333. # ignore the classes/cls.
  334. if not cls_re.match(cls):
  335. classname = os.path.splitext(os.path.basename(cls))[0]
  336. if classname in global_inherit:
  337. continue
  338. inherit_layername = self.get_file_layer(cls)
  339. if inherit_layername != layername and not inherit_layername in ignore_layers:
  340. if not args.filenames:
  341. f_short = self.remove_layer_prefix(f)
  342. cls = self.remove_layer_prefix(cls)
  343. else:
  344. f_short = f
  345. logger.plain("%s inherits %s" % (f_short, cls))
  346. # The 'require/include xxx' in the bb file
  347. pv_re = re.compile(r"\${PV}")
  348. with open(f, 'r') as fnfile:
  349. line = fnfile.readline()
  350. while line:
  351. m, keyword = self.match_require_include(line)
  352. # Found the 'require/include xxxx'
  353. if m:
  354. needed_file = m.group(1)
  355. # Replace the ${PV} with the real PV
  356. if pv_re.search(needed_file) and f in self.tinfoil.cooker_data.pkg_pepvpr:
  357. pv = self.tinfoil.cooker_data.pkg_pepvpr[f][1]
  358. needed_file = re.sub(r"\${PV}", pv, needed_file)
  359. self.print_cross_files(bbpath, keyword, layername, f, needed_file, args.filenames, ignore_layers)
  360. line = fnfile.readline()
  361. # The "require/include xxx" in conf/machine/*.conf, .inc and .bbclass
  362. conf_re = re.compile(".*/conf/machine/[^\/]*\.conf$")
  363. inc_re = re.compile(".*\.inc$")
  364. # The "inherit xxx" in .bbclass
  365. bbclass_re = re.compile(".*\.bbclass$")
  366. for layerdir in self.bblayers:
  367. layername = self.get_layer_name(layerdir)
  368. for dirpath, dirnames, filenames in os.walk(layerdir):
  369. for name in filenames:
  370. f = os.path.join(dirpath, name)
  371. s = conf_re.match(f) or inc_re.match(f) or bbclass_re.match(f)
  372. if s:
  373. with open(f, 'r') as ffile:
  374. line = ffile.readline()
  375. while line:
  376. m, keyword = self.match_require_include(line)
  377. # Only bbclass has the "inherit xxx" here.
  378. bbclass=""
  379. if not m and f.endswith(".bbclass"):
  380. m, keyword = self.match_inherit(line)
  381. bbclass=".bbclass"
  382. # Find a 'require/include xxxx'
  383. if m:
  384. self.print_cross_files(bbpath, keyword, layername, f, m.group(1) + bbclass, args.filenames, ignore_layers)
  385. line = ffile.readline()
  386. def print_cross_files(self, bbpath, keyword, layername, f, needed_filename, show_filenames, ignore_layers):
  387. """Print the depends that crosses a layer boundary"""
  388. needed_file = bb.utils.which(bbpath, needed_filename)
  389. if needed_file:
  390. # Which layer is this file from
  391. needed_layername = self.get_file_layer(needed_file)
  392. if needed_layername != layername and not needed_layername in ignore_layers:
  393. if not show_filenames:
  394. f = self.remove_layer_prefix(f)
  395. needed_file = self.remove_layer_prefix(needed_file)
  396. logger.plain("%s %s %s" %(f, keyword, needed_file))
  397. def match_inherit(self, line):
  398. """Match the inherit xxx line"""
  399. return (self.inherit_re.match(line), "inherits")
  400. def match_require_include(self, line):
  401. """Match the require/include xxx line"""
  402. m = self.require_re.match(line)
  403. keyword = "requires"
  404. if not m:
  405. m = self.include_re.match(line)
  406. keyword = "includes"
  407. return (m, keyword)
  408. def check_cross_depends(self, keyword, layername, f, needed_file, show_filenames, ignore_layers):
  409. """Print the DEPENDS/RDEPENDS file that crosses a layer boundary"""
  410. best_realfn = bb.cache.Cache.virtualfn2realfn(needed_file)[0]
  411. needed_layername = self.get_file_layer(best_realfn)
  412. if needed_layername != layername and not needed_layername in ignore_layers:
  413. if not show_filenames:
  414. f = self.remove_layer_prefix(f)
  415. best_realfn = self.remove_layer_prefix(best_realfn)
  416. logger.plain("%s %s %s" % (f, keyword, best_realfn))
  417. def register_commands(self, sp):
  418. self.add_command(sp, 'show-layers', self.do_show_layers)
  419. parser_show_overlayed = self.add_command(sp, 'show-overlayed', self.do_show_overlayed)
  420. 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')
  421. parser_show_overlayed.add_argument('-s', '--same-version', help='only list overlayed recipes where the version is the same', action='store_true')
  422. parser_show_recipes = self.add_command(sp, 'show-recipes', self.do_show_recipes)
  423. 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')
  424. 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')
  425. parser_show_recipes.add_argument('-i', '--inherits', help='only list recipes that inherit the named class', metavar='CLASS', default='')
  426. parser_show_recipes.add_argument('pnspec', nargs='?', help='optional recipe name specification (wildcards allowed, enclose in quotes to avoid shell expansion)')
  427. self.add_command(sp, 'show-appends', self.do_show_appends)
  428. parser_show_cross_depends = self.add_command(sp, 'show-cross-depends', self.do_show_cross_depends)
  429. parser_show_cross_depends.add_argument('-f', '--filenames', help='show full file path', action='store_true')
  430. 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')