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