oe-pkgdata-util 21 KB

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