blob: c8bf0064cdb613c8e94913ed75a2190c1118fc19 [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')
Tarek Ziadé8b441d02010-01-29 11:46:31 +000019_PLATFORM = None
20
21def 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
Greg Ward50919292000-03-07 03:27:08 +000040
Tarek Ziadé905a2572009-07-02 14:25:23 +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] == '/':
Collin Winter5b7e9d72007-08-30 03:52:21 +000056 raise ValueError("path '%s' cannot be absolute" % pathname)
Neal Norwitzb0df6a12002-08-13 17:42:57 +000057 if pathname[-1] == '/':
Collin Winter5b7e9d72007-08-30 03:52:21 +000058 raise ValueError("path '%s' cannot end with '/'" % pathname)
Greg Ward7ec05352000-09-22 01:05:43 +000059
Neal Norwitz9d72bb42007-04-17 08:48:32 +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
Neal Norwitzd9108552006-03-17 08:00:19 +000065 return os.path.join(*paths)
Greg Ward50919292000-03-07 03:27:08 +000066
Greg Ward1b4ede52000-03-22 00:22:44 +000067
Tarek Ziadé905a2572009-07-02 14:25:23 +000068def change_root(new_root, pathname):
69 """Return 'pathname' with 'new_root' prepended.
Greg Ward1b4ede52000-03-22 00:22:44 +000070
Tarek Ziadé905a2572009-07-02 14:25:23 +000071 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 else:
Tarek Ziadé905a2572009-07-02 14:25:23 +000095 raise DistutilsPlatformError("nothing known about "
96 "platform '%s'" % os.name)
Greg Ward67f75d42000-04-27 01:53:46 +000097
Gregory P. Smithe7e35ac2000-05-12 00:40:00 +000098_environ_checked = 0
Tarek Ziadé905a2572009-07-02 14:25:23 +000099
100def check_environ():
101 """Ensure that 'os.environ' has all the environment variables needed.
102
103 We guarantee that users can use in config files, command-line options,
Greg Wardb8b263b2000-09-30 18:40:42 +0000104 etc. Currently this includes:
105 HOME - user's home directory (Unix only)
106 PLAT - description of the current platform, including hardware
107 and OS (see 'get_platform()')
Greg Ward1b4ede52000-03-22 00:22:44 +0000108 """
Gregory P. Smithe7e35ac2000-05-12 00:40:00 +0000109 global _environ_checked
110 if _environ_checked:
111 return
112
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000113 if os.name == 'posix' and 'HOME' not in os.environ:
Greg Ward1b4ede52000-03-22 00:22:44 +0000114 import pwd
Greg Wardbe86bde2000-09-26 01:56:15 +0000115 os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
Greg Ward1b4ede52000-03-22 00:22:44 +0000116
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000117 if 'PLAT' not in os.environ:
Tarek Ziadéedacea32010-01-29 11:41:03 +0000118 os.environ['PLAT'] = _sysconfig.get_platform()
Greg Ward1b4ede52000-03-22 00:22:44 +0000119
Gregory P. Smithe7e35ac2000-05-12 00:40:00 +0000120 _environ_checked = 1
121
Tarek Ziadé905a2572009-07-02 14:25:23 +0000122def subst_vars(s, local_vars):
123 """Perform shell/Perl-style variable substitution on 'string'.
Greg Ward1b4ede52000-03-22 00:22:44 +0000124
Tarek Ziadé905a2572009-07-02 14:25:23 +0000125 Every occurrence of '$' followed by a name is considered a variable, and
Greg Ward47527692000-09-30 18:49:14 +0000126 variable is substituted by the value found in the 'local_vars'
127 dictionary, or in 'os.environ' if it's not in 'local_vars'.
128 'os.environ' is first checked/augmented to guarantee that it contains
129 certain values: see 'check_environ()'. Raise ValueError for any
130 variables not found in either 'local_vars' or 'os.environ'.
Greg Wardb8b263b2000-09-30 18:40:42 +0000131 """
Greg Wardbe86bde2000-09-26 01:56:15 +0000132 check_environ()
Greg Ward1b4ede52000-03-22 00:22:44 +0000133 def _subst (match, local_vars=local_vars):
134 var_name = match.group(1)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000135 if var_name in local_vars:
Greg Wardbe86bde2000-09-26 01:56:15 +0000136 return str(local_vars[var_name])
Greg Ward1b4ede52000-03-22 00:22:44 +0000137 else:
138 return os.environ[var_name]
139
Greg Ward47527692000-09-30 18:49:14 +0000140 try:
Jeremy Hylton5e2d0762001-01-25 20:10:32 +0000141 return re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s)
Guido van Rossumb940e112007-01-10 16:19:56 +0000142 except KeyError as var:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000143 raise ValueError("invalid variable '$%s'" % var)
Greg Ward1b4ede52000-03-22 00:22:44 +0000144
Tarek Ziadé905a2572009-07-02 14:25:23 +0000145def grok_environment_error(exc, prefix="error: "):
146 """Generate a useful error message from an EnvironmentError.
Greg Ward7c1a6d42000-03-29 02:48:40 +0000147
Tarek Ziadé905a2572009-07-02 14:25:23 +0000148 This will generate an IOError or an OSError exception object.
149 Handles Python 1.5.1 and 1.5.2 styles, and
Greg Warde9055132000-06-17 02:16:46 +0000150 does what it can to deal with exception objects that don't have a
151 filename (which happens when the error is due to a two-file operation,
152 such as 'rename()' or 'link()'. Returns the error message as a string
153 prefixed with 'prefix'.
154 """
155 # check for Python 1.5.2-style {IO,OS}Error exception objects
Greg Wardbe86bde2000-09-26 01:56:15 +0000156 if hasattr(exc, 'filename') and hasattr(exc, 'strerror'):
Greg Warde9055132000-06-17 02:16:46 +0000157 if exc.filename:
158 error = prefix + "%s: %s" % (exc.filename, exc.strerror)
159 else:
160 # two-argument functions in posix module don't
161 # include the filename in the exception object!
162 error = prefix + "%s" % exc.strerror
163 else:
Georg Brandl5dfe0de2008-01-06 21:41:49 +0000164 error = prefix + str(exc.args[-1])
Greg Warde9055132000-06-17 02:16:46 +0000165
166 return error
Greg Ward6a2a3db2000-06-24 20:40:02 +0000167
Greg Ward6a2a3db2000-06-24 20:40:02 +0000168# Needed by 'split_quoted()'
Martin v. Löwis1c0f1f92004-03-25 14:58:19 +0000169_wordchars_re = _squote_re = _dquote_re = None
Tarek Ziadé905a2572009-07-02 14:25:23 +0000170
Martin v. Löwis1c0f1f92004-03-25 14:58:19 +0000171def _init_regex():
172 global _wordchars_re, _squote_re, _dquote_re
173 _wordchars_re = re.compile(r'[^\\\'\"%s ]*' % string.whitespace)
174 _squote_re = re.compile(r"'(?:[^'\\]|\\.)*'")
175 _dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"')
Greg Ward6a2a3db2000-06-24 20:40:02 +0000176
Tarek Ziadé905a2572009-07-02 14:25:23 +0000177def split_quoted(s):
Greg Ward6a2a3db2000-06-24 20:40:02 +0000178 """Split a string up according to Unix shell-like rules for quotes and
Tarek Ziadé905a2572009-07-02 14:25:23 +0000179 backslashes.
180
181 In short: words are delimited by spaces, as long as those
Greg Ward6a2a3db2000-06-24 20:40:02 +0000182 spaces are not escaped by a backslash, or inside a quoted string.
183 Single and double quotes are equivalent, and the quote characters can
184 be backslash-escaped. The backslash is stripped from any two-character
185 escape sequence, leaving only the escaped character. The quote
186 characters are stripped from any quoted string. Returns a list of
187 words.
188 """
Greg Ward6a2a3db2000-06-24 20:40:02 +0000189 # This is a nice algorithm for splitting up a single string, since it
190 # doesn't require character-by-character examination. It was a little
191 # bit of a brain-bender to get it working right, though...
Martin v. Löwis1c0f1f92004-03-25 14:58:19 +0000192 if _wordchars_re is None: _init_regex()
Greg Ward6a2a3db2000-06-24 20:40:02 +0000193
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000194 s = s.strip()
Greg Ward6a2a3db2000-06-24 20:40:02 +0000195 words = []
196 pos = 0
197
198 while s:
199 m = _wordchars_re.match(s, pos)
200 end = m.end()
201 if end == len(s):
202 words.append(s[:end])
203 break
204
Greg Ward2b042de2000-08-08 14:38:13 +0000205 if s[end] in string.whitespace: # unescaped, unquoted whitespace: now
Greg Ward6a2a3db2000-06-24 20:40:02 +0000206 words.append(s[:end]) # we definitely have a word delimiter
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000207 s = s[end:].lstrip()
Greg Ward6a2a3db2000-06-24 20:40:02 +0000208 pos = 0
209
210 elif s[end] == '\\': # preserve whatever is being escaped;
211 # will become part of the current word
212 s = s[:end] + s[end+1:]
213 pos = end+1
214
215 else:
216 if s[end] == "'": # slurp singly-quoted string
217 m = _squote_re.match(s, end)
218 elif s[end] == '"': # slurp doubly-quoted string
219 m = _dquote_re.match(s, end)
220 else:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000221 raise RuntimeError("this can't happen (bad char '%c')" % s[end])
Greg Ward6a2a3db2000-06-24 20:40:02 +0000222
223 if m is None:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000224 raise ValueError("bad string (mismatched %s quotes?)" % s[end])
Greg Ward6a2a3db2000-06-24 20:40:02 +0000225
226 (beg, end) = m.span()
227 s = s[:beg] + s[beg+1:end-1] + s[end:]
228 pos = m.end() - 2
229
230 if pos >= len(s):
231 words.append(s)
232 break
233
234 return words
235
Greg Ward1c16ac32000-08-02 01:37:30 +0000236
Tarek Ziadé905a2572009-07-02 14:25:23 +0000237def execute(func, args, msg=None, verbose=0, dry_run=0):
238 """Perform some action that affects the outside world.
Greg Ward1c16ac32000-08-02 01:37:30 +0000239
Tarek Ziadé905a2572009-07-02 14:25:23 +0000240 eg. by writing to the filesystem). Such actions are special because
241 they are disabled by the 'dry_run' flag. This method takes care of all
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000242 that bureaucracy for you; all you have to do is supply the
243 function to call and an argument tuple for it (to embody the
244 "external action" being performed), and an optional message to
245 print.
Greg Ward1c16ac32000-08-02 01:37:30 +0000246 """
Greg Ward1c16ac32000-08-02 01:37:30 +0000247 if msg is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000248 msg = "%s%r" % (func.__name__, args)
Fred Drakeb94b8492001-12-06 20:51:35 +0000249 if msg[-2:] == ',)': # correct for singleton tuple
Greg Ward1c16ac32000-08-02 01:37:30 +0000250 msg = msg[0:-2] + ')'
251
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000252 log.info(msg)
Greg Ward1c16ac32000-08-02 01:37:30 +0000253 if not dry_run:
Neal Norwitzd9108552006-03-17 08:00:19 +0000254 func(*args)
Greg Ward1c16ac32000-08-02 01:37:30 +0000255
Greg Ward817dc092000-09-25 01:25:06 +0000256
Tarek Ziadé905a2572009-07-02 14:25:23 +0000257def strtobool(val):
Greg Ward817dc092000-09-25 01:25:06 +0000258 """Convert a string representation of truth to true (1) or false (0).
Tim Peters182b5ac2004-07-18 06:16:08 +0000259
Greg Ward817dc092000-09-25 01:25:06 +0000260 True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
261 are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
262 'val' is anything else.
263 """
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000264 val = val.lower()
Greg Ward817dc092000-09-25 01:25:06 +0000265 if val in ('y', 'yes', 't', 'true', 'on', '1'):
266 return 1
267 elif val in ('n', 'no', 'f', 'false', 'off', '0'):
268 return 0
269 else:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000270 raise ValueError("invalid truth value %r" % (val,))
Greg Ward1297b5c2000-09-30 20:37:56 +0000271
272
Tarek Ziadé905a2572009-07-02 14:25:23 +0000273def byte_compile(py_files, optimize=0, force=0, prefix=None, base_dir=None,
274 verbose=1, dry_run=0, direct=None):
Greg Wardf217e212000-10-01 23:49:30 +0000275 """Byte-compile a collection of Python source files to either .pyc
Tarek Ziadé905a2572009-07-02 14:25:23 +0000276 or .pyo files in the same directory.
277
278 'py_files' is a list of files to compile; any files that don't end in
279 ".py" are silently skipped. 'optimize' must be one of the following:
Greg Ward1297b5c2000-09-30 20:37:56 +0000280 0 - don't optimize (generate .pyc)
281 1 - normal optimization (like "python -O")
282 2 - extra optimization (like "python -OO")
283 If 'force' is true, all files are recompiled regardless of
284 timestamps.
285
286 The source filename encoded in each bytecode file defaults to the
287 filenames listed in 'py_files'; you can modify these with 'prefix' and
288 'basedir'. 'prefix' is a string that will be stripped off of each
289 source filename, and 'base_dir' is a directory name that will be
290 prepended (after 'prefix' is stripped). You can supply either or both
291 (or neither) of 'prefix' and 'base_dir', as you wish.
292
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000293 If 'dry_run' is true, doesn't actually do anything that would
294 affect the filesystem.
Greg Ward1297b5c2000-09-30 20:37:56 +0000295
296 Byte-compilation is either done directly in this interpreter process
297 with the standard py_compile module, or indirectly by writing a
298 temporary script and executing it. Normally, you should let
299 'byte_compile()' figure out to use direct compilation or not (see
300 the source for details). The 'direct' flag is used by the script
301 generated in indirect mode; unless you know what you're doing, leave
302 it set to None.
303 """
Tarek Ziadé04fe7c02009-10-25 23:08:47 +0000304 # nothing is done if sys.dont_write_bytecode is True
305 if sys.dont_write_bytecode:
306 raise DistutilsByteCompileError('byte-compiling is disabled.')
307
Greg Ward1297b5c2000-09-30 20:37:56 +0000308 # First, if the caller didn't force us into direct or indirect mode,
309 # figure out which mode we should be in. We take a conservative
310 # approach: choose direct mode *only* if the current interpreter is
311 # in debug mode and optimize is 0. If we're not in debug mode (-O
312 # or -OO), we don't know which level of optimization this
313 # interpreter is running with, so we can't do direct
314 # byte-compilation and be certain that it's the right thing. Thus,
315 # always compile indirectly if the current interpreter is in either
316 # optimize mode, or if either optimization level was requested by
317 # the caller.
318 if direct is None:
319 direct = (__debug__ and optimize == 0)
320
321 # "Indirect" byte-compilation: write a temporary script and then
322 # run it with the appropriate flags.
323 if not direct:
Marc-André Lemburg03750792002-12-03 08:45:11 +0000324 try:
325 from tempfile import mkstemp
326 (script_fd, script_name) = mkstemp(".py")
327 except ImportError:
328 from tempfile import mktemp
329 (script_fd, script_name) = None, mktemp(".py")
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000330 log.info("writing byte-compilation script '%s'", script_name)
Greg Ward1297b5c2000-09-30 20:37:56 +0000331 if not dry_run:
Marc-André Lemburg03750792002-12-03 08:45:11 +0000332 if script_fd is not None:
333 script = os.fdopen(script_fd, "w")
334 else:
335 script = open(script_name, "w")
Greg Ward1297b5c2000-09-30 20:37:56 +0000336
337 script.write("""\
338from distutils.util import byte_compile
339files = [
340""")
Greg Ward9216cfe2000-10-03 03:31:05 +0000341
342 # XXX would be nice to write absolute filenames, just for
343 # safety's sake (script should be more robust in the face of
344 # chdir'ing before running it). But this requires abspath'ing
345 # 'prefix' as well, and that breaks the hack in build_lib's
346 # 'byte_compile()' method that carefully tacks on a trailing
347 # slash (os.sep really) to make sure the prefix here is "just
348 # right". This whole prefix business is rather delicate -- the
349 # problem is that it's really a directory, but I'm treating it
350 # as a dumb string, so trailing slashes and so forth matter.
351
352 #py_files = map(os.path.abspath, py_files)
353 #if prefix:
354 # prefix = os.path.abspath(prefix)
355
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000356 script.write(",\n".join(map(repr, py_files)) + "]\n")
Greg Ward1297b5c2000-09-30 20:37:56 +0000357 script.write("""
Walter Dörwald70a6b492004-02-12 17:35:32 +0000358byte_compile(files, optimize=%r, force=%r,
359 prefix=%r, base_dir=%r,
360 verbose=%r, dry_run=0,
Greg Ward1297b5c2000-09-30 20:37:56 +0000361 direct=1)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000362""" % (optimize, force, prefix, base_dir, verbose))
Greg Ward1297b5c2000-09-30 20:37:56 +0000363
364 script.close()
365
366 cmd = [sys.executable, script_name]
367 if optimize == 1:
368 cmd.insert(1, "-O")
369 elif optimize == 2:
370 cmd.insert(1, "-OO")
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000371 spawn(cmd, dry_run=dry_run)
Greg Ward9216cfe2000-10-03 03:31:05 +0000372 execute(os.remove, (script_name,), "removing %s" % script_name,
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000373 dry_run=dry_run)
Fred Drakeb94b8492001-12-06 20:51:35 +0000374
Greg Ward1297b5c2000-09-30 20:37:56 +0000375 # "Direct" byte-compilation: use the py_compile module to compile
376 # right here, right now. Note that the script generated in indirect
377 # mode simply calls 'byte_compile()' in direct mode, a weird sort of
378 # cross-process recursion. Hey, it works!
379 else:
380 from py_compile import compile
381
382 for file in py_files:
383 if file[-3:] != ".py":
Greg Wardf217e212000-10-01 23:49:30 +0000384 # This lets us be lazy and not filter filenames in
385 # the "install_lib" command.
386 continue
Greg Ward1297b5c2000-09-30 20:37:56 +0000387
388 # Terminology from the py_compile module:
389 # cfile - byte-compiled file
390 # dfile - purported source filename (same as 'file' by default)
391 cfile = file + (__debug__ and "c" or "o")
392 dfile = file
393 if prefix:
394 if file[:len(prefix)] != prefix:
Tarek Ziadé905a2572009-07-02 14:25:23 +0000395 raise ValueError("invalid prefix: filename %r doesn't "
396 "start with %r" % (file, prefix))
Greg Ward1297b5c2000-09-30 20:37:56 +0000397 dfile = dfile[len(prefix):]
398 if base_dir:
399 dfile = os.path.join(base_dir, dfile)
400
401 cfile_base = os.path.basename(cfile)
402 if direct:
403 if force or newer(file, cfile):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000404 log.info("byte-compiling %s to %s", file, cfile_base)
Greg Ward1297b5c2000-09-30 20:37:56 +0000405 if not dry_run:
406 compile(file, cfile, dfile)
407 else:
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000408 log.debug("skipping byte-compilation of %s to %s",
409 file, cfile_base)
Greg Ward1297b5c2000-09-30 20:37:56 +0000410
Andrew M. Kuchlingdf66df02001-03-22 03:03:41 +0000411
Tarek Ziadé905a2572009-07-02 14:25:23 +0000412def rfc822_escape(header):
Andrew M. Kuchlingdf66df02001-03-22 03:03:41 +0000413 """Return a version of the string escaped for inclusion in an
Andrew M. Kuchling88b08842001-03-23 17:30:26 +0000414 RFC-822 header, by ensuring there are 8 spaces space after each newline.
Andrew M. Kuchlingdf66df02001-03-22 03:03:41 +0000415 """
Tarek Ziadédf872d42009-12-06 09:28:17 +0000416 lines = header.split('\n')
417 sep = '\n' + 8 * ' '
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000418 return sep.join(lines)
Martin v. Löwis6178db62008-12-01 04:38:52 +0000419
Tarek Ziadéf8926b22009-07-16 16:18:19 +0000420_RE_VERSION = re.compile(b'(\d+\.\d+(\.\d+)*)')
421_MAC_OS_X_LD_VERSION = re.compile(b'^@\(#\)PROGRAM:ld PROJECT:ld64-((\d+)(\.\d+)*)')
422
423def _find_ld_version():
424 """Finds the ld version. The version scheme differs under Mac OSX."""
425 if sys.platform == 'darwin':
426 return _find_exe_version('ld -v', _MAC_OS_X_LD_VERSION)
427 else:
428 return _find_exe_version('ld -v')
429
430def _find_exe_version(cmd, pattern=_RE_VERSION):
431 """Find the version of an executable by running `cmd` in the shell.
432
433 `pattern` is a compiled regular expression. If not provided, default
434 to _RE_VERSION. If the command is not found, or the output does not
435 match the mattern, returns None.
436 """
437 from subprocess import Popen, PIPE
438 executable = cmd.split()[0]
439 if find_executable(executable) is None:
440 return None
441 pipe = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
442 try:
443 stdout, stderr = pipe.stdout.read(), pipe.stderr.read()
444 finally:
445 pipe.stdout.close()
446 pipe.stderr.close()
447 # some commands like ld under MacOS X, will give the
448 # output in the stderr, rather than stdout.
449 if stdout != b'':
450 out_string = stdout
451 else:
452 out_string = stderr
453
454 result = pattern.search(out_string)
455 if result is None:
456 return None
457 return LooseVersion(result.group(1).decode())
458
459def get_compiler_versions():
460 """Returns a tuple providing the versions of gcc, ld and dllwrap
461
462 For each command, if a command is not found, None is returned.
463 Otherwise a LooseVersion instance is returned.
464 """
465 gcc = _find_exe_version('gcc -dumpversion')
466 ld = _find_ld_version()
467 dllwrap = _find_exe_version('dllwrap --version')
468 return gcc, ld, dllwrap
469
Martin v. Löwis6178db62008-12-01 04:38:52 +0000470# 2to3 support
471
472def run_2to3(files, fixer_names=None, options=None, explicit=None):
473 """Invoke 2to3 on a list of Python files.
474 The files should all come from the build area, as the
475 modification is done in-place. To reduce the build time,
476 only files modified since the last invocation of this
477 function should be passed in the files argument."""
478
479 if not files:
480 return
481
482 # Make this class local, to delay import of 2to3
483 from lib2to3.refactor import RefactoringTool, get_fixers_from_package
484 class DistutilsRefactoringTool(RefactoringTool):
485 def log_error(self, msg, *args, **kw):
486 log.error(msg, *args)
487
488 def log_message(self, msg, *args):
489 log.info(msg, *args)
490
491 def log_debug(self, msg, *args):
492 log.debug(msg, *args)
493
494 if fixer_names is None:
495 fixer_names = get_fixers_from_package('lib2to3.fixes')
496 r = DistutilsRefactoringTool(fixer_names, options=options)
497 r.refactor(files, write=True)
498
Georg Brandl6d4a9cf2009-03-31 00:34:54 +0000499def copydir_run_2to3(src, dest, template=None, fixer_names=None,
500 options=None, explicit=None):
501 """Recursively copy a directory, only copying new and changed files,
502 running run_2to3 over all newly copied Python modules afterward.
503
504 If you give a template string, it's parsed like a MANIFEST.in.
505 """
506 from distutils.dir_util import mkpath
507 from distutils.file_util import copy_file
508 from distutils.filelist import FileList
509 filelist = FileList()
510 curdir = os.getcwd()
511 os.chdir(src)
512 try:
513 filelist.findall()
514 finally:
515 os.chdir(curdir)
516 filelist.files[:] = filelist.allfiles
517 if template:
518 for line in template.splitlines():
519 line = line.strip()
520 if not line: continue
521 filelist.process_template_line(line)
522 copied = []
523 for filename in filelist.files:
524 outname = os.path.join(dest, filename)
525 mkpath(os.path.dirname(outname))
526 res = copy_file(os.path.join(src, filename), outname, update=1)
527 if res[1]: copied.append(outname)
528 run_2to3([fn for fn in copied if fn.lower().endswith('.py')],
529 fixer_names=fixer_names, options=options, explicit=explicit)
530 return copied
531
Martin v. Löwis6178db62008-12-01 04:38:52 +0000532class Mixin2to3:
533 '''Mixin class for commands that run 2to3.
534 To configure 2to3, setup scripts may either change
535 the class variables, or inherit from individual commands
536 to override how 2to3 is invoked.'''
537
538 # provide list of fixers to run;
539 # defaults to all from lib2to3.fixers
540 fixer_names = None
541
542 # options dictionary
543 options = None
544
545 # list of fixers to invoke even though they are marked as explicit
546 explicit = None
547
548 def run_2to3(self, files):
549 return run_2to3(files, self.fixer_names, self.options, self.explicit)