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