oe-pkgdata-util 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. #!/usr/bin/env python
  2. # OpenEmbedded pkgdata utility
  3. #
  4. # Written by: Paul Eggleton <paul.eggleton@linux.intel.com>
  5. #
  6. # Copyright 2012-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. #
  21. import sys
  22. import os
  23. import os.path
  24. import fnmatch
  25. import re
  26. import argparse
  27. import logging
  28. from collections import defaultdict, OrderedDict
  29. scripts_path = os.path.dirname(os.path.realpath(__file__))
  30. lib_path = scripts_path + '/lib'
  31. sys.path = sys.path + [lib_path]
  32. import scriptutils
  33. logger = scriptutils.logger_create('pkgdatautil')
  34. def tinfoil_init():
  35. import bb.tinfoil
  36. import logging
  37. tinfoil = bb.tinfoil.Tinfoil()
  38. tinfoil.prepare(True)
  39. tinfoil.logger.setLevel(logging.WARNING)
  40. return tinfoil
  41. def glob(args):
  42. # Handle both multiple arguments and multiple values within an arg (old syntax)
  43. globs = []
  44. for globitem in args.glob:
  45. globs.extend(globitem.split())
  46. if not os.path.exists(args.pkglistfile):
  47. logger.error('Unable to find package list file %s' % args.pkglistfile)
  48. sys.exit(1)
  49. skipval = "-locale-|^locale-base-|-dev$|-doc$|-dbg$|-staticdev$|^kernel-module-"
  50. if args.exclude:
  51. skipval += "|" + args.exclude
  52. skipregex = re.compile(skipval)
  53. skippedpkgs = set()
  54. mappedpkgs = set()
  55. with open(args.pkglistfile, 'r') as f:
  56. for line in f:
  57. fields = line.rstrip().split()
  58. if not fields:
  59. continue
  60. pkg = fields[0]
  61. # We don't care about other args (used to need the package architecture but the
  62. # new pkgdata structure avoids the need for that)
  63. # Skip packages for which there is no point applying globs
  64. if skipregex.search(pkg):
  65. logger.debug("%s -> !!" % pkg)
  66. skippedpkgs.add(pkg)
  67. continue
  68. # Skip packages that already match the globs, so if e.g. a dev package
  69. # is already installed and thus in the list, we don't process it any further
  70. # Most of these will be caught by skipregex already, but just in case...
  71. already = False
  72. for g in globs:
  73. if fnmatch.fnmatchcase(pkg, g):
  74. already = True
  75. break
  76. if already:
  77. skippedpkgs.add(pkg)
  78. logger.debug("%s -> !" % pkg)
  79. continue
  80. # Define some functions
  81. def revpkgdata(pkgn):
  82. return os.path.join(args.pkgdata_dir, "runtime-reverse", pkgn)
  83. def fwdpkgdata(pkgn):
  84. return os.path.join(args.pkgdata_dir, "runtime", pkgn)
  85. def readpn(pkgdata_file):
  86. pn = ""
  87. with open(pkgdata_file, 'r') as f:
  88. for line in f:
  89. if line.startswith("PN:"):
  90. pn = line.split(': ')[1].rstrip()
  91. return pn
  92. def readrenamed(pkgdata_file):
  93. renamed = ""
  94. pn = os.path.basename(pkgdata_file)
  95. with open(pkgdata_file, 'r') as f:
  96. for line in f:
  97. if line.startswith("PKG_%s:" % pn):
  98. renamed = line.split(': ')[1].rstrip()
  99. return renamed
  100. # Main processing loop
  101. for g in globs:
  102. mappedpkg = ""
  103. # First just try substitution (i.e. packagename -> packagename-dev)
  104. newpkg = g.replace("*", pkg)
  105. revlink = revpkgdata(newpkg)
  106. if os.path.exists(revlink):
  107. mappedpkg = os.path.basename(os.readlink(revlink))
  108. fwdfile = fwdpkgdata(mappedpkg)
  109. if os.path.exists(fwdfile):
  110. mappedpkg = readrenamed(fwdfile)
  111. if not os.path.exists(fwdfile + ".packaged"):
  112. mappedpkg = ""
  113. else:
  114. revlink = revpkgdata(pkg)
  115. if os.path.exists(revlink):
  116. # Check if we can map after undoing the package renaming (by resolving the symlink)
  117. origpkg = os.path.basename(os.readlink(revlink))
  118. newpkg = g.replace("*", origpkg)
  119. fwdfile = fwdpkgdata(newpkg)
  120. if os.path.exists(fwdfile):
  121. mappedpkg = readrenamed(fwdfile)
  122. else:
  123. # That didn't work, so now get the PN, substitute that, then map in the other direction
  124. pn = readpn(revlink)
  125. newpkg = g.replace("*", pn)
  126. fwdfile = fwdpkgdata(newpkg)
  127. if os.path.exists(fwdfile):
  128. mappedpkg = readrenamed(fwdfile)
  129. if not os.path.exists(fwdfile + ".packaged"):
  130. mappedpkg = ""
  131. else:
  132. # Package doesn't even exist...
  133. logger.debug("%s is not a valid package!" % (pkg))
  134. break
  135. if mappedpkg:
  136. logger.debug("%s (%s) -> %s" % (pkg, g, mappedpkg))
  137. mappedpkgs.add(mappedpkg)
  138. else:
  139. logger.debug("%s (%s) -> ?" % (pkg, g))
  140. logger.debug("------")
  141. print("\n".join(mappedpkgs - skippedpkgs))
  142. def read_value(args):
  143. # Handle both multiple arguments and multiple values within an arg (old syntax)
  144. packages = []
  145. for pkgitem in args.pkg:
  146. packages.extend(pkgitem.split())
  147. def readvar(pkgdata_file, valuename):
  148. val = ""
  149. with open(pkgdata_file, 'r') as f:
  150. for line in f:
  151. if line.startswith(valuename + ":"):
  152. val = line.split(': ', 1)[1].rstrip()
  153. return val
  154. logger.debug("read-value('%s', '%s' '%s'" % (args.pkgdata_dir, args.valuename, packages))
  155. for package in packages:
  156. pkg_split = package.split('_')
  157. pkg_name = pkg_split[0]
  158. logger.debug("package: '%s'" % pkg_name)
  159. revlink = os.path.join(args.pkgdata_dir, "runtime-reverse", pkg_name)
  160. logger.debug(revlink)
  161. if os.path.exists(revlink):
  162. mappedpkg = os.path.basename(os.readlink(revlink))
  163. qvar = args.valuename
  164. if qvar == "PKGSIZE":
  165. # append packagename
  166. qvar = "%s_%s" % (args.valuename, mappedpkg)
  167. # PKGSIZE is now in bytes, but we we want it in KB
  168. pkgsize = (int(readvar(revlink, qvar)) + 1024 // 2) // 1024
  169. print("%d" % pkgsize)
  170. else:
  171. print(readvar(revlink, qvar))
  172. def lookup_pkglist(pkgs, pkgdata_dir, reverse):
  173. if reverse:
  174. mappings = OrderedDict()
  175. for pkg in pkgs:
  176. revlink = os.path.join(pkgdata_dir, "runtime-reverse", pkg)
  177. logger.debug(revlink)
  178. if os.path.exists(revlink):
  179. mappings[pkg] = os.path.basename(os.readlink(revlink))
  180. else:
  181. mappings = defaultdict(list)
  182. for pkg in pkgs:
  183. pkgfile = os.path.join(pkgdata_dir, 'runtime', pkg)
  184. if os.path.exists(pkgfile):
  185. with open(pkgfile, 'r') as f:
  186. for line in f:
  187. fields = line.rstrip().split(': ')
  188. if fields[0] == 'PKG_%s' % pkg:
  189. mappings[pkg].append(fields[1])
  190. break
  191. return mappings
  192. def lookup_pkg(args):
  193. # Handle both multiple arguments and multiple values within an arg (old syntax)
  194. pkgs = []
  195. for pkgitem in args.pkg:
  196. pkgs.extend(pkgitem.split())
  197. mappings = lookup_pkglist(pkgs, args.pkgdata_dir, args.reverse)
  198. if len(mappings) < len(pkgs):
  199. missing = list(set(pkgs) - set(mappings.keys()))
  200. logger.error("The following packages could not be found: %s" % ', '.join(missing))
  201. sys.exit(1)
  202. if args.reverse:
  203. items = mappings.values()
  204. else:
  205. items = []
  206. for pkg in pkgs:
  207. items.extend(mappings.get(pkg, []))
  208. print('\n'.join(items))
  209. def lookup_recipe(args):
  210. # Handle both multiple arguments and multiple values within an arg (old syntax)
  211. pkgs = []
  212. for pkgitem in args.pkg:
  213. pkgs.extend(pkgitem.split())
  214. mappings = defaultdict(list)
  215. for pkg in pkgs:
  216. pkgfile = os.path.join(args.pkgdata_dir, 'runtime-reverse', pkg)
  217. if os.path.exists(pkgfile):
  218. with open(pkgfile, 'r') as f:
  219. for line in f:
  220. fields = line.rstrip().split(': ')
  221. if fields[0] == 'PN':
  222. mappings[pkg].append(fields[1])
  223. break
  224. if len(mappings) < len(pkgs):
  225. missing = list(set(pkgs) - set(mappings.keys()))
  226. logger.error("The following packages could not be found: %s" % ', '.join(missing))
  227. sys.exit(1)
  228. items = []
  229. for pkg in pkgs:
  230. items.extend(mappings.get(pkg, []))
  231. print('\n'.join(items))
  232. def get_recipe_pkgs(pkgdata_dir, recipe, unpackaged):
  233. recipedatafile = os.path.join(pkgdata_dir, recipe)
  234. if not os.path.exists(recipedatafile):
  235. logger.error("Unable to find packaged recipe with name %s" % recipe)
  236. sys.exit(1)
  237. packages = []
  238. with open(recipedatafile, 'r') as f:
  239. for line in f:
  240. fields = line.rstrip().split(': ')
  241. if fields[0] == 'PACKAGES':
  242. packages = fields[1].split()
  243. break
  244. if not unpackaged:
  245. pkglist = []
  246. for pkg in packages:
  247. if os.path.exists(os.path.join(pkgdata_dir, 'runtime', '%s.packaged' % pkg)):
  248. pkglist.append(pkg)
  249. return pkglist
  250. else:
  251. return packages
  252. def list_pkgs(args):
  253. found = False
  254. def matchpkg(pkg):
  255. if args.pkgspec:
  256. matched = False
  257. for pkgspec in args.pkgspec:
  258. if fnmatch.fnmatchcase(pkg, pkgspec):
  259. matched = True
  260. break
  261. if not matched:
  262. return False
  263. if not args.unpackaged:
  264. if args.runtime:
  265. revlink = os.path.join(args.pkgdata_dir, "runtime-reverse", pkg)
  266. if os.path.exists(revlink):
  267. # We're unlikely to get here if the package was not packaged, but just in case
  268. # we add the symlinks for unpackaged files in the future
  269. mappedpkg = os.path.basename(os.readlink(revlink))
  270. if not os.path.exists(os.path.join(args.pkgdata_dir, 'runtime', '%s.packaged' % mappedpkg)):
  271. return False
  272. else:
  273. return False
  274. else:
  275. if not os.path.exists(os.path.join(args.pkgdata_dir, 'runtime', '%s.packaged' % pkg)):
  276. return False
  277. return True
  278. if args.recipe:
  279. packages = get_recipe_pkgs(args.pkgdata_dir, args.recipe, args.unpackaged)
  280. if args.runtime:
  281. pkglist = []
  282. runtime_pkgs = lookup_pkglist(packages, args.pkgdata_dir, False)
  283. for rtpkgs in runtime_pkgs.values():
  284. pkglist.extend(rtpkgs)
  285. else:
  286. pkglist = packages
  287. for pkg in pkglist:
  288. if matchpkg(pkg):
  289. found = True
  290. print("%s" % pkg)
  291. else:
  292. if args.runtime:
  293. searchdir = 'runtime-reverse'
  294. else:
  295. searchdir = 'runtime'
  296. for root, dirs, files in os.walk(os.path.join(args.pkgdata_dir, searchdir)):
  297. for fn in files:
  298. if fn.endswith('.packaged'):
  299. continue
  300. if matchpkg(fn):
  301. found = True
  302. print("%s" % fn)
  303. if not found:
  304. if args.pkgspec:
  305. logger.error("Unable to find any package matching %s" % args.pkgspec)
  306. else:
  307. logger.error("No packages found")
  308. sys.exit(1)
  309. def list_pkg_files(args):
  310. import json
  311. if args.recipe:
  312. if args.pkg:
  313. logger.error("list-pkg-files: If -p/--recipe is specified then a package name cannot be specified")
  314. sys.exit(1)
  315. recipepkglist = get_recipe_pkgs(args.pkgdata_dir, args.recipe, args.unpackaged)
  316. if args.runtime:
  317. pkglist = []
  318. runtime_pkgs = lookup_pkglist(recipepkglist, args.pkgdata_dir, False)
  319. for rtpkgs in runtime_pkgs.values():
  320. pkglist.extend(rtpkgs)
  321. else:
  322. pkglist = recipepkglist
  323. else:
  324. if not args.pkg:
  325. logger.error("list-pkg-files: If -p/--recipe is not specified then at least one package name must be specified")
  326. sys.exit(1)
  327. pkglist = args.pkg
  328. for pkg in pkglist:
  329. print("%s:" % pkg)
  330. if args.runtime:
  331. pkgdatafile = os.path.join(args.pkgdata_dir, "runtime-reverse", pkg)
  332. if not os.path.exists(pkgdatafile):
  333. if args.recipe:
  334. # This package was empty and thus never packaged, ignore
  335. continue
  336. logger.error("Unable to find any built runtime package named %s" % pkg)
  337. sys.exit(1)
  338. else:
  339. pkgdatafile = os.path.join(args.pkgdata_dir, "runtime", pkg)
  340. if not os.path.exists(pkgdatafile):
  341. logger.error("Unable to find any built recipe-space package named %s" % pkg)
  342. sys.exit(1)
  343. with open(pkgdatafile, 'r') as f:
  344. found = False
  345. for line in f:
  346. if line.startswith('FILES_INFO:'):
  347. found = True
  348. val = line.split(':', 1)[1].strip()
  349. dictval = json.loads(val)
  350. for fullpth in sorted(dictval):
  351. print("\t%s" % fullpth)
  352. break
  353. if not found:
  354. logger.error("Unable to find FILES_INFO entry in %s" % pkgdatafile)
  355. sys.exit(1)
  356. def find_path(args):
  357. import json
  358. found = False
  359. for root, dirs, files in os.walk(os.path.join(args.pkgdata_dir, 'runtime')):
  360. for fn in files:
  361. with open(os.path.join(root,fn)) as f:
  362. for line in f:
  363. if line.startswith('FILES_INFO:'):
  364. val = line.split(':', 1)[1].strip()
  365. dictval = json.loads(val)
  366. for fullpth in dictval.keys():
  367. if fnmatch.fnmatchcase(fullpth, args.targetpath):
  368. found = True
  369. print("%s: %s" % (fn, fullpth))
  370. break
  371. if not found:
  372. logger.error("Unable to find any package producing path %s" % args.targetpath)
  373. sys.exit(1)
  374. def main():
  375. parser = argparse.ArgumentParser(description="OpenEmbedded pkgdata tool - queries the pkgdata files written out during do_package",
  376. epilog="Use %(prog)s <subcommand> --help to get help on a specific command")
  377. parser.add_argument('-d', '--debug', help='Enable debug output', action='store_true')
  378. parser.add_argument('-p', '--pkgdata-dir', help='Path to pkgdata directory (determined automatically if not specified)')
  379. subparsers = parser.add_subparsers(title='subcommands', metavar='<subcommand>')
  380. parser_lookup_pkg = subparsers.add_parser('lookup-pkg',
  381. help='Translate between recipe-space package names and runtime package names',
  382. description='Looks up the specified recipe-space package name(s) to see what the final runtime package name is (e.g. glibc becomes libc6), or with -r/--reverse looks up the other way.')
  383. parser_lookup_pkg.add_argument('pkg', nargs='+', help='Package name to look up')
  384. parser_lookup_pkg.add_argument('-r', '--reverse', help='Switch to looking up recipe-space package names from runtime package names', action='store_true')
  385. parser_lookup_pkg.set_defaults(func=lookup_pkg)
  386. parser_list_pkgs = subparsers.add_parser('list-pkgs',
  387. help='List packages',
  388. description='Lists packages that have been built')
  389. parser_list_pkgs.add_argument('pkgspec', nargs='*', help='Package name to search for (wildcards * ? allowed, use quotes to avoid shell expansion)')
  390. parser_list_pkgs.add_argument('-r', '--runtime', help='Show runtime package names instead of recipe-space package names', action='store_true')
  391. parser_list_pkgs.add_argument('-p', '--recipe', help='Limit to packages produced by the specified recipe')
  392. parser_list_pkgs.add_argument('-u', '--unpackaged', help='Include unpackaged (i.e. empty) packages', action='store_true')
  393. parser_list_pkgs.set_defaults(func=list_pkgs)
  394. parser_list_pkg_files = subparsers.add_parser('list-pkg-files',
  395. help='List files within a package',
  396. description='Lists files included in one or more packages')
  397. parser_list_pkg_files.add_argument('pkg', nargs='*', help='Package name to report on (if -p/--recipe is not specified)')
  398. parser_list_pkg_files.add_argument('-r', '--runtime', help='Specified package(s) are runtime package names instead of recipe-space package names', action='store_true')
  399. parser_list_pkg_files.add_argument('-p', '--recipe', help='Report on all packages produced by the specified recipe')
  400. parser_list_pkg_files.add_argument('-u', '--unpackaged', help='Include unpackaged (i.e. empty) packages (only useful with -p/--recipe)', action='store_true')
  401. parser_list_pkg_files.set_defaults(func=list_pkg_files)
  402. parser_lookup_recipe = subparsers.add_parser('lookup-recipe',
  403. help='Find recipe producing one or more packages',
  404. description='Looks up the specified runtime package(s) to see which recipe they were produced by')
  405. parser_lookup_recipe.add_argument('pkg', nargs='+', help='Runtime package name to look up')
  406. parser_lookup_recipe.set_defaults(func=lookup_recipe)
  407. parser_find_path = subparsers.add_parser('find-path',
  408. help='Find package providing a target path',
  409. description='Finds the recipe-space package providing the specified target path')
  410. parser_find_path.add_argument('targetpath', help='Path to find (wildcards * ? allowed, use quotes to avoid shell expansion)')
  411. parser_find_path.set_defaults(func=find_path)
  412. parser_read_value = subparsers.add_parser('read-value',
  413. help='Read any pkgdata value for one or more packages',
  414. description='Reads the named value from the pkgdata files for the specified packages')
  415. parser_read_value.add_argument('valuename', help='Name of the value to look up')
  416. parser_read_value.add_argument('pkg', nargs='+', help='Runtime package name to look up')
  417. parser_read_value.set_defaults(func=read_value)
  418. parser_glob = subparsers.add_parser('glob',
  419. help='Expand package name glob expression',
  420. description='Expands one or more glob expressions over the packages listed in pkglistfile')
  421. parser_glob.add_argument('pkglistfile', help='File listing packages (one package name per line)')
  422. parser_glob.add_argument('glob', nargs="+", help='Glob expression for package names, e.g. *-dev')
  423. parser_glob.add_argument('-x', '--exclude', help='Exclude packages matching specified regex from the glob operation')
  424. parser_glob.set_defaults(func=glob)
  425. args = parser.parse_args()
  426. if args.debug:
  427. logger.setLevel(logging.DEBUG)
  428. if not args.pkgdata_dir:
  429. import scriptpath
  430. bitbakepath = scriptpath.add_bitbake_lib_path()
  431. if not bitbakepath:
  432. logger.error("Unable to find bitbake by searching parent directory of this script or PATH")
  433. sys.exit(1)
  434. logger.debug('Found bitbake path: %s' % bitbakepath)
  435. tinfoil = tinfoil_init()
  436. args.pkgdata_dir = tinfoil.config_data.getVar('PKGDATA_DIR', True)
  437. logger.debug('Value of PKGDATA_DIR is "%s"' % args.pkgdata_dir)
  438. if not args.pkgdata_dir:
  439. logger.error('Unable to determine pkgdata directory from PKGDATA_DIR')
  440. sys.exit(1)
  441. if not os.path.exists(args.pkgdata_dir):
  442. logger.error('Unable to find pkgdata directory %s' % args.pkgdata_dir)
  443. sys.exit(1)
  444. ret = args.func(args)
  445. return ret
  446. if __name__ == "__main__":
  447. main()