Fix automatic sys.path insertions so that they're relative instead of absolute hard...
[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
48 def has_version(argv):
49         """<root> <category/package>
50         Return code 0 if it's available, 1 otherwise.
51         """
52         if (len(argv) < 2):
53                 print "ERROR: insufficient parameters!"
54                 sys.exit(2)
55         try:
56                 mylist=portage.db[argv[0]]["vartree"].dbapi.match(argv[1])
57                 if mylist:
58                         sys.exit(0)
59                 else:
60                         sys.exit(1)
61         except KeyError:
62                 sys.exit(1)
63 has_version.uses_root = True
64
65
66 def best_version(argv):
67         """<root> <category/package>
68         Returns category/package-version (without .ebuild).
69         """
70         if (len(argv) < 2):
71                 print "ERROR: insufficient parameters!"
72                 sys.exit(2)
73         try:
74                 mylist=portage.db[argv[0]]["vartree"].dbapi.match(argv[1])
75                 print portage.best(mylist)
76         except KeyError:
77                 sys.exit(1)
78 best_version.uses_root = True
79
80
81 def mass_best_version(argv):
82         """<root> [<category/package>]+
83         Returns category/package-version (without .ebuild).
84         """
85         if (len(argv) < 2):
86                 print "ERROR: insufficient parameters!"
87                 sys.exit(2)
88         try:
89                 for pack in argv[1:]:
90                         mylist=portage.db[argv[0]]["vartree"].dbapi.match(pack)
91                         print pack+":"+portage.best(mylist)
92         except KeyError:
93                 sys.exit(1)
94 mass_best_version.uses_root = True
95
96 def metadata(argv):
97         """<root> <pkgtype> <category/package> [<key>]+
98         Returns metadata values for the specified package.
99         """
100         if (len(argv) < 4):
101                 print >> sys.stderr, "ERROR: insufficient parameters!"
102                 sys.exit(2)
103
104         root, pkgtype, pkgspec = argv[0:3]
105         metakeys = argv[3:]
106         type_map = {
107                 "ebuild":"porttree",
108                 "binary":"bintree",
109                 "installed":"vartree"}
110         if pkgtype not in type_map:
111                 print >> sys.stderr, "Unrecognized package type: '%s'" % pkgtype
112                 sys.exit(1)
113         trees = portage.db
114         if os.path.realpath(root) == os.path.realpath(portage.settings["ROOT"]):
115                 root = portage.settings["ROOT"] # contains the normalized $ROOT
116         try:
117                         values = trees[root][type_map[pkgtype]].dbapi.aux_get(
118                                 pkgspec, metakeys)
119                         for value in values:
120                                 print value
121         except KeyError:
122                 print >> sys.stderr, "Package not found: '%s'" % pkgspec
123                 sys.exit(1)
124
125 metadata.uses_root = True
126
127 def best_visible(argv):
128         """<root> [<category/package>]+
129         Returns category/package-version (without .ebuild).
130         """
131         if (len(argv) < 2):
132                 print "ERROR: insufficient parameters!"
133                 sys.exit(2)
134         try:
135                 mylist=portage.db[argv[0]]["porttree"].dbapi.match(argv[1])
136                 visible=portage.best(mylist)
137                 if visible:
138                         print visible
139                         sys.exit(0)
140                 else:
141                         sys.exit(1)
142         except KeyError:
143                 sys.exit(1)
144 best_visible.uses_root = True
145
146
147 def mass_best_visible(argv):
148         """<root> [<category/package>]+
149         Returns category/package-version (without .ebuild).
150         """
151         if (len(argv) < 2):
152                 print "ERROR: insufficient parameters!"
153                 sys.exit(2)
154         try:
155                 for pack in argv[1:]:
156                         mylist=portage.db[argv[0]]["porttree"].dbapi.match(pack)
157                         print pack+":"+portage.best(mylist)
158         except KeyError:
159                 sys.exit(1)
160 mass_best_visible.uses_root = True
161
162
163 def all_best_visible(argv):
164         """<root>
165         Returns all best_visible packages (without .ebuild).
166         """
167         if (len(argv) < 1):
168                 print "ERROR: insufficient parameters!"
169         
170         #print portage.db[argv[0]]["porttree"].dbapi.cp_all()
171         for pkg in portage.db[argv[0]]["porttree"].dbapi.cp_all():
172                 mybest=portage.best(portage.db[argv[0]]["porttree"].dbapi.match(pkg))
173                 if mybest:
174                         print mybest
175 all_best_visible.uses_root = True
176
177
178 def match(argv):
179         """<root> <category/package>
180         Returns \n seperated list of category/package-version
181         """
182         if (len(argv) < 2):
183                 print "ERROR: insufficient parameters!"
184                 sys.exit(2)
185         try:
186                 print "\n".join(portage.db[argv[0]]["vartree"].dbapi.match(argv[1]))
187         except ValueError, e:
188                 # Multiple matches thrown from cpv_expand
189                 pkgs = e.args[0]
190                 # An error has occurred so we writemsg to stderr and exit nonzero.
191                 portage.writemsg("The following packages available:\n", noiselevel=-1)
192                 for pkg in pkgs:
193                         portage.writemsg("* %s\n" % pkg, noiselevel=-1)
194                 portage.writemsg("\nPlease use a more specific atom.\n", noiselevel=-1)
195                 sys.exit(1)
196         except KeyError, e:
197                 portage.writemsg("%s\n" % str(e), noiselevel=-1)
198                 sys.exit(1)
199 match.uses_root = True
200
201
202 def vdb_path(argv):
203         """
204         Returns the path used for the var(installed) package database for the
205         set environment/configuration options.
206         """
207         print portage.root+portage.VDB_PATH
208
209
210 def gentoo_mirrors(argv):
211         """
212         Returns the mirrors set to use in the portage configuration.
213         """
214         print portage.settings["GENTOO_MIRRORS"]
215
216
217 def portdir(argv):
218         """
219         Returns the PORTDIR path.
220         """
221         print portage.settings["PORTDIR"]
222
223
224 def config_protect(argv):
225         """
226         Returns the CONFIG_PROTECT paths.
227         """
228         print portage.settings["CONFIG_PROTECT"]
229
230
231 def config_protect_mask(argv):
232         """
233         Returns the CONFIG_PROTECT_MASK paths.
234         """
235         print portage.settings["CONFIG_PROTECT_MASK"]
236
237
238 def portdir_overlay(argv):
239         """
240         Returns the PORTDIR_OVERLAY path.
241         """
242         print portage.settings["PORTDIR_OVERLAY"]
243
244
245 def pkgdir(argv):
246         """
247         Returns the PKGDIR path.
248         """
249         print portage.settings["PKGDIR"]
250
251
252 def distdir(argv):
253         """
254         Returns the DISTDIR path.
255         """
256         print portage.settings["DISTDIR"]
257
258
259 def envvar(argv):
260         """<variable>+
261         Returns a specific environment variable as exists prior to ebuild.sh.
262         Similar to: emerge --verbose --info | egrep '^<variable>='
263         """
264         verbose = "-v" in argv
265         if verbose:
266                 argv.pop(argv.index("-v"))
267
268         if len(argv) == 0:
269                 print "ERROR: insufficient parameters!"
270                 sys.exit(2)
271
272         for arg in argv:
273                 if verbose:
274                         print arg +"='"+ portage.settings[arg] +"'"
275                 else:
276                         print portage.settings[arg]
277
278 def get_repos(argv):
279         """<root>
280         Returns all repos with names (repo_name file) argv[0] = $ROOT
281         """
282         if len(argv) < 1:
283                 print "ERROR: insufficient parameters!"
284                 sys.exit(2)
285         print " ".join(portage.db[argv[0]]["porttree"].dbapi.getRepositories())
286
287 def get_repo_path(argv):
288         """<root> <repo_id>+
289         Returns the path to the repo named argv[1], argv[0] = $ROOT
290         """
291         if len(argv) < 2:
292                 print "ERROR: insufficient parameters!"
293                 sys.exit(2)
294         for arg in arvg[1:]:
295                 print portage.db[argv[0]]["porttree"].dbapi.getRepositoryPath(argv[1])
296
297 #-----------------------------------------------------------------------------
298 #
299 # DO NOT CHANGE CODE BEYOND THIS POINT - IT'S NOT NEEDED!
300 #
301
302 def usage(argv):
303         rev="$Revision: 1.13.2.1 $"
304         ver= rev.split(' ')[1]
305         print ">>> Portage information query tool -- version "+ver
306         print ">>> Usage: portageq <command> [<option> ...]"
307         print ""
308         print "Available commands:"
309
310         #
311         # Show our commands -- we do this by scanning the functions in this
312         # file, and formatting each functions documentation.
313         #
314         for name in globals().keys():
315                 # Drop python stuff, modules, and our own support functions.
316                 if (name in ("usage", "__doc__", "__name__", "main", "os", "portage", "sys", "__builtins__", "types", "string","exithandler")):
317                         continue
318
319                 # Drop non-functions
320                 obj = globals()[name]
321                 if  (type(obj) != types.FunctionType):
322                         continue
323
324                 doc = obj.__doc__
325                 if (doc == None):
326                         print "   "+name
327                         print "      MISSING DOCUMENTATION!"
328                         print ""
329                         continue
330
331                 lines = doc.split("\n")
332                 print "   "+name+" "+lines[0].strip()
333                 if (len(sys.argv) > 1):
334                         if ("--help" not in sys.argv):
335                                 lines = lines[:-1]
336                         for line in lines[1:]:
337                                 print "      "+line.strip()
338         if (len(sys.argv) == 1):
339                 print "\nRun portageq with --help for info"
340
341 def main():
342         if "-h" in sys.argv or "--help" in sys.argv:
343                 usage(sys.argv)
344                 sys.exit(os.EX_OK)
345         elif len(sys.argv) < 2:
346                 usage(sys.argv)
347                 sys.exit(os.EX_USAGE)
348
349         cmd = sys.argv[1]
350         try:
351                 function = globals()[cmd]
352                 uses_root = (getattr(function, "uses_root", False) and len(sys.argv) > 2)
353                 if uses_root:
354                         os.environ["ROOT"] = sys.argv[2]
355                 global portage
356                 try:
357                         import portage
358                 except ImportError:
359                         from os import path as osp
360                         sys.path.insert(0, osp.join(osp.dirname(osp.dirname(__file__)), "pym"))
361                         import portage
362                 if uses_root:
363                         sys.argv[2] = portage.root
364                 function(sys.argv[2:])
365         except KeyError:
366                 usage(sys.argv)
367                 sys.exit(os.EX_USAGE)
368
369 main()
370
371 #-----------------------------------------------------------------------------