fb3bd5e1a047106af5a2e940f3bffc31052ace7c
[scons.git] / src / script / sconsign.py
1 #! /usr/bin/env python
2 #
3 # SCons - a Software Constructor
4 #
5 # __COPYRIGHT__
6 #
7 # Permission is hereby granted, free of charge, to any person obtaining
8 # a copy of this software and associated documentation files (the
9 # "Software"), to deal in the Software without restriction, including
10 # without limitation the rights to use, copy, modify, merge, publish,
11 # distribute, sublicense, and/or sell copies of the Software, and to
12 # permit persons to whom the Software is furnished to do so, subject to
13 # the following conditions:
14 #
15 # The above copyright notice and this permission notice shall be included
16 # in all copies or substantial portions of the Software.
17 #
18 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
19 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
20 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
22 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
24 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 #
26 from __future__ import generators  ### KEEP FOR COMPATIBILITY FIXERS
27
28 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
29
30 __version__ = "__VERSION__"
31
32 __build__ = "__BUILD__"
33
34 __buildsys__ = "__BUILDSYS__"
35
36 __date__ = "__DATE__"
37
38 __developer__ = "__DEVELOPER__"
39
40 import os
41 import os.path
42 import sys
43 import time
44
45 ##############################################################################
46 # BEGIN STANDARD SCons SCRIPT HEADER
47 #
48 # This is the cut-and-paste logic so that a self-contained script can
49 # interoperate correctly with different SCons versions and installation
50 # locations for the engine.  If you modify anything in this section, you
51 # should also change other scripts that use this same header.
52 ##############################################################################
53
54 # Strip the script directory from sys.path() so on case-insensitive
55 # (WIN32) systems Python doesn't think that the "scons" script is the
56 # "SCons" package.  Replace it with our own library directories
57 # (version-specific first, in case they installed by hand there,
58 # followed by generic) so we pick up the right version of the build
59 # engine modules if they're in either directory.
60
61 script_dir = sys.path[0]
62
63 if script_dir in sys.path:
64     sys.path.remove(script_dir)
65
66 libs = []
67
68 if "SCONS_LIB_DIR" in os.environ:
69     libs.append(os.environ["SCONS_LIB_DIR"])
70
71 local_version = 'scons-local-' + __version__
72 local = 'scons-local'
73 if script_dir:
74     local_version = os.path.join(script_dir, local_version)
75     local = os.path.join(script_dir, local)
76 libs.append(os.path.abspath(local_version))
77 libs.append(os.path.abspath(local))
78
79 scons_version = 'scons-%s' % __version__
80
81 prefs = []
82
83 if sys.platform == 'win32':
84     # sys.prefix is (likely) C:\Python*;
85     # check only C:\Python*.
86     prefs.append(sys.prefix)
87     prefs.append(os.path.join(sys.prefix, 'Lib', 'site-packages'))
88 else:
89     # On other (POSIX) platforms, things are more complicated due to
90     # the variety of path names and library locations.  Try to be smart
91     # about it.
92     if script_dir == 'bin':
93         # script_dir is `pwd`/bin;
94         # check `pwd`/lib/scons*.
95         prefs.append(os.getcwd())
96     else:
97         if script_dir == '.' or script_dir == '':
98             script_dir = os.getcwd()
99         head, tail = os.path.split(script_dir)
100         if tail == "bin":
101             # script_dir is /foo/bin;
102             # check /foo/lib/scons*.
103             prefs.append(head)
104
105     head, tail = os.path.split(sys.prefix)
106     if tail == "usr":
107         # sys.prefix is /foo/usr;
108         # check /foo/usr/lib/scons* first,
109         # then /foo/usr/local/lib/scons*.
110         prefs.append(sys.prefix)
111         prefs.append(os.path.join(sys.prefix, "local"))
112     elif tail == "local":
113         h, t = os.path.split(head)
114         if t == "usr":
115             # sys.prefix is /foo/usr/local;
116             # check /foo/usr/local/lib/scons* first,
117             # then /foo/usr/lib/scons*.
118             prefs.append(sys.prefix)
119             prefs.append(head)
120         else:
121             # sys.prefix is /foo/local;
122             # check only /foo/local/lib/scons*.
123             prefs.append(sys.prefix)
124     else:
125         # sys.prefix is /foo (ends in neither /usr or /local);
126         # check only /foo/lib/scons*.
127         prefs.append(sys.prefix)
128
129     temp = [os.path.join(x, 'lib') for x in prefs]
130     temp.extend([os.path.join(x,
131                                            'lib',
132                                            'python' + sys.version[:3],
133                                            'site-packages') for x in prefs])
134     prefs = temp
135
136     # Add the parent directory of the current python's library to the
137     # preferences.  On SuSE-91/AMD64, for example, this is /usr/lib64,
138     # not /usr/lib.
139     try:
140         libpath = os.__file__
141     except AttributeError:
142         pass
143     else:
144         # Split /usr/libfoo/python*/os.py to /usr/libfoo/python*.
145         libpath, tail = os.path.split(libpath)
146         # Split /usr/libfoo/python* to /usr/libfoo
147         libpath, tail = os.path.split(libpath)
148         # Check /usr/libfoo/scons*.
149         prefs.append(libpath)
150
151     try:
152         import pkg_resources
153     except ImportError:
154         pass
155     else:
156         # when running from an egg add the egg's directory 
157         try:
158             d = pkg_resources.get_distribution('scons')
159         except pkg_resources.DistributionNotFound:
160             pass
161         else:
162             prefs.append(d.location)
163
164 # Look first for 'scons-__version__' in all of our preference libs,
165 # then for 'scons'.
166 libs.extend([os.path.join(x, scons_version) for x in prefs])
167 libs.extend([os.path.join(x, 'scons') for x in prefs])
168
169 sys.path = libs + sys.path
170
171 ##############################################################################
172 # END STANDARD SCons SCRIPT HEADER
173 ##############################################################################
174
175 import cPickle
176 import imp
177 import whichdb
178
179 import SCons.SConsign
180
181 def my_whichdb(filename):
182     if filename[-7:] == ".dblite":
183         return "SCons.dblite"
184     try:
185         f = open(filename + ".dblite", "rb")
186         f.close()
187         return "SCons.dblite"
188     except IOError:
189         pass
190     return _orig_whichdb(filename)
191
192 _orig_whichdb = whichdb.whichdb
193 whichdb.whichdb = my_whichdb
194
195 def my_import(mname):
196     if '.' in mname:
197         i = mname.rfind('.')
198         parent = my_import(mname[:i])
199         fp, pathname, description = imp.find_module(mname[i+1:],
200                                                     parent.__path__)
201     else:
202         fp, pathname, description = imp.find_module(mname)
203     return imp.load_module(mname, fp, pathname, description)
204
205 class Flagger:
206     default_value = 1
207     def __setitem__(self, item, value):
208         self.__dict__[item] = value
209         self.default_value = 0
210     def __getitem__(self, item):
211         return self.__dict__.get(item, self.default_value)
212
213 Do_Call = None
214 Print_Directories = []
215 Print_Entries = []
216 Print_Flags = Flagger()
217 Verbose = 0
218 Readable = 0
219
220 def default_mapper(entry, name):
221     try:
222         val = eval("entry."+name)
223     except:
224         val = None
225     return str(val)
226
227 def map_action(entry, name):
228     try:
229         bact = entry.bact
230         bactsig = entry.bactsig
231     except AttributeError:
232         return None
233     return '%s [%s]' % (bactsig, bact)
234
235 def map_timestamp(entry, name):
236     try:
237         timestamp = entry.timestamp
238     except AttributeError:
239         timestamp = None
240     if Readable and timestamp:
241         return "'" + time.ctime(timestamp) + "'"
242     else:
243         return str(timestamp)
244
245 def map_bkids(entry, name):
246     try:
247         bkids = entry.bsources + entry.bdepends + entry.bimplicit
248         bkidsigs = entry.bsourcesigs + entry.bdependsigs + entry.bimplicitsigs
249     except AttributeError:
250         return None
251     result = []
252     for i in xrange(len(bkids)):
253         result.append(nodeinfo_string(bkids[i], bkidsigs[i], "        "))
254     if result == []:
255         return None
256     return "\n        ".join(result)
257
258 map_field = {
259     'action'    : map_action,
260     'timestamp' : map_timestamp,
261     'bkids'     : map_bkids,
262 }
263
264 map_name = {
265     'implicit'  : 'bkids',
266 }
267
268 def field(name, entry, verbose=Verbose):
269     if not Print_Flags[name]:
270         return None
271     fieldname = map_name.get(name, name)
272     mapper = map_field.get(fieldname, default_mapper)
273     val = mapper(entry, name)
274     if verbose:
275         val = name + ": " + val
276     return val
277
278 def nodeinfo_raw(name, ninfo, prefix=""):
279     # This just formats the dictionary, which we would normally use str()
280     # to do, except that we want the keys sorted for deterministic output.
281     d = ninfo.__dict__
282     try:
283         keys = ninfo.field_list + ['_version_id']
284     except AttributeError:
285         keys = d.keys()
286         keys.sort()
287     l = []
288     for k in keys:
289         l.append('%s: %s' % (repr(k), repr(d.get(k))))
290     if '\n' in name:
291         name = repr(name)
292     return name + ': {' + ', '.join(l) + '}'
293
294 def nodeinfo_cooked(name, ninfo, prefix=""):
295     try:
296         field_list = ninfo.field_list
297     except AttributeError:
298         field_list = []
299     if '\n' in name:
300         name = repr(name)
301     outlist = [name+':'] + [_f for _f in [field(x, ninfo, Verbose) for x in field_list] if _f]
302     if Verbose:
303         sep = '\n    ' + prefix
304     else:
305         sep = ' '
306     return sep.join(outlist)
307
308 nodeinfo_string = nodeinfo_cooked
309
310 def printfield(name, entry, prefix=""):
311     outlist = field("implicit", entry, 0)
312     if outlist:
313         if Verbose:
314             print "    implicit:"
315         print "        " + outlist
316     outact = field("action", entry, 0)
317     if outact:
318         if Verbose:
319             print "    action: " + outact
320         else:
321             print "        " + outact
322
323 def printentries(entries, location):
324     if Print_Entries:
325         for name in Print_Entries:
326             try:
327                 entry = entries[name]
328             except KeyError:
329                 sys.stderr.write("sconsign: no entry `%s' in `%s'\n" % (name, location))
330             else:
331                 try:
332                     ninfo = entry.ninfo
333                 except AttributeError:
334                     print name + ":"
335                 else:
336                     print nodeinfo_string(name, entry.ninfo)
337                 printfield(name, entry.binfo)
338     else:
339         names = entries.keys()
340         names.sort()
341         for name in names:
342             entry = entries[name]
343             try:
344                 ninfo = entry.ninfo
345             except AttributeError:
346                 print name + ":"
347             else:
348                 print nodeinfo_string(name, entry.ninfo)
349             printfield(name, entry.binfo)
350
351 class Do_SConsignDB:
352     def __init__(self, dbm_name, dbm):
353         self.dbm_name = dbm_name
354         self.dbm = dbm
355
356     def __call__(self, fname):
357         # The *dbm modules stick their own file suffixes on the names
358         # that are passed in.  This is causes us to jump through some
359         # hoops here to be able to allow the user
360         try:
361             # Try opening the specified file name.  Example:
362             #   SPECIFIED                  OPENED BY self.dbm.open()
363             #   ---------                  -------------------------
364             #   .sconsign               => .sconsign.dblite
365             #   .sconsign.dblite        => .sconsign.dblite.dblite
366             db = self.dbm.open(fname, "r")
367         except (IOError, OSError), e:
368             print_e = e
369             try:
370                 # That didn't work, so try opening the base name,
371                 # so that if the actually passed in 'sconsign.dblite'
372                 # (for example), the dbm module will put the suffix back
373                 # on for us and open it anyway.
374                 db = self.dbm.open(os.path.splitext(fname)[0], "r")
375             except (IOError, OSError):
376                 # That didn't work either.  See if the file name
377                 # they specified just exists (independent of the dbm
378                 # suffix-mangling).
379                 try:
380                     open(fname, "r")
381                 except (IOError, OSError), e:
382                     # Nope, that file doesn't even exist, so report that
383                     # fact back.
384                     print_e = e
385                 sys.stderr.write("sconsign: %s\n" % (print_e))
386                 return
387         except KeyboardInterrupt:
388             raise
389         except cPickle.UnpicklingError:
390             sys.stderr.write("sconsign: ignoring invalid `%s' file `%s'\n" % (self.dbm_name, fname))
391             return
392         except Exception, e:
393             sys.stderr.write("sconsign: ignoring invalid `%s' file `%s': %s\n" % (self.dbm_name, fname, e))
394             return
395
396         if Print_Directories:
397             for dir in Print_Directories:
398                 try:
399                     val = db[dir]
400                 except KeyError:
401                     sys.stderr.write("sconsign: no dir `%s' in `%s'\n" % (dir, args[0]))
402                 else:
403                     self.printentries(dir, val)
404         else:
405             keys = db.keys()
406             keys.sort()
407             for dir in keys:
408                 self.printentries(dir, db[dir])
409
410     def printentries(self, dir, val):
411         print '=== ' + dir + ':'
412         printentries(cPickle.loads(val), dir)
413
414 def Do_SConsignDir(name):
415     try:
416         fp = open(name, 'rb')
417     except (IOError, OSError), e:
418         sys.stderr.write("sconsign: %s\n" % (e))
419         return
420     try:
421         sconsign = SCons.SConsign.Dir(fp)
422     except KeyboardInterrupt:
423         raise
424     except cPickle.UnpicklingError:
425         sys.stderr.write("sconsign: ignoring invalid .sconsign file `%s'\n" % (name))
426         return
427     except Exception, e:
428         sys.stderr.write("sconsign: ignoring invalid .sconsign file `%s': %s\n" % (name, e))
429         return
430     printentries(sconsign.entries, args[0])
431
432 ##############################################################################
433
434 import getopt
435
436 helpstr = """\
437 Usage: sconsign [OPTIONS] FILE [...]
438 Options:
439   -a, --act, --action         Print build action information.
440   -c, --csig                  Print content signature information.
441   -d DIR, --dir=DIR           Print only info about DIR.
442   -e ENTRY, --entry=ENTRY     Print only info about ENTRY.
443   -f FORMAT, --format=FORMAT  FILE is in the specified FORMAT.
444   -h, --help                  Print this message and exit.
445   -i, --implicit              Print implicit dependency information.
446   -r, --readable              Print timestamps in human-readable form.
447   --raw                       Print raw Python object representations.
448   -s, --size                  Print file sizes.
449   -t, --timestamp             Print timestamp information.
450   -v, --verbose               Verbose, describe each field.
451 """
452
453 opts, args = getopt.getopt(sys.argv[1:], "acd:e:f:hirstv",
454                             ['act', 'action',
455                              'csig', 'dir=', 'entry=',
456                              'format=', 'help', 'implicit',
457                              'raw', 'readable',
458                              'size', 'timestamp', 'verbose'])
459
460
461 for o, a in opts:
462     if o in ('-a', '--act', '--action'):
463         Print_Flags['action'] = 1
464     elif o in ('-c', '--csig'):
465         Print_Flags['csig'] = 1
466     elif o in ('-d', '--dir'):
467         Print_Directories.append(a)
468     elif o in ('-e', '--entry'):
469         Print_Entries.append(a)
470     elif o in ('-f', '--format'):
471         Module_Map = {'dblite'   : 'SCons.dblite',
472                       'sconsign' : None}
473         dbm_name = Module_Map.get(a, a)
474         if dbm_name:
475             try:
476                 dbm = my_import(dbm_name)
477             except:
478                 sys.stderr.write("sconsign: illegal file format `%s'\n" % a)
479                 print helpstr
480                 sys.exit(2)
481             Do_Call = Do_SConsignDB(a, dbm)
482         else:
483             Do_Call = Do_SConsignDir
484     elif o in ('-h', '--help'):
485         print helpstr
486         sys.exit(0)
487     elif o in ('-i', '--implicit'):
488         Print_Flags['implicit'] = 1
489     elif o in ('--raw',):
490         nodeinfo_string = nodeinfo_raw
491     elif o in ('-r', '--readable'):
492         Readable = 1
493     elif o in ('-s', '--size'):
494         Print_Flags['size'] = 1
495     elif o in ('-t', '--timestamp'):
496         Print_Flags['timestamp'] = 1
497     elif o in ('-v', '--verbose'):
498         Verbose = 1
499
500 if Do_Call:
501     for a in args:
502         Do_Call(a)
503 else:
504     for a in args:
505         dbm_name = whichdb.whichdb(a)
506         if dbm_name:
507             Map_Module = {'SCons.dblite' : 'dblite'}
508             dbm = my_import(dbm_name)
509             Do_SConsignDB(Map_Module.get(dbm_name, dbm_name), dbm)(a)
510         else:
511             Do_SConsignDir(a)
512
513 sys.exit(0)
514
515 # Local Variables:
516 # tab-width:4
517 # indent-tabs-mode:nil
518 # End:
519 # vim: set expandtab tabstop=4 shiftwidth=4: