Add CONTENTS indexing support for optimization of owner lookups. The
[portage.git] / bin / portageq
1 #!/usr/bin/python -O
2 # Copyright 1999-2006 Gentoo Foundation
3 # Distributed under the terms of the GNU General Public License v2
4 # $Id$
5
6 import sys
7 # This block ensures that ^C interrupts are handled quietly.
8 try:
9         import signal
10
11         def exithandler(signum, frame):
12                 signal.signal(signal.SIGINT, signal.SIG_IGN)
13                 signal.signal(signal.SIGTERM, signal.SIG_IGN)
14                 sys.exit(1)
15
16         signal.signal(signal.SIGINT, exithandler)
17         signal.signal(signal.SIGTERM, exithandler)
18
19 except KeyboardInterrupt:
20         sys.exit(1)
21
22 import os
23
24 import types
25
26 #-----------------------------------------------------------------------------
27 #
28 # To add functionality to this tool, add a function below.
29 #
30 # The format for functions is:
31 #
32 #   def function(argv):
33 #       """<list of options for this function>
34 #       <description of the function>
35 #       """
36 #       <code>
37 #
38 # "argv" is an array of the command line parameters provided after the command.
39 #
40 # Make sure you document the function in the right format.  The documentation
41 # is used to display help on the function.
42 #
43 # You do not need to add the function to any lists, this tool is introspective,
44 # and will automaticly add a command by the same name as the function!
45 #
46
47 def has_version(argv):
48         """<root> <category/package>
49         Return code 0 if it's available, 1 otherwise.
50         """
51         if (len(argv) < 2):
52                 print "ERROR: insufficient parameters!"
53                 sys.exit(2)
54         try:
55                 mylist=portage.db[argv[0]]["vartree"].dbapi.match(argv[1])
56                 if mylist:
57                         sys.exit(0)
58                 else:
59                         sys.exit(1)
60         except KeyError:
61                 sys.exit(1)
62 has_version.uses_root = True
63
64
65 def best_version(argv):
66         """<root> <category/package>
67         Returns category/package-version (without .ebuild).
68         """
69         if (len(argv) < 2):
70                 print "ERROR: insufficient parameters!"
71                 sys.exit(2)
72         try:
73                 mylist=portage.db[argv[0]]["vartree"].dbapi.match(argv[1])
74                 print portage.best(mylist)
75         except KeyError:
76                 sys.exit(1)
77 best_version.uses_root = True
78
79
80 def mass_best_version(argv):
81         """<root> [<category/package>]+
82         Returns category/package-version (without .ebuild).
83         """
84         if (len(argv) < 2):
85                 print "ERROR: insufficient parameters!"
86                 sys.exit(2)
87         try:
88                 for pack in argv[1:]:
89                         mylist=portage.db[argv[0]]["vartree"].dbapi.match(pack)
90                         print pack+":"+portage.best(mylist)
91         except KeyError:
92                 sys.exit(1)
93 mass_best_version.uses_root = True
94
95 def metadata(argv):
96         """<root> <pkgtype> <category/package> [<key>]+
97         Returns metadata values for the specified package.
98         """
99         if (len(argv) < 4):
100                 print >> sys.stderr, "ERROR: insufficient parameters!"
101                 sys.exit(2)
102
103         root, pkgtype, pkgspec = argv[0:3]
104         metakeys = argv[3:]
105         type_map = {
106                 "ebuild":"porttree",
107                 "binary":"bintree",
108                 "installed":"vartree"}
109         if pkgtype not in type_map:
110                 print >> sys.stderr, "Unrecognized package type: '%s'" % pkgtype
111                 sys.exit(1)
112         trees = portage.db
113         if os.path.realpath(root) == os.path.realpath(portage.settings["ROOT"]):
114                 root = portage.settings["ROOT"] # contains the normalized $ROOT
115         try:
116                         values = trees[root][type_map[pkgtype]].dbapi.aux_get(
117                                 pkgspec, metakeys)
118                         for value in values:
119                                 print value
120         except KeyError:
121                 print >> sys.stderr, "Package not found: '%s'" % pkgspec
122                 sys.exit(1)
123
124 metadata.uses_root = True
125
126 def contents(argv):
127         """<root> <category/package>
128         List the files that are installed for a given package, with
129         one file listed on each line. All file names will begin with
130         <root>.
131         """
132         if len(argv) != 2:
133                 print "ERROR: expected 2 parameters, got %d!" % len(argv)
134                 return 2
135
136         root, cpv = argv
137         vartree = portage.db[root]["vartree"]
138         if not vartree.dbapi.cpv_exists(cpv):
139                 sys.stderr.write("Package not found: '%s'\n" % cpv)
140                 return 1
141         cat, pkg = portage.catsplit(cpv)
142         db = portage.dblink(cat, pkg, root, vartree.settings,
143                 treetype="vartree", vartree=vartree)
144         file_list = db.getcontents().keys()
145         file_list.sort()
146         for f in file_list:
147                 sys.stdout.write("%s\n" % f)
148         sys.stdout.flush()
149 contents.uses_root = True
150
151 def owners(argv):
152         """<root> [<filename>]+
153         Given a list of files, print the packages that own the files and which
154         files belong to each package. Files owned by a package are listed on
155         the lines below it, indented by a single tab character (\\t). All file
156         paths must start with <root>. Returns 1 if no owners could be found,
157         and 0 otherwise.
158         """
159         if len(argv) < 2:
160                 sys.stderr.write("ERROR: insufficient parameters!\n")
161                 sys.stderr.flush()
162                 return 2
163
164         from portage import catsplit, dblink
165         settings = portage.settings
166         root = settings["ROOT"]
167         vardb = portage.db[root]["vartree"].dbapi
168
169         cwd = None
170         try:
171                 cwd = os.getcwd()
172         except OSError:
173                 pass
174
175         files = []
176         for f in argv[1:]:
177                 f = portage.normalize_path(f)
178                 if not f.startswith(os.path.sep):
179                         if cwd is None:
180                                 sys.stderr.write("ERROR: cwd does not exist!\n")
181                                 sys.stderr.flush()
182                                 return 2
183                         f = os.path.join(cwd, f)
184                         f = portage.normalize_path(f)
185                 if not f.startswith(root):
186                         sys.stderr.write("ERROR: file paths must begin with <root>!\n")
187                         sys.stderr.flush()
188                         return 2
189                 files.append(f[len(root):])
190
191         owners = vardb._owners.get_owners(files)
192
193         for pkg, owned_files in owners.iteritems():
194                 cpv = pkg.mycpv
195                 sys.stdout.write("%s\n" % cpv)
196                 for f in sorted(owned_files):
197                         sys.stdout.write("\t%s\n" % \
198                                 os.path.join(root, f.lstrip(os.path.sep)))
199         if owners:
200                 sys.stdout.flush()
201                 return 0
202
203         sys.stderr.write("None of the installed packages claim the file(s).\n")
204         sys.stderr.flush()
205         return 1
206
207 owners.uses_root = True
208
209 def best_visible(argv):
210         """<root> [<category/package>]+
211         Returns category/package-version (without .ebuild).
212         """
213         if (len(argv) < 2):
214                 print "ERROR: insufficient parameters!"
215                 sys.exit(2)
216         try:
217                 mylist=portage.db[argv[0]]["porttree"].dbapi.match(argv[1])
218                 visible=portage.best(mylist)
219                 if visible:
220                         print visible
221                         sys.exit(0)
222                 else:
223                         sys.exit(1)
224         except KeyError:
225                 sys.exit(1)
226 best_visible.uses_root = True
227
228
229 def mass_best_visible(argv):
230         """<root> [<category/package>]+
231         Returns category/package-version (without .ebuild).
232         """
233         if (len(argv) < 2):
234                 print "ERROR: insufficient parameters!"
235                 sys.exit(2)
236         try:
237                 for pack in argv[1:]:
238                         mylist=portage.db[argv[0]]["porttree"].dbapi.match(pack)
239                         print pack+":"+portage.best(mylist)
240         except KeyError:
241                 sys.exit(1)
242 mass_best_visible.uses_root = True
243
244
245 def all_best_visible(argv):
246         """<root>
247         Returns all best_visible packages (without .ebuild).
248         """
249         if (len(argv) < 1):
250                 print "ERROR: insufficient parameters!"
251         
252         #print portage.db[argv[0]]["porttree"].dbapi.cp_all()
253         for pkg in portage.db[argv[0]]["porttree"].dbapi.cp_all():
254                 mybest=portage.best(portage.db[argv[0]]["porttree"].dbapi.match(pkg))
255                 if mybest:
256                         print mybest
257 all_best_visible.uses_root = True
258
259
260 def match(argv):
261         """<root> <atom>
262         Returns a \\n separated list of category/package-version.
263         When given an empty string, all installed packages will
264         be listed.
265         """
266         if len(argv) != 2:
267                 print "ERROR: expected 2 parameters, got %d!" % len(argv)
268                 sys.exit(2)
269         root, atom = argv
270         if atom:
271                 results = portage.db[root]["vartree"].dbapi.match(atom)
272         else:
273                 results = portage.db[root]["vartree"].dbapi.cpv_all()
274                 results.sort()
275         for cpv in results:
276                 print cpv
277 match.uses_root = True
278
279
280 def vdb_path(argv):
281         """
282         Returns the path used for the var(installed) package database for the
283         set environment/configuration options.
284         """
285         print portage.root+portage.VDB_PATH
286
287
288 def gentoo_mirrors(argv):
289         """
290         Returns the mirrors set to use in the portage configuration.
291         """
292         print portage.settings["GENTOO_MIRRORS"]
293
294
295 def portdir(argv):
296         """
297         Returns the PORTDIR path.
298         """
299         print portage.settings["PORTDIR"]
300
301
302 def config_protect(argv):
303         """
304         Returns the CONFIG_PROTECT paths.
305         """
306         print portage.settings["CONFIG_PROTECT"]
307
308
309 def config_protect_mask(argv):
310         """
311         Returns the CONFIG_PROTECT_MASK paths.
312         """
313         print portage.settings["CONFIG_PROTECT_MASK"]
314
315
316 def portdir_overlay(argv):
317         """
318         Returns the PORTDIR_OVERLAY path.
319         """
320         print portage.settings["PORTDIR_OVERLAY"]
321
322
323 def pkgdir(argv):
324         """
325         Returns the PKGDIR path.
326         """
327         print portage.settings["PKGDIR"]
328
329
330 def distdir(argv):
331         """
332         Returns the DISTDIR path.
333         """
334         print portage.settings["DISTDIR"]
335
336
337 def envvar(argv):
338         """<variable>+
339         Returns a specific environment variable as exists prior to ebuild.sh.
340         Similar to: emerge --verbose --info | egrep '^<variable>='
341         """
342         verbose = "-v" in argv
343         if verbose:
344                 argv.pop(argv.index("-v"))
345
346         if len(argv) == 0:
347                 print "ERROR: insufficient parameters!"
348                 sys.exit(2)
349
350         for arg in argv:
351                 if verbose:
352                         print arg +"='"+ portage.settings[arg] +"'"
353                 else:
354                         print portage.settings[arg]
355
356 def get_repos(argv):
357         """<root>
358         Returns all repos with names (repo_name file) argv[0] = $ROOT
359         """
360         if len(argv) < 1:
361                 print "ERROR: insufficient parameters!"
362                 sys.exit(2)
363         print " ".join(portage.db[argv[0]]["porttree"].dbapi.getRepositories())
364
365 def get_repo_path(argv):
366         """<root> <repo_id>+
367         Returns the path to the repo named argv[1], argv[0] = $ROOT
368         """
369         if len(argv) < 2:
370                 print "ERROR: insufficient parameters!"
371                 sys.exit(2)
372         for arg in arvg[1:]:
373                 print portage.db[argv[0]]["porttree"].dbapi.getRepositoryPath(argv[1])
374
375 def list_preserved_libs(argv):
376         """<root>
377         Print a list of libraries preserved during a package update in the form
378         package: path. Returns 0 if no preserved libraries could be found, 
379         1 otherwise.
380         """
381
382         if len(argv) != 1:
383                 print "ERROR: wrong number of arguments"
384                 sys.exit(2)
385         mylibs = portage.db[argv[0]]["vartree"].dbapi.plib_registry.getPreservedLibs()
386         rValue = 0
387         for cpv in mylibs:
388                 print cpv,
389                 for path in mylibs[cpv]:
390                         print path,
391                         rValue = 1
392                 print
393         return rValue
394 list_preserved_libs.uses_root = True
395
396 #-----------------------------------------------------------------------------
397 #
398 # DO NOT CHANGE CODE BEYOND THIS POINT - IT'S NOT NEEDED!
399 #
400
401 def usage(argv):
402         print ">>> Portage information query tool"
403         print ">>> $Id$"
404         print ">>> Usage: portageq <command> [<option> ...]"
405         print ""
406         print "Available commands:"
407
408         #
409         # Show our commands -- we do this by scanning the functions in this
410         # file, and formatting each functions documentation.
411         #
412         commands = [x for x in globals() if x not in \
413                                 ("usage", "__doc__", "__name__", "main", "os", "portage", \
414                                 "sys", "__builtins__", "types", "string","exithandler")]
415         commands.sort()
416
417         for name in commands:
418                 # Drop non-functions
419                 obj = globals()[name]
420                 if  (type(obj) != types.FunctionType):
421                         continue
422
423                 doc = obj.__doc__
424                 if (doc == None):
425                         print "   "+name
426                         print "      MISSING DOCUMENTATION!"
427                         print ""
428                         continue
429
430                 lines = doc.split("\n")
431                 print "   "+name+" "+lines[0].strip()
432                 if (len(sys.argv) > 1):
433                         if ("--help" not in sys.argv):
434                                 lines = lines[:-1]
435                         for line in lines[1:]:
436                                 print "      "+line.strip()
437         if (len(sys.argv) == 1):
438                 print "\nRun portageq with --help for info"
439
440 def main():
441         if "-h" in sys.argv or "--help" in sys.argv:
442                 usage(sys.argv)
443                 sys.exit(os.EX_OK)
444         elif len(sys.argv) < 2:
445                 usage(sys.argv)
446                 sys.exit(os.EX_USAGE)
447
448         cmd = sys.argv[1]
449         function = globals().get(cmd)
450         if function is None:
451                 usage(sys.argv)
452                 sys.exit(os.EX_USAGE)
453         function = globals()[cmd]
454         uses_root = getattr(function, "uses_root", False) and len(sys.argv) > 2
455         if uses_root:
456                 if not os.path.isdir(sys.argv[2]):
457                         sys.stderr.write("Not a directory: '%s'\n" % sys.argv[2])
458                         sys.stderr.write("Run portageq with --help for info\n")
459                         sys.stderr.flush()
460                         sys.exit(os.EX_USAGE)
461                 os.environ["ROOT"] = sys.argv[2]
462
463         global portage
464
465         # First import the main portage module without legacy globals since it
466         # is almost certain to succeed in that case. This provides access to
467         # the portage.exception namespace which is needed for later exception
468         # handling, like if portage.exception.PermissionDenied is raised when
469         # constructing the legacy global config instance.
470         os.environ["PORTAGE_LEGACY_GLOBALS"] = "false"
471         import portage
472         del os.environ["PORTAGE_LEGACY_GLOBALS"]
473         try:
474                 try:
475                         reload(portage)
476                 except ImportError:
477                         from os import path as osp
478                         sys.path.insert(0, osp.join(osp.dirname(osp.dirname(osp.realpath(__file__))), "pym"))
479                         import portage
480                 if uses_root:
481                         sys.argv[2] = portage.root
482                 retval = function(sys.argv[2:])
483                 if retval:
484                         sys.exit(retval)
485         except portage.exception.PermissionDenied, e:
486                 sys.stderr.write("Permission denied: '%s'\n" % str(e))
487                 sys.exit(e.errno)
488         except portage.exception.ParseError, e:
489                 sys.stderr.write("%s\n" % str(e))
490                 sys.exit(1)
491         except ValueError, e:
492                 if not e.args or \
493                         not hasattr(e.args[0], "__len__") or \
494                         len(e.args[0]) < 2:
495                         raise
496                 # Multiple matches thrown from cpv_expand
497                 pkgs = e.args[0]
498                 # An error has occurred so we writemsg to stderr and exit nonzero.
499                 portage.writemsg("You specified an unqualified atom that matched multiple packages:\n", noiselevel=-1)
500                 for pkg in pkgs:
501                         portage.writemsg("* %s\n" % pkg, noiselevel=-1)
502                 portage.writemsg("\nPlease use a more specific atom.\n", noiselevel=-1)
503                 sys.exit(1)
504
505 main()
506
507 #-----------------------------------------------------------------------------