blob: 0515fefd2fdbfa8a83cef97c178bee34a3b46698 [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éf8926b22009-07-16 16:18:19 +000010
Greg Ward1297b5c2000-09-30 20:37:56 +000011from distutils.errors import DistutilsPlatformError
12from distutils.dep_util import newer
Tarek Ziadéf8926b22009-07-16 16:18:19 +000013from distutils.spawn import spawn, find_executable
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000014from distutils import log
Tarek Ziadéf8926b22009-07-16 16:18:19 +000015from distutils.version import LooseVersion
Tarek Ziadé04fe7c02009-10-25 23:08:47 +000016from distutils.errors import DistutilsByteCompileError
Greg Wardaa458bc2000-04-22 15:14:58 +000017
Tarek Ziadéedacea32010-01-29 11:41:03 +000018_sysconfig = __import__('sysconfig')
Greg Ward50919292000-03-07 03:27:08 +000019
Tarek Ziadé905a2572009-07-02 14:25:23 +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] == '/':
Collin Winter5b7e9d72007-08-30 03:52:21 +000035 raise ValueError("path '%s' cannot be absolute" % pathname)
Neal Norwitzb0df6a12002-08-13 17:42:57 +000036 if pathname[-1] == '/':
Collin Winter5b7e9d72007-08-30 03:52:21 +000037 raise ValueError("path '%s' cannot end with '/'" % pathname)
Greg Ward7ec05352000-09-22 01:05:43 +000038
Neal Norwitz9d72bb42007-04-17 08:48:32 +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
Neal Norwitzd9108552006-03-17 08:00:19 +000044 return os.path.join(*paths)
Greg Ward50919292000-03-07 03:27:08 +000045
Greg Ward1b4ede52000-03-22 00:22:44 +000046
Tarek Ziadé905a2572009-07-02 14:25:23 +000047def change_root(new_root, pathname):
48 """Return 'pathname' with 'new_root' prepended.
Greg Ward1b4ede52000-03-22 00:22:44 +000049
Tarek Ziadé905a2572009-07-02 14:25:23 +000050 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
Neal Norwitz9d72bb42007-04-17 08:48:32 +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é905a2572009-07-02 14:25:23 +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é905a2572009-07-02 14:25:23 +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 Rossume2b70bc2006-08-18 22:13:04 +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 Rossume2b70bc2006-08-18 22:13:04 +0000105 if 'PLAT' not in os.environ:
Tarek Ziadéedacea32010-01-29 11:41:03 +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é905a2572009-07-02 14:25:23 +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é905a2572009-07-02 14:25:23 +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 Rossume2b70bc2006-08-18 22:13:04 +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)
Guido van Rossumb940e112007-01-10 16:19:56 +0000130 except KeyError as var:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000131 raise ValueError("invalid variable '$%s'" % var)
Greg Ward1b4ede52000-03-22 00:22:44 +0000132
Tarek Ziadé905a2572009-07-02 14:25:23 +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é905a2572009-07-02 14:25:23 +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:
Georg Brandl5dfe0de2008-01-06 21:41:49 +0000152 error = prefix + str(exc.args[-1])
Greg Warde9055132000-06-17 02:16:46 +0000153
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é905a2572009-07-02 14:25:23 +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é905a2572009-07-02 14:25:23 +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é905a2572009-07-02 14:25:23 +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
Neal Norwitz9d72bb42007-04-17 08:48:32 +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
Neal Norwitz9d72bb42007-04-17 08:48:32 +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:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000209 raise RuntimeError("this can't happen (bad char '%c')" % s[end])
Greg Ward6a2a3db2000-06-24 20:40:02 +0000210
211 if m is None:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000212 raise ValueError("bad string (mismatched %s quotes?)" % s[end])
Greg Ward6a2a3db2000-06-24 20:40:02 +0000213
214 (beg, end) = m.span()
215 s = s[:beg] + s[beg+1:end-1] + s[end:]
216 pos = m.end() - 2
217
218 if pos >= len(s):
219 words.append(s)
220 break
221
222 return words
223
Greg Ward1c16ac32000-08-02 01:37:30 +0000224
Tarek Ziadé905a2572009-07-02 14:25:23 +0000225def execute(func, args, msg=None, verbose=0, dry_run=0):
226 """Perform some action that affects the outside world.
Greg Ward1c16ac32000-08-02 01:37:30 +0000227
Tarek Ziadé905a2572009-07-02 14:25:23 +0000228 eg. by writing to the filesystem). Such actions are special because
229 they are disabled by the 'dry_run' flag. This method takes care of all
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000230 that bureaucracy for you; all you have to do is supply the
231 function to call and an argument tuple for it (to embody the
232 "external action" being performed), and an optional message to
233 print.
Greg Ward1c16ac32000-08-02 01:37:30 +0000234 """
Greg Ward1c16ac32000-08-02 01:37:30 +0000235 if msg is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000236 msg = "%s%r" % (func.__name__, args)
Fred Drakeb94b8492001-12-06 20:51:35 +0000237 if msg[-2:] == ',)': # correct for singleton tuple
Greg Ward1c16ac32000-08-02 01:37:30 +0000238 msg = msg[0:-2] + ')'
239
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000240 log.info(msg)
Greg Ward1c16ac32000-08-02 01:37:30 +0000241 if not dry_run:
Neal Norwitzd9108552006-03-17 08:00:19 +0000242 func(*args)
Greg Ward1c16ac32000-08-02 01:37:30 +0000243
Greg Ward817dc092000-09-25 01:25:06 +0000244
Tarek Ziadé905a2572009-07-02 14:25:23 +0000245def strtobool(val):
Greg Ward817dc092000-09-25 01:25:06 +0000246 """Convert a string representation of truth to true (1) or false (0).
Tim Peters182b5ac2004-07-18 06:16:08 +0000247
Greg Ward817dc092000-09-25 01:25:06 +0000248 True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
249 are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
250 'val' is anything else.
251 """
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000252 val = val.lower()
Greg Ward817dc092000-09-25 01:25:06 +0000253 if val in ('y', 'yes', 't', 'true', 'on', '1'):
254 return 1
255 elif val in ('n', 'no', 'f', 'false', 'off', '0'):
256 return 0
257 else:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000258 raise ValueError("invalid truth value %r" % (val,))
Greg Ward1297b5c2000-09-30 20:37:56 +0000259
260
Tarek Ziadé905a2572009-07-02 14:25:23 +0000261def byte_compile(py_files, optimize=0, force=0, prefix=None, base_dir=None,
262 verbose=1, dry_run=0, direct=None):
Greg Wardf217e212000-10-01 23:49:30 +0000263 """Byte-compile a collection of Python source files to either .pyc
Tarek Ziadé905a2572009-07-02 14:25:23 +0000264 or .pyo files in the same directory.
265
266 'py_files' is a list of files to compile; any files that don't end in
267 ".py" are silently skipped. 'optimize' must be one of the following:
Greg Ward1297b5c2000-09-30 20:37:56 +0000268 0 - don't optimize (generate .pyc)
269 1 - normal optimization (like "python -O")
270 2 - extra optimization (like "python -OO")
271 If 'force' is true, all files are recompiled regardless of
272 timestamps.
273
274 The source filename encoded in each bytecode file defaults to the
275 filenames listed in 'py_files'; you can modify these with 'prefix' and
276 'basedir'. 'prefix' is a string that will be stripped off of each
277 source filename, and 'base_dir' is a directory name that will be
278 prepended (after 'prefix' is stripped). You can supply either or both
279 (or neither) of 'prefix' and 'base_dir', as you wish.
280
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000281 If 'dry_run' is true, doesn't actually do anything that would
282 affect the filesystem.
Greg Ward1297b5c2000-09-30 20:37:56 +0000283
284 Byte-compilation is either done directly in this interpreter process
285 with the standard py_compile module, or indirectly by writing a
286 temporary script and executing it. Normally, you should let
287 'byte_compile()' figure out to use direct compilation or not (see
288 the source for details). The 'direct' flag is used by the script
289 generated in indirect mode; unless you know what you're doing, leave
290 it set to None.
291 """
Tarek Ziadé04fe7c02009-10-25 23:08:47 +0000292 # nothing is done if sys.dont_write_bytecode is True
293 if sys.dont_write_bytecode:
294 raise DistutilsByteCompileError('byte-compiling is disabled.')
295
Greg Ward1297b5c2000-09-30 20:37:56 +0000296 # First, if the caller didn't force us into direct or indirect mode,
297 # figure out which mode we should be in. We take a conservative
298 # approach: choose direct mode *only* if the current interpreter is
299 # in debug mode and optimize is 0. If we're not in debug mode (-O
300 # or -OO), we don't know which level of optimization this
301 # interpreter is running with, so we can't do direct
302 # byte-compilation and be certain that it's the right thing. Thus,
303 # always compile indirectly if the current interpreter is in either
304 # optimize mode, or if either optimization level was requested by
305 # the caller.
306 if direct is None:
307 direct = (__debug__ and optimize == 0)
308
309 # "Indirect" byte-compilation: write a temporary script and then
310 # run it with the appropriate flags.
311 if not direct:
Marc-André Lemburg03750792002-12-03 08:45:11 +0000312 try:
313 from tempfile import mkstemp
314 (script_fd, script_name) = mkstemp(".py")
315 except ImportError:
316 from tempfile import mktemp
317 (script_fd, script_name) = None, mktemp(".py")
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000318 log.info("writing byte-compilation script '%s'", script_name)
Greg Ward1297b5c2000-09-30 20:37:56 +0000319 if not dry_run:
Marc-André Lemburg03750792002-12-03 08:45:11 +0000320 if script_fd is not None:
321 script = os.fdopen(script_fd, "w")
322 else:
323 script = open(script_name, "w")
Greg Ward1297b5c2000-09-30 20:37:56 +0000324
325 script.write("""\
326from distutils.util import byte_compile
327files = [
328""")
Greg Ward9216cfe2000-10-03 03:31:05 +0000329
330 # XXX would be nice to write absolute filenames, just for
331 # safety's sake (script should be more robust in the face of
332 # chdir'ing before running it). But this requires abspath'ing
333 # 'prefix' as well, and that breaks the hack in build_lib's
334 # 'byte_compile()' method that carefully tacks on a trailing
335 # slash (os.sep really) to make sure the prefix here is "just
336 # right". This whole prefix business is rather delicate -- the
337 # problem is that it's really a directory, but I'm treating it
338 # as a dumb string, so trailing slashes and so forth matter.
339
340 #py_files = map(os.path.abspath, py_files)
341 #if prefix:
342 # prefix = os.path.abspath(prefix)
343
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000344 script.write(",\n".join(map(repr, py_files)) + "]\n")
Greg Ward1297b5c2000-09-30 20:37:56 +0000345 script.write("""
Walter Dörwald70a6b492004-02-12 17:35:32 +0000346byte_compile(files, optimize=%r, force=%r,
347 prefix=%r, base_dir=%r,
348 verbose=%r, dry_run=0,
Greg Ward1297b5c2000-09-30 20:37:56 +0000349 direct=1)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000350""" % (optimize, force, prefix, base_dir, verbose))
Greg Ward1297b5c2000-09-30 20:37:56 +0000351
352 script.close()
353
354 cmd = [sys.executable, script_name]
355 if optimize == 1:
356 cmd.insert(1, "-O")
357 elif optimize == 2:
358 cmd.insert(1, "-OO")
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000359 spawn(cmd, dry_run=dry_run)
Greg Ward9216cfe2000-10-03 03:31:05 +0000360 execute(os.remove, (script_name,), "removing %s" % script_name,
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000361 dry_run=dry_run)
Fred Drakeb94b8492001-12-06 20:51:35 +0000362
Greg Ward1297b5c2000-09-30 20:37:56 +0000363 # "Direct" byte-compilation: use the py_compile module to compile
364 # right here, right now. Note that the script generated in indirect
365 # mode simply calls 'byte_compile()' in direct mode, a weird sort of
366 # cross-process recursion. Hey, it works!
367 else:
368 from py_compile import compile
369
370 for file in py_files:
371 if file[-3:] != ".py":
Greg Wardf217e212000-10-01 23:49:30 +0000372 # This lets us be lazy and not filter filenames in
373 # the "install_lib" command.
374 continue
Greg Ward1297b5c2000-09-30 20:37:56 +0000375
376 # Terminology from the py_compile module:
377 # cfile - byte-compiled file
378 # dfile - purported source filename (same as 'file' by default)
379 cfile = file + (__debug__ and "c" or "o")
380 dfile = file
381 if prefix:
382 if file[:len(prefix)] != prefix:
Tarek Ziadé905a2572009-07-02 14:25:23 +0000383 raise ValueError("invalid prefix: filename %r doesn't "
384 "start with %r" % (file, prefix))
Greg Ward1297b5c2000-09-30 20:37:56 +0000385 dfile = dfile[len(prefix):]
386 if base_dir:
387 dfile = os.path.join(base_dir, dfile)
388
389 cfile_base = os.path.basename(cfile)
390 if direct:
391 if force or newer(file, cfile):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000392 log.info("byte-compiling %s to %s", file, cfile_base)
Greg Ward1297b5c2000-09-30 20:37:56 +0000393 if not dry_run:
394 compile(file, cfile, dfile)
395 else:
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000396 log.debug("skipping byte-compilation of %s to %s",
397 file, cfile_base)
Greg Ward1297b5c2000-09-30 20:37:56 +0000398
Andrew M. Kuchlingdf66df02001-03-22 03:03:41 +0000399
Tarek Ziadé905a2572009-07-02 14:25:23 +0000400def rfc822_escape(header):
Andrew M. Kuchlingdf66df02001-03-22 03:03:41 +0000401 """Return a version of the string escaped for inclusion in an
Andrew M. Kuchling88b08842001-03-23 17:30:26 +0000402 RFC-822 header, by ensuring there are 8 spaces space after each newline.
Andrew M. Kuchlingdf66df02001-03-22 03:03:41 +0000403 """
Tarek Ziadédf872d42009-12-06 09:28:17 +0000404 lines = header.split('\n')
405 sep = '\n' + 8 * ' '
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000406 return sep.join(lines)
Martin v. Löwis6178db62008-12-01 04:38:52 +0000407
Tarek Ziadéf8926b22009-07-16 16:18:19 +0000408_RE_VERSION = re.compile(b'(\d+\.\d+(\.\d+)*)')
409_MAC_OS_X_LD_VERSION = re.compile(b'^@\(#\)PROGRAM:ld PROJECT:ld64-((\d+)(\.\d+)*)')
410
411def _find_ld_version():
412 """Finds the ld version. The version scheme differs under Mac OSX."""
413 if sys.platform == 'darwin':
414 return _find_exe_version('ld -v', _MAC_OS_X_LD_VERSION)
415 else:
416 return _find_exe_version('ld -v')
417
418def _find_exe_version(cmd, pattern=_RE_VERSION):
419 """Find the version of an executable by running `cmd` in the shell.
420
421 `pattern` is a compiled regular expression. If not provided, default
422 to _RE_VERSION. If the command is not found, or the output does not
423 match the mattern, returns None.
424 """
425 from subprocess import Popen, PIPE
426 executable = cmd.split()[0]
427 if find_executable(executable) is None:
428 return None
429 pipe = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
430 try:
431 stdout, stderr = pipe.stdout.read(), pipe.stderr.read()
432 finally:
433 pipe.stdout.close()
434 pipe.stderr.close()
435 # some commands like ld under MacOS X, will give the
436 # output in the stderr, rather than stdout.
437 if stdout != b'':
438 out_string = stdout
439 else:
440 out_string = stderr
441
442 result = pattern.search(out_string)
443 if result is None:
444 return None
445 return LooseVersion(result.group(1).decode())
446
447def get_compiler_versions():
448 """Returns a tuple providing the versions of gcc, ld and dllwrap
449
450 For each command, if a command is not found, None is returned.
451 Otherwise a LooseVersion instance is returned.
452 """
453 gcc = _find_exe_version('gcc -dumpversion')
454 ld = _find_ld_version()
455 dllwrap = _find_exe_version('dllwrap --version')
456 return gcc, ld, dllwrap
457
Martin v. Löwis6178db62008-12-01 04:38:52 +0000458# 2to3 support
459
460def run_2to3(files, fixer_names=None, options=None, explicit=None):
461 """Invoke 2to3 on a list of Python files.
462 The files should all come from the build area, as the
463 modification is done in-place. To reduce the build time,
464 only files modified since the last invocation of this
465 function should be passed in the files argument."""
466
467 if not files:
468 return
469
470 # Make this class local, to delay import of 2to3
471 from lib2to3.refactor import RefactoringTool, get_fixers_from_package
472 class DistutilsRefactoringTool(RefactoringTool):
473 def log_error(self, msg, *args, **kw):
474 log.error(msg, *args)
475
476 def log_message(self, msg, *args):
477 log.info(msg, *args)
478
479 def log_debug(self, msg, *args):
480 log.debug(msg, *args)
481
482 if fixer_names is None:
483 fixer_names = get_fixers_from_package('lib2to3.fixes')
484 r = DistutilsRefactoringTool(fixer_names, options=options)
485 r.refactor(files, write=True)
486
Georg Brandl6d4a9cf2009-03-31 00:34:54 +0000487def copydir_run_2to3(src, dest, template=None, fixer_names=None,
488 options=None, explicit=None):
489 """Recursively copy a directory, only copying new and changed files,
490 running run_2to3 over all newly copied Python modules afterward.
491
492 If you give a template string, it's parsed like a MANIFEST.in.
493 """
494 from distutils.dir_util import mkpath
495 from distutils.file_util import copy_file
496 from distutils.filelist import FileList
497 filelist = FileList()
498 curdir = os.getcwd()
499 os.chdir(src)
500 try:
501 filelist.findall()
502 finally:
503 os.chdir(curdir)
504 filelist.files[:] = filelist.allfiles
505 if template:
506 for line in template.splitlines():
507 line = line.strip()
508 if not line: continue
509 filelist.process_template_line(line)
510 copied = []
511 for filename in filelist.files:
512 outname = os.path.join(dest, filename)
513 mkpath(os.path.dirname(outname))
514 res = copy_file(os.path.join(src, filename), outname, update=1)
515 if res[1]: copied.append(outname)
516 run_2to3([fn for fn in copied if fn.lower().endswith('.py')],
517 fixer_names=fixer_names, options=options, explicit=explicit)
518 return copied
519
Martin v. Löwis6178db62008-12-01 04:38:52 +0000520class Mixin2to3:
521 '''Mixin class for commands that run 2to3.
522 To configure 2to3, setup scripts may either change
523 the class variables, or inherit from individual commands
524 to override how 2to3 is invoked.'''
525
526 # provide list of fixers to run;
527 # defaults to all from lib2to3.fixers
528 fixer_names = None
529
530 # options dictionary
531 options = None
532
533 # list of fixers to invoke even though they are marked as explicit
534 explicit = None
535
536 def run_2to3(self, files):
537 return run_2to3(files, self.fixer_names, self.options, self.explicit)