blob: 18d0d2ef4c4167cd864c289f585fc16f2681fe8a [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é3757fbb2009-07-02 14:20:47 +000020def convert_path(pathname):
21 """Return 'pathname' as a name that will work on the native filesystem.
Greg Ward50919292000-03-07 03:27:08 +000022
Greg Wardb8b263b2000-09-30 18:40:42 +000023 i.e. split it on '/' and put it back together again using the current
24 directory separator. Needed because filenames in the setup script are
25 always supplied in Unix style, and have to be converted to the local
26 convention before we can actually use them in the filesystem. Raises
Greg Ward47527692000-09-30 18:49:14 +000027 ValueError on non-Unix-ish systems if 'pathname' either starts or
28 ends with a slash.
Greg Wardb8b263b2000-09-30 18:40:42 +000029 """
Greg Ward7ec05352000-09-22 01:05:43 +000030 if os.sep == '/':
31 return pathname
Neal Norwitzb0df6a12002-08-13 17:42:57 +000032 if not pathname:
33 return pathname
34 if pathname[0] == '/':
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000035 raise ValueError("path '%s' cannot be absolute" % pathname)
Neal Norwitzb0df6a12002-08-13 17:42:57 +000036 if pathname[-1] == '/':
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000037 raise ValueError("path '%s' cannot end with '/'" % pathname)
Greg Ward7ec05352000-09-22 01:05:43 +000038
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000039 paths = pathname.split('/')
Jack Jansenb4cd5c12001-01-28 12:23:32 +000040 while '.' in paths:
41 paths.remove('.')
42 if not paths:
43 return os.curdir
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000044 return os.path.join(*paths)
Greg Ward1b4ede52000-03-22 00:22:44 +000045
46
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000047def change_root(new_root, pathname):
48 """Return 'pathname' with 'new_root' prepended.
49
50 If 'pathname' is relative, this is equivalent to
51 "os.path.join(new_root,pathname)".
Greg Ward67f75d42000-04-27 01:53:46 +000052 Otherwise, it requires making 'pathname' relative and then joining the
Greg Ward4b46ef92000-05-31 02:14:32 +000053 two, which is tricky on DOS/Windows and Mac OS.
54 """
55 if os.name == 'posix':
Greg Wardbe86bde2000-09-26 01:56:15 +000056 if not os.path.isabs(pathname):
57 return os.path.join(new_root, pathname)
Greg Ward4b46ef92000-05-31 02:14:32 +000058 else:
Greg Wardbe86bde2000-09-26 01:56:15 +000059 return os.path.join(new_root, pathname[1:])
Greg Ward67f75d42000-04-27 01:53:46 +000060
61 elif os.name == 'nt':
Greg Wardbe86bde2000-09-26 01:56:15 +000062 (drive, path) = os.path.splitdrive(pathname)
Greg Ward4b46ef92000-05-31 02:14:32 +000063 if path[0] == '\\':
64 path = path[1:]
Greg Wardbe86bde2000-09-26 01:56:15 +000065 return os.path.join(new_root, path)
Greg Ward67f75d42000-04-27 01:53:46 +000066
Marc-André Lemburg2544f512002-01-31 18:56:00 +000067 elif os.name == 'os2':
68 (drive, path) = os.path.splitdrive(pathname)
69 if path[0] == os.sep:
70 path = path[1:]
71 return os.path.join(new_root, path)
72
Greg Ward67f75d42000-04-27 01:53:46 +000073 elif os.name == 'mac':
Greg Wardf5855742000-09-21 01:23:35 +000074 if not os.path.isabs(pathname):
75 return os.path.join(new_root, pathname)
76 else:
77 # Chop off volume name from start of path
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000078 elements = pathname.split(":", 1)
Greg Wardf5855742000-09-21 01:23:35 +000079 pathname = ":" + elements[1]
80 return os.path.join(new_root, pathname)
Greg Ward67f75d42000-04-27 01:53:46 +000081
82 else:
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000083 raise DistutilsPlatformError("nothing known about "
84 "platform '%s'" % os.name)
Greg Ward67f75d42000-04-27 01:53:46 +000085
Gregory P. Smithe7e35ac2000-05-12 00:40:00 +000086_environ_checked = 0
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000087
88def check_environ():
89 """Ensure that 'os.environ' has all the environment variables needed.
90
91 We guarantee that users can use in config files, command-line options,
Greg Wardb8b263b2000-09-30 18:40:42 +000092 etc. Currently this includes:
93 HOME - user's home directory (Unix only)
94 PLAT - description of the current platform, including hardware
95 and OS (see 'get_platform()')
Greg Ward1b4ede52000-03-22 00:22:44 +000096 """
Gregory P. Smithe7e35ac2000-05-12 00:40:00 +000097 global _environ_checked
98 if _environ_checked:
99 return
100
Guido van Rossum8bc09652008-02-21 18:18:37 +0000101 if os.name == 'posix' and 'HOME' not in os.environ:
Greg Ward1b4ede52000-03-22 00:22:44 +0000102 import pwd
Greg Wardbe86bde2000-09-26 01:56:15 +0000103 os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
Greg Ward1b4ede52000-03-22 00:22:44 +0000104
Guido van Rossum8bc09652008-02-21 18:18:37 +0000105 if 'PLAT' not in os.environ:
Tarek Ziadé5633a802010-01-23 09:23:15 +0000106 os.environ['PLAT'] = _sysconfig.get_platform()
Greg Ward1b4ede52000-03-22 00:22:44 +0000107
Gregory P. Smithe7e35ac2000-05-12 00:40:00 +0000108 _environ_checked = 1
109
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000110def subst_vars(s, local_vars):
111 """Perform shell/Perl-style variable substitution on 'string'.
Greg Ward1b4ede52000-03-22 00:22:44 +0000112
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000113 Every occurrence of '$' followed by a name is considered a variable, and
Greg Ward47527692000-09-30 18:49:14 +0000114 variable is substituted by the value found in the 'local_vars'
115 dictionary, or in 'os.environ' if it's not in 'local_vars'.
116 'os.environ' is first checked/augmented to guarantee that it contains
117 certain values: see 'check_environ()'. Raise ValueError for any
118 variables not found in either 'local_vars' or 'os.environ'.
Greg Wardb8b263b2000-09-30 18:40:42 +0000119 """
Greg Wardbe86bde2000-09-26 01:56:15 +0000120 check_environ()
Greg Ward1b4ede52000-03-22 00:22:44 +0000121 def _subst (match, local_vars=local_vars):
122 var_name = match.group(1)
Guido van Rossum8bc09652008-02-21 18:18:37 +0000123 if var_name in local_vars:
Greg Wardbe86bde2000-09-26 01:56:15 +0000124 return str(local_vars[var_name])
Greg Ward1b4ede52000-03-22 00:22:44 +0000125 else:
126 return os.environ[var_name]
127
Greg Ward47527692000-09-30 18:49:14 +0000128 try:
Jeremy Hylton5e2d0762001-01-25 20:10:32 +0000129 return re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s)
Greg Ward47527692000-09-30 18:49:14 +0000130 except KeyError, var:
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000131 raise ValueError("invalid variable '$%s'" % var)
Greg Ward1b4ede52000-03-22 00:22:44 +0000132
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000133def grok_environment_error(exc, prefix="error: "):
134 """Generate a useful error message from an EnvironmentError.
Greg Ward7c1a6d42000-03-29 02:48:40 +0000135
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000136 This will generate an IOError or an OSError exception object.
137 Handles Python 1.5.1 and 1.5.2 styles, and
Greg Warde9055132000-06-17 02:16:46 +0000138 does what it can to deal with exception objects that don't have a
139 filename (which happens when the error is due to a two-file operation,
140 such as 'rename()' or 'link()'. Returns the error message as a string
141 prefixed with 'prefix'.
142 """
143 # check for Python 1.5.2-style {IO,OS}Error exception objects
Greg Wardbe86bde2000-09-26 01:56:15 +0000144 if hasattr(exc, 'filename') and hasattr(exc, 'strerror'):
Greg Warde9055132000-06-17 02:16:46 +0000145 if exc.filename:
146 error = prefix + "%s: %s" % (exc.filename, exc.strerror)
147 else:
148 # two-argument functions in posix module don't
149 # include the filename in the exception object!
150 error = prefix + "%s" % exc.strerror
151 else:
152 error = prefix + str(exc[-1])
153
154 return error
Greg Ward6a2a3db2000-06-24 20:40:02 +0000155
Greg Ward6a2a3db2000-06-24 20:40:02 +0000156# Needed by 'split_quoted()'
Martin v. Löwis1c0f1f92004-03-25 14:58:19 +0000157_wordchars_re = _squote_re = _dquote_re = None
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000158
Martin v. Löwis1c0f1f92004-03-25 14:58:19 +0000159def _init_regex():
160 global _wordchars_re, _squote_re, _dquote_re
161 _wordchars_re = re.compile(r'[^\\\'\"%s ]*' % string.whitespace)
162 _squote_re = re.compile(r"'(?:[^'\\]|\\.)*'")
163 _dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"')
Greg Ward6a2a3db2000-06-24 20:40:02 +0000164
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000165def split_quoted(s):
Greg Ward6a2a3db2000-06-24 20:40:02 +0000166 """Split a string up according to Unix shell-like rules for quotes and
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000167 backslashes.
168
169 In short: words are delimited by spaces, as long as those
Greg Ward6a2a3db2000-06-24 20:40:02 +0000170 spaces are not escaped by a backslash, or inside a quoted string.
171 Single and double quotes are equivalent, and the quote characters can
172 be backslash-escaped. The backslash is stripped from any two-character
173 escape sequence, leaving only the escaped character. The quote
174 characters are stripped from any quoted string. Returns a list of
175 words.
176 """
Greg Ward6a2a3db2000-06-24 20:40:02 +0000177 # This is a nice algorithm for splitting up a single string, since it
178 # doesn't require character-by-character examination. It was a little
179 # bit of a brain-bender to get it working right, though...
Martin v. Löwis1c0f1f92004-03-25 14:58:19 +0000180 if _wordchars_re is None: _init_regex()
Greg Ward6a2a3db2000-06-24 20:40:02 +0000181
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000182 s = s.strip()
Greg Ward6a2a3db2000-06-24 20:40:02 +0000183 words = []
184 pos = 0
185
186 while s:
187 m = _wordchars_re.match(s, pos)
188 end = m.end()
189 if end == len(s):
190 words.append(s[:end])
191 break
192
Greg Ward2b042de2000-08-08 14:38:13 +0000193 if s[end] in string.whitespace: # unescaped, unquoted whitespace: now
Greg Ward6a2a3db2000-06-24 20:40:02 +0000194 words.append(s[:end]) # we definitely have a word delimiter
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000195 s = s[end:].lstrip()
Greg Ward6a2a3db2000-06-24 20:40:02 +0000196 pos = 0
197
198 elif s[end] == '\\': # preserve whatever is being escaped;
199 # will become part of the current word
200 s = s[:end] + s[end+1:]
201 pos = end+1
202
203 else:
204 if s[end] == "'": # slurp singly-quoted string
205 m = _squote_re.match(s, end)
206 elif s[end] == '"': # slurp doubly-quoted string
207 m = _dquote_re.match(s, end)
208 else:
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000209 raise RuntimeError("this can't happen "
210 "(bad char '%c')" % s[end])
Greg Ward6a2a3db2000-06-24 20:40:02 +0000211
212 if m is None:
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000213 raise ValueError("bad string (mismatched %s quotes?)" % s[end])
Greg Ward6a2a3db2000-06-24 20:40:02 +0000214
215 (beg, end) = m.span()
216 s = s[:beg] + s[beg+1:end-1] + s[end:]
217 pos = m.end() - 2
218
219 if pos >= len(s):
220 words.append(s)
221 break
222
223 return words
224
Greg Ward1c16ac32000-08-02 01:37:30 +0000225
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000226def execute(func, args, msg=None, verbose=0, dry_run=0):
227 """Perform some action that affects the outside world.
Greg Ward1c16ac32000-08-02 01:37:30 +0000228
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000229 eg. by writing to the filesystem). Such actions are special because
230 they are disabled by the 'dry_run' flag. This method takes care of all
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000231 that bureaucracy for you; all you have to do is supply the
232 function to call and an argument tuple for it (to embody the
233 "external action" being performed), and an optional message to
234 print.
Greg Ward1c16ac32000-08-02 01:37:30 +0000235 """
Greg Ward1c16ac32000-08-02 01:37:30 +0000236 if msg is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000237 msg = "%s%r" % (func.__name__, args)
Fred Drakeb94b8492001-12-06 20:51:35 +0000238 if msg[-2:] == ',)': # correct for singleton tuple
Greg Ward1c16ac32000-08-02 01:37:30 +0000239 msg = msg[0:-2] + ')'
240
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000241 log.info(msg)
Greg Ward1c16ac32000-08-02 01:37:30 +0000242 if not dry_run:
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000243 func(*args)
Greg Ward1c16ac32000-08-02 01:37:30 +0000244
Greg Ward817dc092000-09-25 01:25:06 +0000245
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000246def strtobool(val):
Greg Ward817dc092000-09-25 01:25:06 +0000247 """Convert a string representation of truth to true (1) or false (0).
Tim Peters182b5ac2004-07-18 06:16:08 +0000248
Greg Ward817dc092000-09-25 01:25:06 +0000249 True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
250 are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
251 'val' is anything else.
252 """
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000253 val = val.lower()
Greg Ward817dc092000-09-25 01:25:06 +0000254 if val in ('y', 'yes', 't', 'true', 'on', '1'):
255 return 1
256 elif val in ('n', 'no', 'f', 'false', 'off', '0'):
257 return 0
258 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000259 raise ValueError, "invalid truth value %r" % (val,)
Greg Ward1297b5c2000-09-30 20:37:56 +0000260
261
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000262def byte_compile(py_files, optimize=0, force=0, prefix=None, base_dir=None,
263 verbose=1, dry_run=0, direct=None):
Greg Wardf217e212000-10-01 23:49:30 +0000264 """Byte-compile a collection of Python source files to either .pyc
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000265 or .pyo files in the same directory.
266
267 'py_files' is a list of files to compile; any files that don't end in
268 ".py" are silently skipped. 'optimize' must be one of the following:
Greg Ward1297b5c2000-09-30 20:37:56 +0000269 0 - don't optimize (generate .pyc)
270 1 - normal optimization (like "python -O")
271 2 - extra optimization (like "python -OO")
272 If 'force' is true, all files are recompiled regardless of
273 timestamps.
274
275 The source filename encoded in each bytecode file defaults to the
276 filenames listed in 'py_files'; you can modify these with 'prefix' and
277 'basedir'. 'prefix' is a string that will be stripped off of each
278 source filename, and 'base_dir' is a directory name that will be
279 prepended (after 'prefix' is stripped). You can supply either or both
280 (or neither) of 'prefix' and 'base_dir', as you wish.
281
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000282 If 'dry_run' is true, doesn't actually do anything that would
283 affect the filesystem.
Greg Ward1297b5c2000-09-30 20:37:56 +0000284
285 Byte-compilation is either done directly in this interpreter process
286 with the standard py_compile module, or indirectly by writing a
287 temporary script and executing it. Normally, you should let
288 'byte_compile()' figure out to use direct compilation or not (see
289 the source for details). The 'direct' flag is used by the script
290 generated in indirect mode; unless you know what you're doing, leave
291 it set to None.
292 """
Tarek Ziadéb9c1cfc2009-10-24 15:10:37 +0000293 # nothing is done if sys.dont_write_bytecode is True
294 if sys.dont_write_bytecode:
Tarek Ziadé1733c932009-10-24 15:51:30 +0000295 raise DistutilsByteCompileError('byte-compiling is disabled.')
Tarek Ziadéb9c1cfc2009-10-24 15:10:37 +0000296
Greg Ward1297b5c2000-09-30 20:37:56 +0000297 # First, if the caller didn't force us into direct or indirect mode,
298 # figure out which mode we should be in. We take a conservative
299 # approach: choose direct mode *only* if the current interpreter is
300 # in debug mode and optimize is 0. If we're not in debug mode (-O
301 # or -OO), we don't know which level of optimization this
302 # interpreter is running with, so we can't do direct
303 # byte-compilation and be certain that it's the right thing. Thus,
304 # always compile indirectly if the current interpreter is in either
305 # optimize mode, or if either optimization level was requested by
306 # the caller.
307 if direct is None:
308 direct = (__debug__ and optimize == 0)
309
310 # "Indirect" byte-compilation: write a temporary script and then
311 # run it with the appropriate flags.
312 if not direct:
Marc-André Lemburg03750792002-12-03 08:45:11 +0000313 try:
314 from tempfile import mkstemp
315 (script_fd, script_name) = mkstemp(".py")
316 except ImportError:
317 from tempfile import mktemp
318 (script_fd, script_name) = None, mktemp(".py")
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000319 log.info("writing byte-compilation script '%s'", script_name)
Greg Ward1297b5c2000-09-30 20:37:56 +0000320 if not dry_run:
Marc-André Lemburg03750792002-12-03 08:45:11 +0000321 if script_fd is not None:
322 script = os.fdopen(script_fd, "w")
323 else:
324 script = open(script_name, "w")
Greg Ward1297b5c2000-09-30 20:37:56 +0000325
326 script.write("""\
327from distutils.util import byte_compile
328files = [
329""")
Greg Ward9216cfe2000-10-03 03:31:05 +0000330
331 # XXX would be nice to write absolute filenames, just for
332 # safety's sake (script should be more robust in the face of
333 # chdir'ing before running it). But this requires abspath'ing
334 # 'prefix' as well, and that breaks the hack in build_lib's
335 # 'byte_compile()' method that carefully tacks on a trailing
336 # slash (os.sep really) to make sure the prefix here is "just
337 # right". This whole prefix business is rather delicate -- the
338 # problem is that it's really a directory, but I'm treating it
339 # as a dumb string, so trailing slashes and so forth matter.
340
341 #py_files = map(os.path.abspath, py_files)
342 #if prefix:
343 # prefix = os.path.abspath(prefix)
344
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000345 script.write(",\n".join(map(repr, py_files)) + "]\n")
Greg Ward1297b5c2000-09-30 20:37:56 +0000346 script.write("""
Walter Dörwald70a6b492004-02-12 17:35:32 +0000347byte_compile(files, optimize=%r, force=%r,
348 prefix=%r, base_dir=%r,
349 verbose=%r, dry_run=0,
Greg Ward1297b5c2000-09-30 20:37:56 +0000350 direct=1)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000351""" % (optimize, force, prefix, base_dir, verbose))
Greg Ward1297b5c2000-09-30 20:37:56 +0000352
353 script.close()
354
355 cmd = [sys.executable, script_name]
356 if optimize == 1:
357 cmd.insert(1, "-O")
358 elif optimize == 2:
359 cmd.insert(1, "-OO")
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000360 spawn(cmd, dry_run=dry_run)
Greg Ward9216cfe2000-10-03 03:31:05 +0000361 execute(os.remove, (script_name,), "removing %s" % script_name,
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000362 dry_run=dry_run)
Fred Drakeb94b8492001-12-06 20:51:35 +0000363
Greg Ward1297b5c2000-09-30 20:37:56 +0000364 # "Direct" byte-compilation: use the py_compile module to compile
365 # right here, right now. Note that the script generated in indirect
366 # mode simply calls 'byte_compile()' in direct mode, a weird sort of
367 # cross-process recursion. Hey, it works!
368 else:
369 from py_compile import compile
370
371 for file in py_files:
372 if file[-3:] != ".py":
Greg Wardf217e212000-10-01 23:49:30 +0000373 # This lets us be lazy and not filter filenames in
374 # the "install_lib" command.
375 continue
Greg Ward1297b5c2000-09-30 20:37:56 +0000376
377 # Terminology from the py_compile module:
378 # cfile - byte-compiled file
379 # dfile - purported source filename (same as 'file' by default)
380 cfile = file + (__debug__ and "c" or "o")
381 dfile = file
382 if prefix:
383 if file[:len(prefix)] != prefix:
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000384 raise ValueError("invalid prefix: filename %r doesn't "
385 "start with %r" % (file, prefix))
Greg Ward1297b5c2000-09-30 20:37:56 +0000386 dfile = dfile[len(prefix):]
387 if base_dir:
388 dfile = os.path.join(base_dir, dfile)
389
390 cfile_base = os.path.basename(cfile)
391 if direct:
392 if force or newer(file, cfile):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000393 log.info("byte-compiling %s to %s", file, cfile_base)
Greg Ward1297b5c2000-09-30 20:37:56 +0000394 if not dry_run:
395 compile(file, cfile, dfile)
396 else:
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000397 log.debug("skipping byte-compilation of %s to %s",
398 file, cfile_base)
Greg Ward1297b5c2000-09-30 20:37:56 +0000399
Andrew M. Kuchlingdf66df02001-03-22 03:03:41 +0000400
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000401def rfc822_escape(header):
Andrew M. Kuchlingdf66df02001-03-22 03:03:41 +0000402 """Return a version of the string escaped for inclusion in an
Andrew M. Kuchling88b08842001-03-23 17:30:26 +0000403 RFC-822 header, by ensuring there are 8 spaces space after each newline.
Andrew M. Kuchlingdf66df02001-03-22 03:03:41 +0000404 """
Tarek Ziadé4f383172009-12-06 09:22:40 +0000405 lines = header.split('\n')
406 sep = '\n' + 8 * ' '
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000407 return sep.join(lines)
Tarek Ziadéa99dedf2009-07-16 15:35:45 +0000408
409_RE_VERSION = re.compile('(\d+\.\d+(\.\d+)*)')
410_MAC_OS_X_LD_VERSION = re.compile('^@\(#\)PROGRAM:ld PROJECT:ld64-((\d+)(\.\d+)*)')
411
412def _find_ld_version():
413 """Finds the ld version. The version scheme differs under Mac OSX."""
414 if sys.platform == 'darwin':
415 return _find_exe_version('ld -v', _MAC_OS_X_LD_VERSION)
416 else:
417 return _find_exe_version('ld -v')
418
419def _find_exe_version(cmd, pattern=_RE_VERSION):
420 """Find the version of an executable by running `cmd` in the shell.
421
422 `pattern` is a compiled regular expression. If not provided, default
423 to _RE_VERSION. If the command is not found, or the output does not
424 match the mattern, returns None.
425 """
426 from subprocess import Popen, PIPE
427 executable = cmd.split()[0]
428 if find_executable(executable) is None:
429 return None
430 pipe = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
431 try:
432 stdout, stderr = pipe.stdout.read(), pipe.stderr.read()
433 finally:
434 pipe.stdout.close()
435 pipe.stderr.close()
436 # some commands like ld under MacOS X, will give the
437 # output in the stderr, rather than stdout.
438 if stdout != '':
439 out_string = stdout
440 else:
441 out_string = stderr
442
443 result = pattern.search(out_string)
444 if result is None:
445 return None
446 return LooseVersion(result.group(1))
447
448def get_compiler_versions():
449 """Returns a tuple providing the versions of gcc, ld and dllwrap
450
451 For each command, if a command is not found, None is returned.
452 Otherwise a LooseVersion instance is returned.
453 """
454 gcc = _find_exe_version('gcc -dumpversion')
455 ld = _find_ld_version()
456 dllwrap = _find_exe_version('dllwrap --version')
457 return gcc, ld, dllwrap