query.py 24 KB

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