cc14b92aa19e4f610bdcdd4f581913088c4be03a
[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 __builtin__ 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 __builtin__ name space come from
39 our 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.
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     imp.load_module(name, file, filename, suffix_mode_type)
75
76 import builtins
77
78 try:
79     import hashlib
80 except ImportError:
81     # Pre-2.5 Python has no hashlib module.
82     try:
83         import_as('_scons_hashlib', 'hashlib')
84     except ImportError:
85         # If we failed importing our compatibility module, it probably
86         # means this version of Python has no md5 module.  Don't do
87         # anything and let the higher layer discover this fact, so it
88         # can fall back to using timestamp.
89         pass
90
91 try:
92     set
93 except NameError:
94     # Pre-2.4 Python has no native set type
95     import_as('_scons_sets', 'sets')
96     import __builtin__, sets
97     __builtin__.set = sets.Set
98
99
100 try:
101     import collections
102 except ImportError:
103     # Pre-2.4 Python has no collections module.
104     import_as('_scons_collections', 'collections')
105 else:
106     try:
107         collections.UserDict
108     except AttributeError:
109         import UserDict
110         collections.UserDict = UserDict.UserDict
111         del UserDict
112     try:
113         collections.UserList
114     except AttributeError:
115         import UserList
116         collections.UserList = UserList.UserList
117         del UserList
118     try:
119         collections.UserString
120     except AttributeError:
121         import UserString
122         collections.UserString = UserString.UserString
123         del UserString
124
125
126 import fnmatch
127 try:
128     fnmatch.filter
129 except AttributeError:
130     # Pre-2.2 Python has no fnmatch.filter() function.
131     def filter(names, pat):
132         """Return the subset of the list NAMES that match PAT"""
133         import os,posixpath
134         result=[]
135         pat = os.path.normcase(pat)
136         if pat not in fnmatch._cache:
137             import re
138             res = fnmatch.translate(pat)
139             fnmatch._cache[pat] = re.compile(res)
140         match = fnmatch._cache[pat].match
141         if os.path is posixpath:
142             # normcase on posix is NOP. Optimize it away from the loop.
143             for name in names:
144                 if match(name):
145                     result.append(name)
146         else:
147             for name in names:
148                 if match(os.path.normcase(name)):
149                     result.append(name)
150         return result
151     fnmatch.filter = filter
152     del filter
153
154 try:
155     import io
156 except ImportError:
157     # Pre-2.6 Python has no io module.
158     import_as('_scons_io', 'io')
159
160 try:
161     import itertools
162 except ImportError:
163     # Pre-2.3 Python has no itertools module.
164     import_as('_scons_itertools', 'itertools')
165
166 # If we need the compatibility version of textwrap, it  must be imported
167 # before optparse, which uses it.
168 try:
169     import textwrap
170 except ImportError:
171     # Pre-2.3 Python has no textwrap module.
172     import_as('_scons_textwrap', 'textwrap')
173
174 try:
175     import optparse
176 except ImportError:
177     # Pre-2.3 Python has no optparse module.
178     import_as('_scons_optparse', 'optparse')
179
180 import os
181 try:
182     os.devnull
183 except AttributeError:
184     # Pre-2.4 Python has no os.devnull attribute
185     import sys
186     _names = sys.builtin_module_names
187     if 'posix' in _names:
188         os.devnull = '/dev/null'
189     elif 'nt' in _names:
190         os.devnull = 'nul'
191     os.path.devnull = os.devnull
192 try:
193     os.path.lexists
194 except AttributeError:
195     # Pre-2.4 Python has no os.path.lexists function
196     def lexists(path):
197         return os.path.exists(path) or os.path.islink(path)
198     os.path.lexists = lexists
199
200
201 try:
202     # Use the "imp" module to protect the import from fixers.
203     import imp
204     cPickle = imp.load_module('cPickle', *imp.find_module('cPickle'))
205 except ImportError, e:
206     # The "cPickle" module has already been eliminated in favor of
207     # having "import pickle" import the fast version when available.
208     pass
209 else:
210     import sys
211     sys.modules['pickle'] = cPickle
212     del cPickle
213
214
215 try:
216     # Use the "imp" module to protect the import from fixers.
217     import imp
218     cProfile = imp.load_module('cProfile', *imp.find_module('cProfile'))
219 except ImportError:
220     # The "cProfile" module has already been eliminated in favor of
221     # having "import profile" import the fast version when available.
222     pass
223 else:
224     import sys
225     sys.modules['profile'] = cProfile
226     del cProfile
227
228
229 try:
230     import platform
231 except ImportError:
232     # Pre-2.3 Python has no platform module.
233     import_as('_scons_platform', 'platform')
234
235
236 try:
237     import queue
238 except ImportError:
239     # Before Python 3.0, the 'queue' module was named 'Queue'.
240     import imp
241     file, filename, suffix_mode_type = imp.find_module('Queue')
242     imp.load_module('queue', file, filename, suffix_mode_type)
243
244
245 import shlex
246 try:
247     shlex.split
248 except AttributeError:
249     # Pre-2.3 Python has no shlex.split() function.
250     #
251     # The full white-space splitting semantics of shlex.split() are
252     # complicated to reproduce by hand, so just use a compatibility
253     # version of the shlex module cribbed from Python 2.5 with some
254     # minor modifications for older Python versions.
255     del shlex
256     import_as('_scons_shlex', 'shlex')
257
258
259 import shutil
260 try:
261     shutil.move
262 except AttributeError:
263     # Pre-2.3 Python has no shutil.move() function.
264     #
265     # Cribbed from Python 2.5.
266     import os
267
268     def move(src, dst):
269         """Recursively move a file or directory to another location.
270
271         If the destination is on our current filesystem, then simply use
272         rename.  Otherwise, copy src to the dst and then remove src.
273         A lot more could be done here...  A look at a mv.c shows a lot of
274         the issues this implementation glosses over.
275
276         """
277         try:
278             os.rename(src, dst)
279         except OSError:
280             if os.path.isdir(src):
281                 if shutil.destinsrc(src, dst):
282                     raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst)
283                 shutil.copytree(src, dst, symlinks=True)
284                 shutil.rmtree(src)
285             else:
286                 shutil.copy2(src,dst)
287                 os.unlink(src)
288     shutil.move = move
289     del move
290
291     def destinsrc(src, dst):
292         src = os.path.abspath(src)
293         return os.path.abspath(dst)[:len(src)] == src
294     shutil.destinsrc = destinsrc
295     del destinsrc
296
297
298 try:
299     import subprocess
300 except ImportError:
301     # Pre-2.4 Python has no subprocess module.
302     import_as('_scons_subprocess', 'subprocess')
303
304 import sys
305 try:
306     sys.intern
307 except AttributeError:
308     # Pre-2.6 Python has no sys.intern() function.
309     import __builtin__
310     try:
311         sys.intern = __builtin__.intern
312     except AttributeError:
313         # Pre-2.x Python has no builtin intern() function.
314         def intern(x):
315            return x
316         sys.intern = intern
317         del intern
318 try:
319     sys.maxsize
320 except AttributeError:
321     # Pre-2.6 Python has no sys.maxsize attribute
322     # Wrapping sys in () is silly, but protects it from 2to3 renames fixer
323     sys.maxsize = (sys).maxint
324
325
326 import tempfile
327 try:
328     tempfile.mkstemp
329 except AttributeError:
330     # Pre-2.3 Python has no tempfile.mkstemp function, so try to simulate it.
331     # adapted from the mkstemp implementation in python 3.
332     import os
333     import errno
334     def mkstemp(*args, **kw):
335         text = False
336         # TODO (1.5)
337         #if 'text' in kw :
338         if 'text' in kw.keys() :
339             text = kw['text']
340             del kw['text']
341         elif len( args ) == 4 :
342             text = args[3]
343             args = args[:3]
344         flags = os.O_RDWR | os.O_CREAT | os.O_EXCL
345         if not text and hasattr( os, 'O_BINARY' ) :
346             flags = flags | os.O_BINARY
347         while True:
348             try :
349                 name = tempfile.mktemp(*args, **kw)
350                 fd = os.open( name, flags, 0600 )
351                 return (fd, os.path.abspath(name))
352             except OSError, e:
353                 if e.errno == errno.EEXIST:
354                     continue
355                 raise
356
357     tempfile.mkstemp = mkstemp
358     del mkstemp
359
360 try:
361     # pre-2.7 doesn't have the memoryview() built-in
362     memoryview
363 except NameError:
364     class memoryview:
365         from types import SliceType
366         def __init__(self, obj):
367             # wrapping buffer in () keeps the fixer from changing it
368             self.obj = (buffer)(obj)
369         def __getitem__(self, indx):
370             if isinstance(indx, self.SliceType):
371                 return self.obj[indx.start:indx.stop]
372             else:
373                 return self.obj[indx]
374     import __builtin__
375     __builtin__.memoryview = memoryview
376
377
378 # Local Variables:
379 # tab-width:4
380 # indent-tabs-mode:nil
381 # End:
382 # vim: set expandtab tabstop=4 shiftwidth=4: