1792dc48a244685ac2e04766704c034f02b0e2b0
[scons.git] / src / engine / SCons / compat / __init__.py
1 #
2 # __COPYRIGHT__
3 #
4 # Permission is hereby granted, free of charge, to any person obtaining
5 # a copy of this software and associated documentation files (the
6 # "Software"), to deal in the Software without restriction, including
7 # without limitation the rights to use, copy, modify, merge, publish,
8 # distribute, sublicense, and/or sell copies of the Software, and to
9 # permit persons to whom the Software is furnished to do so, subject to
10 # the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included
13 # in all copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
16 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
17 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 #
23
24 __doc__ = """
25 SCons compatibility package for old Python versions
26
27 This subpackage holds modules that provide backwards-compatible
28 implementations of various things that we'd like to use in SCons but which
29 only show up in later versions of Python than the early, old version(s)
30 we still support.
31
32 Other code will not generally reference things in this package through
33 the SCons.compat namespace.  The modules included here add things to
34 the builtins namespace or the global module list so that the rest
35 of our code can use the objects and names imported here regardless of
36 Python version.
37
38 Simply enough, things that go in the builtins name space come from
39 our _scons_builtins module.
40
41 The rest of the things here will be in individual compatibility modules
42 that are either: 1) suitably modified copies of the future modules that
43 we want to use; or 2) backwards compatible re-implementations of the
44 specific portions of a future module's API that we want to use.
45
46 GENERAL WARNINGS:  Implementations of functions in the SCons.compat
47 modules are *NOT* guaranteed to be fully compliant with these functions in
48 later versions of Python.  We are only concerned with adding functionality
49 that we actually use in SCons, so be wary if you lift this code for
50 other uses.  (That said, making these more nearly the same as later,
51 official versions is still a desirable goal, we just don't need to be
52 obsessive about it.)
53
54 We name the compatibility modules with an initial '_scons_' (for example,
55 _scons_subprocess.py is our compatibility module for subprocess) so
56 that we can still try to import the real module name and fall back to
57 our compatibility module if we get an ImportError.  The import_as()
58 function defined below loads the module as the "real" name (without the
59 '_scons'), after which all of the "import {module}" statements in the
60 rest of our code will find our pre-loaded compatibility module.
61 """
62
63 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
64
65 def import_as(module, name):
66     """
67     Imports the specified module (from our local directory) as the
68     specified name, returning the loaded module object.
69     """
70     import imp
71     import os.path
72     dir = os.path.split(__file__)[0]
73     file, filename, suffix_mode_type = imp.find_module(module, [dir])
74     return imp.load_module(name, file, filename, suffix_mode_type)
75
76
77 try:
78     import builtins
79 except ImportError:
80     # Use the "imp" module to protect the import from fixers.
81     import imp
82     import sys
83     _builtin = imp.load_module('__builtin__',
84                                *imp.find_module('__builtin__'))
85     sys.modules['builtins'] = _builtin
86     del _builtin
87
88 import _scons_builtins
89
90
91 try:
92     import hashlib
93 except ImportError:
94     # Pre-2.5 Python has no hashlib module.
95     try:
96         import_as('_scons_hashlib', 'hashlib')
97     except ImportError:
98         # If we failed importing our compatibility module, it probably
99         # means this version of Python has no md5 module.  Don't do
100         # anything and let the higher layer discover this fact, so it
101         # can fall back to using timestamp.
102         pass
103
104 try:
105     set
106 except NameError:
107     # Pre-2.4 Python has no native set type
108     import_as('_scons_sets', 'sets')
109     import builtins, sets
110     builtins.set = sets.Set
111
112
113 try:
114     import collections
115 except ImportError:
116     # Pre-2.4 Python has no collections module.
117     import_as('_scons_collections', 'collections')
118 else:
119     # Use the "imp" module to protect the imports below from fixers.
120     import imp
121     try:
122         collections.UserDict
123     except AttributeError:
124         _UserDict = imp.load_module('UserDict', *imp.find_module('UserDict'))
125         collections.UserDict = _UserDict.UserDict
126         del _UserDict
127     try:
128         collections.UserList
129     except AttributeError:
130         _UserList = imp.load_module('UserList', *imp.find_module('UserList'))
131         collections.UserList = _UserList.UserList
132         del _UserList
133     try:
134         collections.UserString
135     except AttributeError:
136         _UserString = imp.load_module('UserString',
137                                       *imp.find_module('UserString'))
138         collections.UserString = _UserString.UserString
139         del _UserString
140
141
142 try:
143     import dbm
144 except ImportError:
145     dbm = import_as('_scons_dbm', 'dbm')
146 try:
147     dbm.whichdb
148 except AttributeError:
149     # Pre-3.0 Python has no dbm.whichdb function.
150     import whichdb
151     dbm.whichdb = whichdb.whichdb
152     del whichdb
153
154
155 import fnmatch
156 try:
157     fnmatch.filter
158 except AttributeError:
159     # Pre-2.2 Python has no fnmatch.filter() function.
160     def filter(names, pat):
161         """Return the subset of the list NAMES that match PAT"""
162         import os,posixpath
163         result=[]
164         pat = os.path.normcase(pat)
165         if pat not in fnmatch._cache:
166             import re
167             res = fnmatch.translate(pat)
168             fnmatch._cache[pat] = re.compile(res)
169         match = fnmatch._cache[pat].match
170         if os.path is posixpath:
171             # normcase on posix is NOP. Optimize it away from the loop.
172             for name in names:
173                 if match(name):
174                     result.append(name)
175         else:
176             for name in names:
177                 if match(os.path.normcase(name)):
178                     result.append(name)
179         return result
180     fnmatch.filter = filter
181     del filter
182
183 try:
184     import io
185 except ImportError:
186     # Pre-2.6 Python has no io module.
187     import_as('_scons_io', 'io')
188
189 try:
190     import itertools
191 except ImportError:
192     # Pre-2.3 Python has no itertools module.
193     import_as('_scons_itertools', 'itertools')
194
195 # If we need the compatibility version of textwrap, it  must be imported
196 # before optparse, which uses it.
197 try:
198     import textwrap
199 except ImportError:
200     # Pre-2.3 Python has no textwrap module.
201     import_as('_scons_textwrap', 'textwrap')
202
203 try:
204     import optparse
205 except ImportError:
206     # Pre-2.3 Python has no optparse module.
207     import_as('_scons_optparse', 'optparse')
208
209 import os
210 try:
211     os.devnull
212 except AttributeError:
213     # Pre-2.4 Python has no os.devnull attribute
214     import sys
215     _names = sys.builtin_module_names
216     if 'posix' in _names:
217         os.devnull = '/dev/null'
218     elif 'nt' in _names:
219         os.devnull = 'nul'
220     os.path.devnull = os.devnull
221 try:
222     os.path.lexists
223 except AttributeError:
224     # Pre-2.4 Python has no os.path.lexists function
225     def lexists(path):
226         return os.path.exists(path) or os.path.islink(path)
227     os.path.lexists = lexists
228
229
230 try:
231     # Use the "imp" module to protect the import from fixers.
232     import imp
233     _cPickle = imp.load_module('cPickle', *imp.find_module('cPickle'))
234 except ImportError, e:
235     # The "cPickle" module has already been eliminated in favor of
236     # having "import pickle" import the fast version when available.
237     pass
238 else:
239     import sys
240     sys.modules['pickle'] = _cPickle
241     del _cPickle
242
243
244 try:
245     # Use the "imp" module to protect the import from fixers.
246     import imp
247     _cProfile = imp.load_module('cProfile', *imp.find_module('cProfile'))
248 except ImportError:
249     # The "cProfile" module has already been eliminated in favor of
250     # having "import profile" import the fast version when available.
251     pass
252 else:
253     import sys
254     sys.modules['profile'] = _cProfile
255     del _cProfile
256
257
258 try:
259     import platform
260 except ImportError:
261     # Pre-2.3 Python has no platform module.
262     import_as('_scons_platform', 'platform')
263
264
265 try:
266     import queue
267 except ImportError:
268     # Before Python 3.0, the 'queue' module was named 'Queue'.
269     import imp
270     file, filename, suffix_mode_type = imp.find_module('Queue')
271     imp.load_module('queue', file, filename, suffix_mode_type)
272
273
274 import shlex
275 try:
276     shlex.split
277 except AttributeError:
278     # Pre-2.3 Python has no shlex.split() function.
279     #
280     # The full white-space splitting semantics of shlex.split() are
281     # complicated to reproduce by hand, so just use a compatibility
282     # version of the shlex module cribbed from Python 2.5 with some
283     # minor modifications for older Python versions.
284     del shlex
285     import_as('_scons_shlex', 'shlex')
286
287
288 import shutil
289 try:
290     shutil.move
291 except AttributeError:
292     # Pre-2.3 Python has no shutil.move() function.
293     #
294     # Cribbed from Python 2.5.
295     import os
296
297     def move(src, dst):
298         """Recursively move a file or directory to another location.
299
300         If the destination is on our current filesystem, then simply use
301         rename.  Otherwise, copy src to the dst and then remove src.
302         A lot more could be done here...  A look at a mv.c shows a lot of
303         the issues this implementation glosses over.
304
305         """
306         try:
307             os.rename(src, dst)
308         except OSError:
309             if os.path.isdir(src):
310                 if shutil.destinsrc(src, dst):
311                     raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst)
312                 shutil.copytree(src, dst, symlinks=True)
313                 shutil.rmtree(src)
314             else:
315                 shutil.copy2(src,dst)
316                 os.unlink(src)
317     shutil.move = move
318     del move
319
320     def destinsrc(src, dst):
321         src = os.path.abspath(src)
322         return os.path.abspath(dst)[:len(src)] == src
323     shutil.destinsrc = destinsrc
324     del destinsrc
325
326
327 try:
328     import subprocess
329 except ImportError:
330     # Pre-2.4 Python has no subprocess module.
331     import_as('_scons_subprocess', 'subprocess')
332
333 import sys
334 try:
335     sys.intern
336 except AttributeError:
337     # Pre-2.6 Python has no sys.intern() function.
338     import builtins
339     try:
340         sys.intern = builtins.intern
341     except AttributeError:
342         # Pre-2.x Python has no builtin intern() function.
343         def intern(x):
344            return x
345         sys.intern = intern
346         del intern
347 try:
348     sys.maxsize
349 except AttributeError:
350     # Pre-2.6 Python has no sys.maxsize attribute
351     # Wrapping sys in () is silly, but protects it from 2to3 renames fixer
352     sys.maxsize = (sys).maxint
353
354
355 import tempfile
356 try:
357     tempfile.mkstemp
358 except AttributeError:
359     # Pre-2.3 Python has no tempfile.mkstemp function, so try to simulate it.
360     # adapted from the mkstemp implementation in python 3.
361     import os
362     import errno
363     def mkstemp(*args, **kw):
364         text = False
365         # TODO (1.5)
366         #if 'text' in kw :
367         if 'text' in kw.keys() :
368             text = kw['text']
369             del kw['text']
370         elif len( args ) == 4 :
371             text = args[3]
372             args = args[:3]
373         flags = os.O_RDWR | os.O_CREAT | os.O_EXCL
374         if not text and hasattr( os, 'O_BINARY' ) :
375             flags = flags | os.O_BINARY
376         while True:
377             try :
378                 name = tempfile.mktemp(*args, **kw)
379                 fd = os.open( name, flags, 0600 )
380                 return (fd, os.path.abspath(name))
381             except OSError, e:
382                 if e.errno == errno.EEXIST:
383                     continue
384                 raise
385
386     tempfile.mkstemp = mkstemp
387     del mkstemp
388
389
390 # Local Variables:
391 # tab-width:4
392 # indent-tabs-mode:nil
393 # End:
394 # vim: set expandtab tabstop=4 shiftwidth=4: