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