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