blob: 8650d450c3d42ea12fc88018d8f2de79f4c53f6e [file] [log] [blame]
Greg Ward2689e3d1999-03-22 14:52:19 +00001"""distutils.util
2
Greg Wardaebf7062000-04-04 02:05:59 +00003Miscellaneous utility functions -- anything that doesn't fit into
Greg Ward47527692000-09-30 18:49:14 +00004one of the other *util.py modules.
5"""
Greg Ward2689e3d1999-03-22 14:52:19 +00006
Greg Ward3ce77fd2000-03-02 01:49:45 +00007__revision__ = "$Id$"
Greg Ward2689e3d1999-03-22 14:52:19 +00008
Greg Ward1297b5c2000-09-30 20:37:56 +00009import sys, os, string, re
Tarek Ziadéa99dedf2009-07-16 15:35:45 +000010
Greg Ward1297b5c2000-09-30 20:37:56 +000011from distutils.errors import DistutilsPlatformError
12from distutils.dep_util import newer
Tarek Ziadéa99dedf2009-07-16 15:35:45 +000013from distutils.spawn import spawn, find_executable
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000014from distutils import log
Tarek Ziadéa99dedf2009-07-16 15:35:45 +000015from distutils.version import LooseVersion
Tarek Ziadéb9c1cfc2009-10-24 15:10:37 +000016from distutils.errors import DistutilsByteCompileError
Greg Wardaa458bc2000-04-22 15:14:58 +000017
Tarek Ziadé5633a802010-01-23 09:23:15 +000018_sysconfig = __import__('sysconfig')
Greg Ward50919292000-03-07 03:27:08 +000019
Tarek Ziadé0276c7a2010-01-26 21:21:54 +000020# kept for backward compatibility
21# since this API was relocated
22get_platform = _sysconfig.get_platform
23
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000024def convert_path(pathname):
25 """Return 'pathname' as a name that will work on the native filesystem.
Greg Ward50919292000-03-07 03:27:08 +000026
Greg Wardb8b263b2000-09-30 18:40:42 +000027 i.e. split it on '/' and put it back together again using the current
28 directory separator. Needed because filenames in the setup script are
29 always supplied in Unix style, and have to be converted to the local
30 convention before we can actually use them in the filesystem. Raises
Greg Ward47527692000-09-30 18:49:14 +000031 ValueError on non-Unix-ish systems if 'pathname' either starts or
32 ends with a slash.
Greg Wardb8b263b2000-09-30 18:40:42 +000033 """
Greg Ward7ec05352000-09-22 01:05:43 +000034 if os.sep == '/':
35 return pathname
Neal Norwitzb0df6a12002-08-13 17:42:57 +000036 if not pathname:
37 return pathname
38 if pathname[0] == '/':
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000039 raise ValueError("path '%s' cannot be absolute" % pathname)
Neal Norwitzb0df6a12002-08-13 17:42:57 +000040 if pathname[-1] == '/':
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000041 raise ValueError("path '%s' cannot end with '/'" % pathname)
Greg Ward7ec05352000-09-22 01:05:43 +000042
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000043 paths = pathname.split('/')
Jack Jansenb4cd5c12001-01-28 12:23:32 +000044 while '.' in paths:
45 paths.remove('.')
46 if not paths:
47 return os.curdir
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000048 return os.path.join(*paths)
Greg Ward1b4ede52000-03-22 00:22:44 +000049
50
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000051def change_root(new_root, pathname):
52 """Return 'pathname' with 'new_root' prepended.
53
54 If 'pathname' is relative, this is equivalent to
55 "os.path.join(new_root,pathname)".
Greg Ward67f75d42000-04-27 01:53:46 +000056 Otherwise, it requires making 'pathname' relative and then joining the
Greg Ward4b46ef92000-05-31 02:14:32 +000057 two, which is tricky on DOS/Windows and Mac OS.
58 """
59 if os.name == 'posix':
Greg Wardbe86bde2000-09-26 01:56:15 +000060 if not os.path.isabs(pathname):
61 return os.path.join(new_root, pathname)
Greg Ward4b46ef92000-05-31 02:14:32 +000062 else:
Greg Wardbe86bde2000-09-26 01:56:15 +000063 return os.path.join(new_root, pathname[1:])
Greg Ward67f75d42000-04-27 01:53:46 +000064
65 elif os.name == 'nt':
Greg Wardbe86bde2000-09-26 01:56:15 +000066 (drive, path) = os.path.splitdrive(pathname)
Greg Ward4b46ef92000-05-31 02:14:32 +000067 if path[0] == '\\':
68 path = path[1:]
Greg Wardbe86bde2000-09-26 01:56:15 +000069 return os.path.join(new_root, path)
Greg Ward67f75d42000-04-27 01:53:46 +000070
Marc-André Lemburg2544f512002-01-31 18:56:00 +000071 elif os.name == 'os2':
72 (drive, path) = os.path.splitdrive(pathname)
73 if path[0] == os.sep:
74 path = path[1:]
75 return os.path.join(new_root, path)
76
Greg Ward67f75d42000-04-27 01:53:46 +000077 elif os.name == 'mac':
Greg Wardf5855742000-09-21 01:23:35 +000078 if not os.path.isabs(pathname):
79 return os.path.join(new_root, pathname)
80 else:
81 # Chop off volume name from start of path
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000082 elements = pathname.split(":", 1)
Greg Wardf5855742000-09-21 01:23:35 +000083 pathname = ":" + elements[1]
84 return os.path.join(new_root, pathname)
Greg Ward67f75d42000-04-27 01:53:46 +000085
86 else:
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000087 raise DistutilsPlatformError("nothing known about "
88 "platform '%s'" % os.name)
Greg Ward67f75d42000-04-27 01:53:46 +000089
Gregory P. Smithe7e35ac2000-05-12 00:40:00 +000090_environ_checked = 0
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000091
92def check_environ():
93 """Ensure that 'os.environ' has all the environment variables needed.
94
95 We guarantee that users can use in config files, command-line options,
Greg Wardb8b263b2000-09-30 18:40:42 +000096 etc. Currently this includes:
97 HOME - user's home directory (Unix only)
98 PLAT - description of the current platform, including hardware
99 and OS (see 'get_platform()')
Greg Ward1b4ede52000-03-22 00:22:44 +0000100 """
Gregory P. Smithe7e35ac2000-05-12 00:40:00 +0000101 global _environ_checked
102 if _environ_checked:
103 return
104
Guido van Rossum8bc09652008-02-21 18:18:37 +0000105 if os.name == 'posix' and 'HOME' not in os.environ:
Greg Ward1b4ede52000-03-22 00:22:44 +0000106 import pwd
Greg Wardbe86bde2000-09-26 01:56:15 +0000107 os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
Greg Ward1b4ede52000-03-22 00:22:44 +0000108
Guido van Rossum8bc09652008-02-21 18:18:37 +0000109 if 'PLAT' not in os.environ:
Tarek Ziadé5633a802010-01-23 09:23:15 +0000110 os.environ['PLAT'] = _sysconfig.get_platform()
Greg Ward1b4ede52000-03-22 00:22:44 +0000111
Gregory P. Smithe7e35ac2000-05-12 00:40:00 +0000112 _environ_checked = 1
113
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000114def subst_vars(s, local_vars):
115 """Perform shell/Perl-style variable substitution on 'string'.
Greg Ward1b4ede52000-03-22 00:22:44 +0000116
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000117 Every occurrence of '$' followed by a name is considered a variable, and
Greg Ward47527692000-09-30 18:49:14 +0000118 variable is substituted by the value found in the 'local_vars'
119 dictionary, or in 'os.environ' if it's not in 'local_vars'.
120 'os.environ' is first checked/augmented to guarantee that it contains
121 certain values: see 'check_environ()'. Raise ValueError for any
122 variables not found in either 'local_vars' or 'os.environ'.
Greg Wardb8b263b2000-09-30 18:40:42 +0000123 """
Greg Wardbe86bde2000-09-26 01:56:15 +0000124 check_environ()
Greg Ward1b4ede52000-03-22 00:22:44 +0000125 def _subst (match, local_vars=local_vars):
126 var_name = match.group(1)
Guido van Rossum8bc09652008-02-21 18:18:37 +0000127 if var_name in local_vars:
Greg Wardbe86bde2000-09-26 01:56:15 +0000128 return str(local_vars[var_name])
Greg Ward1b4ede52000-03-22 00:22:44 +0000129 else:
130 return os.environ[var_name]
131
Greg Ward47527692000-09-30 18:49:14 +0000132 try:
Jeremy Hylton5e2d0762001-01-25 20:10:32 +0000133 return re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s)
Greg Ward47527692000-09-30 18:49:14 +0000134 except KeyError, var:
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000135 raise ValueError("invalid variable '$%s'" % var)
Greg Ward1b4ede52000-03-22 00:22:44 +0000136
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000137def grok_environment_error(exc, prefix="error: "):
138 """Generate a useful error message from an EnvironmentError.
Greg Ward7c1a6d42000-03-29 02:48:40 +0000139
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000140 This will generate an IOError or an OSError exception object.
141 Handles Python 1.5.1 and 1.5.2 styles, and
Greg Warde9055132000-06-17 02:16:46 +0000142 does what it can to deal with exception objects that don't have a
143 filename (which happens when the error is due to a two-file operation,
144 such as 'rename()' or 'link()'. Returns the error message as a string
145 prefixed with 'prefix'.
146 """
147 # check for Python 1.5.2-style {IO,OS}Error exception objects
Greg Wardbe86bde2000-09-26 01:56:15 +0000148 if hasattr(exc, 'filename') and hasattr(exc, 'strerror'):
Greg Warde9055132000-06-17 02:16:46 +0000149 if exc.filename:
150 error = prefix + "%s: %s" % (exc.filename, exc.strerror)
151 else:
152 # two-argument functions in posix module don't
153 # include the filename in the exception object!
154 error = prefix + "%s" % exc.strerror
155 else:
156 error = prefix + str(exc[-1])
157
158 return error
Greg Ward6a2a3db2000-06-24 20:40:02 +0000159
Greg Ward6a2a3db2000-06-24 20:40:02 +0000160# Needed by 'split_quoted()'
Martin v. Löwis1c0f1f92004-03-25 14:58:19 +0000161_wordchars_re = _squote_re = _dquote_re = None
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000162
Martin v. Löwis1c0f1f92004-03-25 14:58:19 +0000163def _init_regex():
164 global _wordchars_re, _squote_re, _dquote_re
165 _wordchars_re = re.compile(r'[^\\\'\"%s ]*' % string.whitespace)
166 _squote_re = re.compile(r"'(?:[^'\\]|\\.)*'")
167 _dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"')
Greg Ward6a2a3db2000-06-24 20:40:02 +0000168
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000169def split_quoted(s):
Greg Ward6a2a3db2000-06-24 20:40:02 +0000170 """Split a string up according to Unix shell-like rules for quotes and
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000171 backslashes.
172
173 In short: words are delimited by spaces, as long as those
Greg Ward6a2a3db2000-06-24 20:40:02 +0000174 spaces are not escaped by a backslash, or inside a quoted string.
175 Single and double quotes are equivalent, and the quote characters can
176 be backslash-escaped. The backslash is stripped from any two-character
177 escape sequence, leaving only the escaped character. The quote
178 characters are stripped from any quoted string. Returns a list of
179 words.
180 """
Greg Ward6a2a3db2000-06-24 20:40:02 +0000181 # This is a nice algorithm for splitting up a single string, since it
182 # doesn't require character-by-character examination. It was a little
183 # bit of a brain-bender to get it working right, though...
Martin v. Löwis1c0f1f92004-03-25 14:58:19 +0000184 if _wordchars_re is None: _init_regex()
Greg Ward6a2a3db2000-06-24 20:40:02 +0000185
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000186 s = s.strip()
Greg Ward6a2a3db2000-06-24 20:40:02 +0000187 words = []
188 pos = 0
189
190 while s:
191 m = _wordchars_re.match(s, pos)
192 end = m.end()
193 if end == len(s):
194 words.append(s[:end])
195 break
196
Greg Ward2b042de2000-08-08 14:38:13 +0000197 if s[end] in string.whitespace: # unescaped, unquoted whitespace: now
Greg Ward6a2a3db2000-06-24 20:40:02 +0000198 words.append(s[:end]) # we definitely have a word delimiter
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000199 s = s[end:].lstrip()
Greg Ward6a2a3db2000-06-24 20:40:02 +0000200 pos = 0
201
202 elif s[end] == '\\': # preserve whatever is being escaped;
203 # will become part of the current word
204 s = s[:end] + s[end+1:]
205 pos = end+1
206
207 else:
208 if s[end] == "'": # slurp singly-quoted string
209 m = _squote_re.match(s, end)
210 elif s[end] == '"': # slurp doubly-quoted string
211 m = _dquote_re.match(s, end)
212 else:
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000213 raise RuntimeError("this can't happen "
214 "(bad char '%c')" % s[end])
Greg Ward6a2a3db2000-06-24 20:40:02 +0000215
216 if m is None:
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000217 raise ValueError("bad string (mismatched %s quotes?)" % s[end])
Greg Ward6a2a3db2000-06-24 20:40:02 +0000218
219 (beg, end) = m.span()
220 s = s[:beg] + s[beg+1:end-1] + s[end:]
221 pos = m.end() - 2
222
223 if pos >= len(s):
224 words.append(s)
225 break
226
227 return words
228
Greg Ward1c16ac32000-08-02 01:37:30 +0000229
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000230def execute(func, args, msg=None, verbose=0, dry_run=0):
231 """Perform some action that affects the outside world.
Greg Ward1c16ac32000-08-02 01:37:30 +0000232
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000233 eg. by writing to the filesystem). Such actions are special because
234 they are disabled by the 'dry_run' flag. This method takes care of all
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000235 that bureaucracy for you; all you have to do is supply the
236 function to call and an argument tuple for it (to embody the
237 "external action" being performed), and an optional message to
238 print.
Greg Ward1c16ac32000-08-02 01:37:30 +0000239 """
Greg Ward1c16ac32000-08-02 01:37:30 +0000240 if msg is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000241 msg = "%s%r" % (func.__name__, args)
Fred Drakeb94b8492001-12-06 20:51:35 +0000242 if msg[-2:] == ',)': # correct for singleton tuple
Greg Ward1c16ac32000-08-02 01:37:30 +0000243 msg = msg[0:-2] + ')'
244
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000245 log.info(msg)
Greg Ward1c16ac32000-08-02 01:37:30 +0000246 if not dry_run:
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000247 func(*args)
Greg Ward1c16ac32000-08-02 01:37:30 +0000248
Greg Ward817dc092000-09-25 01:25:06 +0000249
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000250def strtobool(val):
Greg Ward817dc092000-09-25 01:25:06 +0000251 """Convert a string representation of truth to true (1) or false (0).
Tim Peters182b5ac2004-07-18 06:16:08 +0000252
Greg Ward817dc092000-09-25 01:25:06 +0000253 True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
254 are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
255 'val' is anything else.
256 """
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000257 val = val.lower()
Greg Ward817dc092000-09-25 01:25:06 +0000258 if val in ('y', 'yes', 't', 'true', 'on', '1'):
259 return 1
260 elif val in ('n', 'no', 'f', 'false', 'off', '0'):
261 return 0
262 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000263 raise ValueError, "invalid truth value %r" % (val,)
Greg Ward1297b5c2000-09-30 20:37:56 +0000264
265
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000266def byte_compile(py_files, optimize=0, force=0, prefix=None, base_dir=None,
267 verbose=1, dry_run=0, direct=None):
Greg Wardf217e212000-10-01 23:49:30 +0000268 """Byte-compile a collection of Python source files to either .pyc
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000269 or .pyo files in the same directory.
270
271 'py_files' is a list of files to compile; any files that don't end in
272 ".py" are silently skipped. 'optimize' must be one of the following:
Greg Ward1297b5c2000-09-30 20:37:56 +0000273 0 - don't optimize (generate .pyc)
274 1 - normal optimization (like "python -O")
275 2 - extra optimization (like "python -OO")
276 If 'force' is true, all files are recompiled regardless of
277 timestamps.
278
279 The source filename encoded in each bytecode file defaults to the
280 filenames listed in 'py_files'; you can modify these with 'prefix' and
281 'basedir'. 'prefix' is a string that will be stripped off of each
282 source filename, and 'base_dir' is a directory name that will be
283 prepended (after 'prefix' is stripped). You can supply either or both
284 (or neither) of 'prefix' and 'base_dir', as you wish.
285
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000286 If 'dry_run' is true, doesn't actually do anything that would
287 affect the filesystem.
Greg Ward1297b5c2000-09-30 20:37:56 +0000288
289 Byte-compilation is either done directly in this interpreter process
290 with the standard py_compile module, or indirectly by writing a
291 temporary script and executing it. Normally, you should let
292 'byte_compile()' figure out to use direct compilation or not (see
293 the source for details). The 'direct' flag is used by the script
294 generated in indirect mode; unless you know what you're doing, leave
295 it set to None.
296 """
Tarek Ziadéb9c1cfc2009-10-24 15:10:37 +0000297 # nothing is done if sys.dont_write_bytecode is True
298 if sys.dont_write_bytecode:
Tarek Ziadé1733c932009-10-24 15:51:30 +0000299 raise DistutilsByteCompileError('byte-compiling is disabled.')
Tarek Ziadéb9c1cfc2009-10-24 15:10:37 +0000300
Greg Ward1297b5c2000-09-30 20:37:56 +0000301 # First, if the caller didn't force us into direct or indirect mode,
302 # figure out which mode we should be in. We take a conservative
303 # approach: choose direct mode *only* if the current interpreter is
304 # in debug mode and optimize is 0. If we're not in debug mode (-O
305 # or -OO), we don't know which level of optimization this
306 # interpreter is running with, so we can't do direct
307 # byte-compilation and be certain that it's the right thing. Thus,
308 # always compile indirectly if the current interpreter is in either
309 # optimize mode, or if either optimization level was requested by
310 # the caller.
311 if direct is None:
312 direct = (__debug__ and optimize == 0)
313
314 # "Indirect" byte-compilation: write a temporary script and then
315 # run it with the appropriate flags.
316 if not direct:
Marc-André Lemburg03750792002-12-03 08:45:11 +0000317 try:
318 from tempfile import mkstemp
319 (script_fd, script_name) = mkstemp(".py")
320 except ImportError:
321 from tempfile import mktemp
322 (script_fd, script_name) = None, mktemp(".py")
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000323 log.info("writing byte-compilation script '%s'", script_name)
Greg Ward1297b5c2000-09-30 20:37:56 +0000324 if not dry_run:
Marc-André Lemburg03750792002-12-03 08:45:11 +0000325 if script_fd is not None:
326 script = os.fdopen(script_fd, "w")
327 else:
328 script = open(script_name, "w")
Greg Ward1297b5c2000-09-30 20:37:56 +0000329
330 script.write("""\
331from distutils.util import byte_compile
332files = [
333""")
Greg Ward9216cfe2000-10-03 03:31:05 +0000334
335 # XXX would be nice to write absolute filenames, just for
336 # safety's sake (script should be more robust in the face of
337 # chdir'ing before running it). But this requires abspath'ing
338 # 'prefix' as well, and that breaks the hack in build_lib's
339 # 'byte_compile()' method that carefully tacks on a trailing
340 # slash (os.sep really) to make sure the prefix here is "just
341 # right". This whole prefix business is rather delicate -- the
342 # problem is that it's really a directory, but I'm treating it
343 # as a dumb string, so trailing slashes and so forth matter.
344
345 #py_files = map(os.path.abspath, py_files)
346 #if prefix:
347 # prefix = os.path.abspath(prefix)
348
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000349 script.write(",\n".join(map(repr, py_files)) + "]\n")
Greg Ward1297b5c2000-09-30 20:37:56 +0000350 script.write("""
Walter Dörwald70a6b492004-02-12 17:35:32 +0000351byte_compile(files, optimize=%r, force=%r,
352 prefix=%r, base_dir=%r,
353 verbose=%r, dry_run=0,
Greg Ward1297b5c2000-09-30 20:37:56 +0000354 direct=1)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000355""" % (optimize, force, prefix, base_dir, verbose))
Greg Ward1297b5c2000-09-30 20:37:56 +0000356
357 script.close()
358
359 cmd = [sys.executable, script_name]
360 if optimize == 1:
361 cmd.insert(1, "-O")
362 elif optimize == 2:
363 cmd.insert(1, "-OO")
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000364 spawn(cmd, dry_run=dry_run)
Greg Ward9216cfe2000-10-03 03:31:05 +0000365 execute(os.remove, (script_name,), "removing %s" % script_name,
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000366 dry_run=dry_run)
Fred Drakeb94b8492001-12-06 20:51:35 +0000367
Greg Ward1297b5c2000-09-30 20:37:56 +0000368 # "Direct" byte-compilation: use the py_compile module to compile
369 # right here, right now. Note that the script generated in indirect
370 # mode simply calls 'byte_compile()' in direct mode, a weird sort of
371 # cross-process recursion. Hey, it works!
372 else:
373 from py_compile import compile
374
375 for file in py_files:
376 if file[-3:] != ".py":
Greg Wardf217e212000-10-01 23:49:30 +0000377 # This lets us be lazy and not filter filenames in
378 # the "install_lib" command.
379 continue
Greg Ward1297b5c2000-09-30 20:37:56 +0000380
381 # Terminology from the py_compile module:
382 # cfile - byte-compiled file
383 # dfile - purported source filename (same as 'file' by default)
384 cfile = file + (__debug__ and "c" or "o")
385 dfile = file
386 if prefix:
387 if file[:len(prefix)] != prefix:
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000388 raise ValueError("invalid prefix: filename %r doesn't "
389 "start with %r" % (file, prefix))
Greg Ward1297b5c2000-09-30 20:37:56 +0000390 dfile = dfile[len(prefix):]
391 if base_dir:
392 dfile = os.path.join(base_dir, dfile)
393
394 cfile_base = os.path.basename(cfile)
395 if direct:
396 if force or newer(file, cfile):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000397 log.info("byte-compiling %s to %s", file, cfile_base)
Greg Ward1297b5c2000-09-30 20:37:56 +0000398 if not dry_run:
399 compile(file, cfile, dfile)
400 else:
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000401 log.debug("skipping byte-compilation of %s to %s",
402 file, cfile_base)
Greg Ward1297b5c2000-09-30 20:37:56 +0000403
Andrew M. Kuchlingdf66df02001-03-22 03:03:41 +0000404
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000405def rfc822_escape(header):
Andrew M. Kuchlingdf66df02001-03-22 03:03:41 +0000406 """Return a version of the string escaped for inclusion in an
Andrew M. Kuchling88b08842001-03-23 17:30:26 +0000407 RFC-822 header, by ensuring there are 8 spaces space after each newline.
Andrew M. Kuchlingdf66df02001-03-22 03:03:41 +0000408 """
Tarek Ziadé4f383172009-12-06 09:22:40 +0000409 lines = header.split('\n')
410 sep = '\n' + 8 * ' '
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000411 return sep.join(lines)
Tarek Ziadéa99dedf2009-07-16 15:35:45 +0000412
413_RE_VERSION = re.compile('(\d+\.\d+(\.\d+)*)')
414_MAC_OS_X_LD_VERSION = re.compile('^@\(#\)PROGRAM:ld PROJECT:ld64-((\d+)(\.\d+)*)')
415
416def _find_ld_version():
417 """Finds the ld version. The version scheme differs under Mac OSX."""
418 if sys.platform == 'darwin':
419 return _find_exe_version('ld -v', _MAC_OS_X_LD_VERSION)
420 else:
421 return _find_exe_version('ld -v')
422
423def _find_exe_version(cmd, pattern=_RE_VERSION):
424 """Find the version of an executable by running `cmd` in the shell.
425
426 `pattern` is a compiled regular expression. If not provided, default
427 to _RE_VERSION. If the command is not found, or the output does not
428 match the mattern, returns None.
429 """
430 from subprocess import Popen, PIPE
431 executable = cmd.split()[0]
432 if find_executable(executable) is None:
433 return None
434 pipe = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
435 try:
436 stdout, stderr = pipe.stdout.read(), pipe.stderr.read()
437 finally:
438 pipe.stdout.close()
439 pipe.stderr.close()
440 # some commands like ld under MacOS X, will give the
441 # output in the stderr, rather than stdout.
442 if stdout != '':
443 out_string = stdout
444 else:
445 out_string = stderr
446
447 result = pattern.search(out_string)
448 if result is None:
449 return None
450 return LooseVersion(result.group(1))
451
452def get_compiler_versions():
453 """Returns a tuple providing the versions of gcc, ld and dllwrap
454
455 For each command, if a command is not found, None is returned.
456 Otherwise a LooseVersion instance is returned.
457 """
458 gcc = _find_exe_version('gcc -dumpversion')
459 ld = _find_ld_version()
460 dllwrap = _find_exe_version('dllwrap --version')
461 return gcc, ld, dllwrap