blob: fbd3a67243824b04f677439bf24988c7b2481969 [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')
Tarek Ziadé92e68af2010-01-26 22:46:15 +000019_PLATFORM = None
Greg Ward50919292000-03-07 03:27:08 +000020
Tarek Ziadé92e68af2010-01-26 22:46:15 +000021def get_platform():
22 """Return a string that identifies the current platform.
23
24 By default, will return the value returned by sysconfig.get_platform(),
25 but it can be changed by calling set_platform().
26 """
27 global _PLATFORM
28 if _PLATFORM is None:
29 _PLATFORM = _sysconfig.get_platform()
30 return _PLATFORM
31
32def set_platform(identifier):
33 """Sets the platform string identifier returned by get_platform().
34
35 Note that this change doesn't impact the value returned by
36 sysconfig.get_platform() and is local to Distutils
37 """
38 global _PLATFORM
39 _PLATFORM = identifier
Tarek Ziadé0276c7a2010-01-26 21:21:54 +000040
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000041def convert_path(pathname):
42 """Return 'pathname' as a name that will work on the native filesystem.
Greg Ward50919292000-03-07 03:27:08 +000043
Greg Wardb8b263b2000-09-30 18:40:42 +000044 i.e. split it on '/' and put it back together again using the current
45 directory separator. Needed because filenames in the setup script are
46 always supplied in Unix style, and have to be converted to the local
47 convention before we can actually use them in the filesystem. Raises
Greg Ward47527692000-09-30 18:49:14 +000048 ValueError on non-Unix-ish systems if 'pathname' either starts or
49 ends with a slash.
Greg Wardb8b263b2000-09-30 18:40:42 +000050 """
Greg Ward7ec05352000-09-22 01:05:43 +000051 if os.sep == '/':
52 return pathname
Neal Norwitzb0df6a12002-08-13 17:42:57 +000053 if not pathname:
54 return pathname
55 if pathname[0] == '/':
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000056 raise ValueError("path '%s' cannot be absolute" % pathname)
Neal Norwitzb0df6a12002-08-13 17:42:57 +000057 if pathname[-1] == '/':
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000058 raise ValueError("path '%s' cannot end with '/'" % pathname)
Greg Ward7ec05352000-09-22 01:05:43 +000059
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000060 paths = pathname.split('/')
Jack Jansenb4cd5c12001-01-28 12:23:32 +000061 while '.' in paths:
62 paths.remove('.')
63 if not paths:
64 return os.curdir
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000065 return os.path.join(*paths)
Greg Ward1b4ede52000-03-22 00:22:44 +000066
67
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000068def change_root(new_root, pathname):
69 """Return 'pathname' with 'new_root' prepended.
70
71 If 'pathname' is relative, this is equivalent to
72 "os.path.join(new_root,pathname)".
Greg Ward67f75d42000-04-27 01:53:46 +000073 Otherwise, it requires making 'pathname' relative and then joining the
Greg Ward4b46ef92000-05-31 02:14:32 +000074 two, which is tricky on DOS/Windows and Mac OS.
75 """
76 if os.name == 'posix':
Greg Wardbe86bde2000-09-26 01:56:15 +000077 if not os.path.isabs(pathname):
78 return os.path.join(new_root, pathname)
Greg Ward4b46ef92000-05-31 02:14:32 +000079 else:
Greg Wardbe86bde2000-09-26 01:56:15 +000080 return os.path.join(new_root, pathname[1:])
Greg Ward67f75d42000-04-27 01:53:46 +000081
82 elif os.name == 'nt':
Greg Wardbe86bde2000-09-26 01:56:15 +000083 (drive, path) = os.path.splitdrive(pathname)
Greg Ward4b46ef92000-05-31 02:14:32 +000084 if path[0] == '\\':
85 path = path[1:]
Greg Wardbe86bde2000-09-26 01:56:15 +000086 return os.path.join(new_root, path)
Greg Ward67f75d42000-04-27 01:53:46 +000087
Marc-André Lemburg2544f512002-01-31 18:56:00 +000088 elif os.name == 'os2':
89 (drive, path) = os.path.splitdrive(pathname)
90 if path[0] == os.sep:
91 path = path[1:]
92 return os.path.join(new_root, path)
93
Greg Ward67f75d42000-04-27 01:53:46 +000094 elif os.name == 'mac':
Greg Wardf5855742000-09-21 01:23:35 +000095 if not os.path.isabs(pathname):
96 return os.path.join(new_root, pathname)
97 else:
98 # Chop off volume name from start of path
Tarek Ziadé3757fbb2009-07-02 14:20:47 +000099 elements = pathname.split(":", 1)
Greg Wardf5855742000-09-21 01:23:35 +0000100 pathname = ":" + elements[1]
101 return os.path.join(new_root, pathname)
Greg Ward67f75d42000-04-27 01:53:46 +0000102
103 else:
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000104 raise DistutilsPlatformError("nothing known about "
105 "platform '%s'" % os.name)
Greg Ward67f75d42000-04-27 01:53:46 +0000106
Gregory P. Smithe7e35ac2000-05-12 00:40:00 +0000107_environ_checked = 0
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000108
109def check_environ():
110 """Ensure that 'os.environ' has all the environment variables needed.
111
112 We guarantee that users can use in config files, command-line options,
Greg Wardb8b263b2000-09-30 18:40:42 +0000113 etc. Currently this includes:
114 HOME - user's home directory (Unix only)
115 PLAT - description of the current platform, including hardware
116 and OS (see 'get_platform()')
Greg Ward1b4ede52000-03-22 00:22:44 +0000117 """
Gregory P. Smithe7e35ac2000-05-12 00:40:00 +0000118 global _environ_checked
119 if _environ_checked:
120 return
121
Guido van Rossum8bc09652008-02-21 18:18:37 +0000122 if os.name == 'posix' and 'HOME' not in os.environ:
Greg Ward1b4ede52000-03-22 00:22:44 +0000123 import pwd
Greg Wardbe86bde2000-09-26 01:56:15 +0000124 os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
Greg Ward1b4ede52000-03-22 00:22:44 +0000125
Guido van Rossum8bc09652008-02-21 18:18:37 +0000126 if 'PLAT' not in os.environ:
Tarek Ziadé5633a802010-01-23 09:23:15 +0000127 os.environ['PLAT'] = _sysconfig.get_platform()
Greg Ward1b4ede52000-03-22 00:22:44 +0000128
Gregory P. Smithe7e35ac2000-05-12 00:40:00 +0000129 _environ_checked = 1
130
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000131def subst_vars(s, local_vars):
132 """Perform shell/Perl-style variable substitution on 'string'.
Greg Ward1b4ede52000-03-22 00:22:44 +0000133
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000134 Every occurrence of '$' followed by a name is considered a variable, and
Greg Ward47527692000-09-30 18:49:14 +0000135 variable is substituted by the value found in the 'local_vars'
136 dictionary, or in 'os.environ' if it's not in 'local_vars'.
137 'os.environ' is first checked/augmented to guarantee that it contains
138 certain values: see 'check_environ()'. Raise ValueError for any
139 variables not found in either 'local_vars' or 'os.environ'.
Greg Wardb8b263b2000-09-30 18:40:42 +0000140 """
Greg Wardbe86bde2000-09-26 01:56:15 +0000141 check_environ()
Greg Ward1b4ede52000-03-22 00:22:44 +0000142 def _subst (match, local_vars=local_vars):
143 var_name = match.group(1)
Guido van Rossum8bc09652008-02-21 18:18:37 +0000144 if var_name in local_vars:
Greg Wardbe86bde2000-09-26 01:56:15 +0000145 return str(local_vars[var_name])
Greg Ward1b4ede52000-03-22 00:22:44 +0000146 else:
147 return os.environ[var_name]
148
Greg Ward47527692000-09-30 18:49:14 +0000149 try:
Jeremy Hylton5e2d0762001-01-25 20:10:32 +0000150 return re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s)
Greg Ward47527692000-09-30 18:49:14 +0000151 except KeyError, var:
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000152 raise ValueError("invalid variable '$%s'" % var)
Greg Ward1b4ede52000-03-22 00:22:44 +0000153
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000154def grok_environment_error(exc, prefix="error: "):
155 """Generate a useful error message from an EnvironmentError.
Greg Ward7c1a6d42000-03-29 02:48:40 +0000156
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000157 This will generate an IOError or an OSError exception object.
158 Handles Python 1.5.1 and 1.5.2 styles, and
Greg Warde9055132000-06-17 02:16:46 +0000159 does what it can to deal with exception objects that don't have a
160 filename (which happens when the error is due to a two-file operation,
161 such as 'rename()' or 'link()'. Returns the error message as a string
162 prefixed with 'prefix'.
163 """
164 # check for Python 1.5.2-style {IO,OS}Error exception objects
Greg Wardbe86bde2000-09-26 01:56:15 +0000165 if hasattr(exc, 'filename') and hasattr(exc, 'strerror'):
Greg Warde9055132000-06-17 02:16:46 +0000166 if exc.filename:
167 error = prefix + "%s: %s" % (exc.filename, exc.strerror)
168 else:
169 # two-argument functions in posix module don't
170 # include the filename in the exception object!
171 error = prefix + "%s" % exc.strerror
172 else:
173 error = prefix + str(exc[-1])
174
175 return error
Greg Ward6a2a3db2000-06-24 20:40:02 +0000176
Greg Ward6a2a3db2000-06-24 20:40:02 +0000177# Needed by 'split_quoted()'
Martin v. Löwis1c0f1f92004-03-25 14:58:19 +0000178_wordchars_re = _squote_re = _dquote_re = None
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000179
Martin v. Löwis1c0f1f92004-03-25 14:58:19 +0000180def _init_regex():
181 global _wordchars_re, _squote_re, _dquote_re
182 _wordchars_re = re.compile(r'[^\\\'\"%s ]*' % string.whitespace)
183 _squote_re = re.compile(r"'(?:[^'\\]|\\.)*'")
184 _dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"')
Greg Ward6a2a3db2000-06-24 20:40:02 +0000185
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000186def split_quoted(s):
Greg Ward6a2a3db2000-06-24 20:40:02 +0000187 """Split a string up according to Unix shell-like rules for quotes and
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000188 backslashes.
189
190 In short: words are delimited by spaces, as long as those
Greg Ward6a2a3db2000-06-24 20:40:02 +0000191 spaces are not escaped by a backslash, or inside a quoted string.
192 Single and double quotes are equivalent, and the quote characters can
193 be backslash-escaped. The backslash is stripped from any two-character
194 escape sequence, leaving only the escaped character. The quote
195 characters are stripped from any quoted string. Returns a list of
196 words.
197 """
Greg Ward6a2a3db2000-06-24 20:40:02 +0000198 # This is a nice algorithm for splitting up a single string, since it
199 # doesn't require character-by-character examination. It was a little
200 # bit of a brain-bender to get it working right, though...
Martin v. Löwis1c0f1f92004-03-25 14:58:19 +0000201 if _wordchars_re is None: _init_regex()
Greg Ward6a2a3db2000-06-24 20:40:02 +0000202
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000203 s = s.strip()
Greg Ward6a2a3db2000-06-24 20:40:02 +0000204 words = []
205 pos = 0
206
207 while s:
208 m = _wordchars_re.match(s, pos)
209 end = m.end()
210 if end == len(s):
211 words.append(s[:end])
212 break
213
Greg Ward2b042de2000-08-08 14:38:13 +0000214 if s[end] in string.whitespace: # unescaped, unquoted whitespace: now
Greg Ward6a2a3db2000-06-24 20:40:02 +0000215 words.append(s[:end]) # we definitely have a word delimiter
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000216 s = s[end:].lstrip()
Greg Ward6a2a3db2000-06-24 20:40:02 +0000217 pos = 0
218
219 elif s[end] == '\\': # preserve whatever is being escaped;
220 # will become part of the current word
221 s = s[:end] + s[end+1:]
222 pos = end+1
223
224 else:
225 if s[end] == "'": # slurp singly-quoted string
226 m = _squote_re.match(s, end)
227 elif s[end] == '"': # slurp doubly-quoted string
228 m = _dquote_re.match(s, end)
229 else:
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000230 raise RuntimeError("this can't happen "
231 "(bad char '%c')" % s[end])
Greg Ward6a2a3db2000-06-24 20:40:02 +0000232
233 if m is None:
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000234 raise ValueError("bad string (mismatched %s quotes?)" % s[end])
Greg Ward6a2a3db2000-06-24 20:40:02 +0000235
236 (beg, end) = m.span()
237 s = s[:beg] + s[beg+1:end-1] + s[end:]
238 pos = m.end() - 2
239
240 if pos >= len(s):
241 words.append(s)
242 break
243
244 return words
245
Greg Ward1c16ac32000-08-02 01:37:30 +0000246
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000247def execute(func, args, msg=None, verbose=0, dry_run=0):
248 """Perform some action that affects the outside world.
Greg Ward1c16ac32000-08-02 01:37:30 +0000249
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000250 eg. by writing to the filesystem). Such actions are special because
251 they are disabled by the 'dry_run' flag. This method takes care of all
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000252 that bureaucracy for you; all you have to do is supply the
253 function to call and an argument tuple for it (to embody the
254 "external action" being performed), and an optional message to
255 print.
Greg Ward1c16ac32000-08-02 01:37:30 +0000256 """
Greg Ward1c16ac32000-08-02 01:37:30 +0000257 if msg is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000258 msg = "%s%r" % (func.__name__, args)
Fred Drakeb94b8492001-12-06 20:51:35 +0000259 if msg[-2:] == ',)': # correct for singleton tuple
Greg Ward1c16ac32000-08-02 01:37:30 +0000260 msg = msg[0:-2] + ')'
261
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000262 log.info(msg)
Greg Ward1c16ac32000-08-02 01:37:30 +0000263 if not dry_run:
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000264 func(*args)
Greg Ward1c16ac32000-08-02 01:37:30 +0000265
Greg Ward817dc092000-09-25 01:25:06 +0000266
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000267def strtobool(val):
Greg Ward817dc092000-09-25 01:25:06 +0000268 """Convert a string representation of truth to true (1) or false (0).
Tim Peters182b5ac2004-07-18 06:16:08 +0000269
Greg Ward817dc092000-09-25 01:25:06 +0000270 True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
271 are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
272 'val' is anything else.
273 """
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000274 val = val.lower()
Greg Ward817dc092000-09-25 01:25:06 +0000275 if val in ('y', 'yes', 't', 'true', 'on', '1'):
276 return 1
277 elif val in ('n', 'no', 'f', 'false', 'off', '0'):
278 return 0
279 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000280 raise ValueError, "invalid truth value %r" % (val,)
Greg Ward1297b5c2000-09-30 20:37:56 +0000281
282
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000283def byte_compile(py_files, optimize=0, force=0, prefix=None, base_dir=None,
284 verbose=1, dry_run=0, direct=None):
Greg Wardf217e212000-10-01 23:49:30 +0000285 """Byte-compile a collection of Python source files to either .pyc
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000286 or .pyo files in the same directory.
287
288 'py_files' is a list of files to compile; any files that don't end in
289 ".py" are silently skipped. 'optimize' must be one of the following:
Greg Ward1297b5c2000-09-30 20:37:56 +0000290 0 - don't optimize (generate .pyc)
291 1 - normal optimization (like "python -O")
292 2 - extra optimization (like "python -OO")
293 If 'force' is true, all files are recompiled regardless of
294 timestamps.
295
296 The source filename encoded in each bytecode file defaults to the
297 filenames listed in 'py_files'; you can modify these with 'prefix' and
298 'basedir'. 'prefix' is a string that will be stripped off of each
299 source filename, and 'base_dir' is a directory name that will be
300 prepended (after 'prefix' is stripped). You can supply either or both
301 (or neither) of 'prefix' and 'base_dir', as you wish.
302
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000303 If 'dry_run' is true, doesn't actually do anything that would
304 affect the filesystem.
Greg Ward1297b5c2000-09-30 20:37:56 +0000305
306 Byte-compilation is either done directly in this interpreter process
307 with the standard py_compile module, or indirectly by writing a
308 temporary script and executing it. Normally, you should let
309 'byte_compile()' figure out to use direct compilation or not (see
310 the source for details). The 'direct' flag is used by the script
311 generated in indirect mode; unless you know what you're doing, leave
312 it set to None.
313 """
Tarek Ziadéb9c1cfc2009-10-24 15:10:37 +0000314 # nothing is done if sys.dont_write_bytecode is True
315 if sys.dont_write_bytecode:
Tarek Ziadé1733c932009-10-24 15:51:30 +0000316 raise DistutilsByteCompileError('byte-compiling is disabled.')
Tarek Ziadéb9c1cfc2009-10-24 15:10:37 +0000317
Greg Ward1297b5c2000-09-30 20:37:56 +0000318 # First, if the caller didn't force us into direct or indirect mode,
319 # figure out which mode we should be in. We take a conservative
320 # approach: choose direct mode *only* if the current interpreter is
321 # in debug mode and optimize is 0. If we're not in debug mode (-O
322 # or -OO), we don't know which level of optimization this
323 # interpreter is running with, so we can't do direct
324 # byte-compilation and be certain that it's the right thing. Thus,
325 # always compile indirectly if the current interpreter is in either
326 # optimize mode, or if either optimization level was requested by
327 # the caller.
328 if direct is None:
329 direct = (__debug__ and optimize == 0)
330
331 # "Indirect" byte-compilation: write a temporary script and then
332 # run it with the appropriate flags.
333 if not direct:
Marc-André Lemburg03750792002-12-03 08:45:11 +0000334 try:
335 from tempfile import mkstemp
336 (script_fd, script_name) = mkstemp(".py")
337 except ImportError:
338 from tempfile import mktemp
339 (script_fd, script_name) = None, mktemp(".py")
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000340 log.info("writing byte-compilation script '%s'", script_name)
Greg Ward1297b5c2000-09-30 20:37:56 +0000341 if not dry_run:
Marc-André Lemburg03750792002-12-03 08:45:11 +0000342 if script_fd is not None:
343 script = os.fdopen(script_fd, "w")
344 else:
345 script = open(script_name, "w")
Greg Ward1297b5c2000-09-30 20:37:56 +0000346
347 script.write("""\
348from distutils.util import byte_compile
349files = [
350""")
Greg Ward9216cfe2000-10-03 03:31:05 +0000351
352 # XXX would be nice to write absolute filenames, just for
353 # safety's sake (script should be more robust in the face of
354 # chdir'ing before running it). But this requires abspath'ing
355 # 'prefix' as well, and that breaks the hack in build_lib's
356 # 'byte_compile()' method that carefully tacks on a trailing
357 # slash (os.sep really) to make sure the prefix here is "just
358 # right". This whole prefix business is rather delicate -- the
359 # problem is that it's really a directory, but I'm treating it
360 # as a dumb string, so trailing slashes and so forth matter.
361
362 #py_files = map(os.path.abspath, py_files)
363 #if prefix:
364 # prefix = os.path.abspath(prefix)
365
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000366 script.write(",\n".join(map(repr, py_files)) + "]\n")
Greg Ward1297b5c2000-09-30 20:37:56 +0000367 script.write("""
Walter Dörwald70a6b492004-02-12 17:35:32 +0000368byte_compile(files, optimize=%r, force=%r,
369 prefix=%r, base_dir=%r,
370 verbose=%r, dry_run=0,
Greg Ward1297b5c2000-09-30 20:37:56 +0000371 direct=1)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000372""" % (optimize, force, prefix, base_dir, verbose))
Greg Ward1297b5c2000-09-30 20:37:56 +0000373
374 script.close()
375
376 cmd = [sys.executable, script_name]
377 if optimize == 1:
378 cmd.insert(1, "-O")
379 elif optimize == 2:
380 cmd.insert(1, "-OO")
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000381 spawn(cmd, dry_run=dry_run)
Greg Ward9216cfe2000-10-03 03:31:05 +0000382 execute(os.remove, (script_name,), "removing %s" % script_name,
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000383 dry_run=dry_run)
Fred Drakeb94b8492001-12-06 20:51:35 +0000384
Greg Ward1297b5c2000-09-30 20:37:56 +0000385 # "Direct" byte-compilation: use the py_compile module to compile
386 # right here, right now. Note that the script generated in indirect
387 # mode simply calls 'byte_compile()' in direct mode, a weird sort of
388 # cross-process recursion. Hey, it works!
389 else:
390 from py_compile import compile
391
392 for file in py_files:
393 if file[-3:] != ".py":
Greg Wardf217e212000-10-01 23:49:30 +0000394 # This lets us be lazy and not filter filenames in
395 # the "install_lib" command.
396 continue
Greg Ward1297b5c2000-09-30 20:37:56 +0000397
398 # Terminology from the py_compile module:
399 # cfile - byte-compiled file
400 # dfile - purported source filename (same as 'file' by default)
401 cfile = file + (__debug__ and "c" or "o")
402 dfile = file
403 if prefix:
404 if file[:len(prefix)] != prefix:
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000405 raise ValueError("invalid prefix: filename %r doesn't "
406 "start with %r" % (file, prefix))
Greg Ward1297b5c2000-09-30 20:37:56 +0000407 dfile = dfile[len(prefix):]
408 if base_dir:
409 dfile = os.path.join(base_dir, dfile)
410
411 cfile_base = os.path.basename(cfile)
412 if direct:
413 if force or newer(file, cfile):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000414 log.info("byte-compiling %s to %s", file, cfile_base)
Greg Ward1297b5c2000-09-30 20:37:56 +0000415 if not dry_run:
416 compile(file, cfile, dfile)
417 else:
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000418 log.debug("skipping byte-compilation of %s to %s",
419 file, cfile_base)
Greg Ward1297b5c2000-09-30 20:37:56 +0000420
Andrew M. Kuchlingdf66df02001-03-22 03:03:41 +0000421
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000422def rfc822_escape(header):
Andrew M. Kuchlingdf66df02001-03-22 03:03:41 +0000423 """Return a version of the string escaped for inclusion in an
Andrew M. Kuchling88b08842001-03-23 17:30:26 +0000424 RFC-822 header, by ensuring there are 8 spaces space after each newline.
Andrew M. Kuchlingdf66df02001-03-22 03:03:41 +0000425 """
Tarek Ziadé4f383172009-12-06 09:22:40 +0000426 lines = header.split('\n')
427 sep = '\n' + 8 * ' '
Tarek Ziadé3757fbb2009-07-02 14:20:47 +0000428 return sep.join(lines)
Tarek Ziadéa99dedf2009-07-16 15:35:45 +0000429
430_RE_VERSION = re.compile('(\d+\.\d+(\.\d+)*)')
431_MAC_OS_X_LD_VERSION = re.compile('^@\(#\)PROGRAM:ld PROJECT:ld64-((\d+)(\.\d+)*)')
432
433def _find_ld_version():
434 """Finds the ld version. The version scheme differs under Mac OSX."""
435 if sys.platform == 'darwin':
436 return _find_exe_version('ld -v', _MAC_OS_X_LD_VERSION)
437 else:
438 return _find_exe_version('ld -v')
439
440def _find_exe_version(cmd, pattern=_RE_VERSION):
441 """Find the version of an executable by running `cmd` in the shell.
442
443 `pattern` is a compiled regular expression. If not provided, default
444 to _RE_VERSION. If the command is not found, or the output does not
445 match the mattern, returns None.
446 """
447 from subprocess import Popen, PIPE
448 executable = cmd.split()[0]
449 if find_executable(executable) is None:
450 return None
451 pipe = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
452 try:
453 stdout, stderr = pipe.stdout.read(), pipe.stderr.read()
454 finally:
455 pipe.stdout.close()
456 pipe.stderr.close()
457 # some commands like ld under MacOS X, will give the
458 # output in the stderr, rather than stdout.
459 if stdout != '':
460 out_string = stdout
461 else:
462 out_string = stderr
463
464 result = pattern.search(out_string)
465 if result is None:
466 return None
467 return LooseVersion(result.group(1))
468
469def get_compiler_versions():
470 """Returns a tuple providing the versions of gcc, ld and dllwrap
471
472 For each command, if a command is not found, None is returned.
473 Otherwise a LooseVersion instance is returned.
474 """
475 gcc = _find_exe_version('gcc -dumpversion')
476 ld = _find_ld_version()
477 dllwrap = _find_exe_version('dllwrap --version')
478 return gcc, ld, dllwrap