blob: 8fd2ca077f10ebc5c6a69c2c9468d43f3bbe71de [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 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
Neal Norwitz9d72bb42007-04-17 08:48:32 +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é905a2572009-07-02 14:25:23 +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é905a2572009-07-02 14:25:23 +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 Rossume2b70bc2006-08-18 22:13:04 +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 Rossume2b70bc2006-08-18 22:13:04 +0000126 if 'PLAT' not in os.environ:
Tarek Ziadéedacea32010-01-29 11:41:03 +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é905a2572009-07-02 14:25:23 +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é905a2572009-07-02 14:25:23 +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 Rossume2b70bc2006-08-18 22:13:04 +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)
Guido van Rossumb940e112007-01-10 16:19:56 +0000151 except KeyError as var:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000152 raise ValueError("invalid variable '$%s'" % var)
Greg Ward1b4ede52000-03-22 00:22:44 +0000153
Tarek Ziadé905a2572009-07-02 14:25:23 +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é905a2572009-07-02 14:25:23 +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:
Georg Brandl5dfe0de2008-01-06 21:41:49 +0000173 error = prefix + str(exc.args[-1])
Greg Warde9055132000-06-17 02:16:46 +0000174
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é905a2572009-07-02 14:25:23 +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é905a2572009-07-02 14:25:23 +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é905a2572009-07-02 14:25:23 +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
Neal Norwitz9d72bb42007-04-17 08:48:32 +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
Neal Norwitz9d72bb42007-04-17 08:48:32 +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:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000230 raise RuntimeError("this can't happen (bad char '%c')" % s[end])
Greg Ward6a2a3db2000-06-24 20:40:02 +0000231
232 if m is None:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000233 raise ValueError("bad string (mismatched %s quotes?)" % s[end])
Greg Ward6a2a3db2000-06-24 20:40:02 +0000234
235 (beg, end) = m.span()
236 s = s[:beg] + s[beg+1:end-1] + s[end:]
237 pos = m.end() - 2
238
239 if pos >= len(s):
240 words.append(s)
241 break
242
243 return words
244
Greg Ward1c16ac32000-08-02 01:37:30 +0000245
Tarek Ziadé905a2572009-07-02 14:25:23 +0000246def execute(func, args, msg=None, verbose=0, dry_run=0):
247 """Perform some action that affects the outside world.
Greg Ward1c16ac32000-08-02 01:37:30 +0000248
Tarek Ziadé905a2572009-07-02 14:25:23 +0000249 eg. by writing to the filesystem). Such actions are special because
250 they are disabled by the 'dry_run' flag. This method takes care of all
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000251 that bureaucracy for you; all you have to do is supply the
252 function to call and an argument tuple for it (to embody the
253 "external action" being performed), and an optional message to
254 print.
Greg Ward1c16ac32000-08-02 01:37:30 +0000255 """
Greg Ward1c16ac32000-08-02 01:37:30 +0000256 if msg is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000257 msg = "%s%r" % (func.__name__, args)
Fred Drakeb94b8492001-12-06 20:51:35 +0000258 if msg[-2:] == ',)': # correct for singleton tuple
Greg Ward1c16ac32000-08-02 01:37:30 +0000259 msg = msg[0:-2] + ')'
260
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000261 log.info(msg)
Greg Ward1c16ac32000-08-02 01:37:30 +0000262 if not dry_run:
Neal Norwitzd9108552006-03-17 08:00:19 +0000263 func(*args)
Greg Ward1c16ac32000-08-02 01:37:30 +0000264
Greg Ward817dc092000-09-25 01:25:06 +0000265
Tarek Ziadé905a2572009-07-02 14:25:23 +0000266def strtobool(val):
Greg Ward817dc092000-09-25 01:25:06 +0000267 """Convert a string representation of truth to true (1) or false (0).
Tim Peters182b5ac2004-07-18 06:16:08 +0000268
Greg Ward817dc092000-09-25 01:25:06 +0000269 True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
270 are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
271 'val' is anything else.
272 """
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000273 val = val.lower()
Greg Ward817dc092000-09-25 01:25:06 +0000274 if val in ('y', 'yes', 't', 'true', 'on', '1'):
275 return 1
276 elif val in ('n', 'no', 'f', 'false', 'off', '0'):
277 return 0
278 else:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000279 raise ValueError("invalid truth value %r" % (val,))
Greg Ward1297b5c2000-09-30 20:37:56 +0000280
281
Tarek Ziadé905a2572009-07-02 14:25:23 +0000282def byte_compile(py_files, optimize=0, force=0, prefix=None, base_dir=None,
283 verbose=1, dry_run=0, direct=None):
Greg Wardf217e212000-10-01 23:49:30 +0000284 """Byte-compile a collection of Python source files to either .pyc
Tarek Ziadé905a2572009-07-02 14:25:23 +0000285 or .pyo files in the same directory.
286
287 'py_files' is a list of files to compile; any files that don't end in
288 ".py" are silently skipped. 'optimize' must be one of the following:
Greg Ward1297b5c2000-09-30 20:37:56 +0000289 0 - don't optimize (generate .pyc)
290 1 - normal optimization (like "python -O")
291 2 - extra optimization (like "python -OO")
292 If 'force' is true, all files are recompiled regardless of
293 timestamps.
294
295 The source filename encoded in each bytecode file defaults to the
296 filenames listed in 'py_files'; you can modify these with 'prefix' and
297 'basedir'. 'prefix' is a string that will be stripped off of each
298 source filename, and 'base_dir' is a directory name that will be
299 prepended (after 'prefix' is stripped). You can supply either or both
300 (or neither) of 'prefix' and 'base_dir', as you wish.
301
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000302 If 'dry_run' is true, doesn't actually do anything that would
303 affect the filesystem.
Greg Ward1297b5c2000-09-30 20:37:56 +0000304
305 Byte-compilation is either done directly in this interpreter process
306 with the standard py_compile module, or indirectly by writing a
307 temporary script and executing it. Normally, you should let
308 'byte_compile()' figure out to use direct compilation or not (see
309 the source for details). The 'direct' flag is used by the script
310 generated in indirect mode; unless you know what you're doing, leave
311 it set to None.
312 """
Tarek Ziadé04fe7c02009-10-25 23:08:47 +0000313 # nothing is done if sys.dont_write_bytecode is True
314 if sys.dont_write_bytecode:
315 raise DistutilsByteCompileError('byte-compiling is disabled.')
316
Greg Ward1297b5c2000-09-30 20:37:56 +0000317 # First, if the caller didn't force us into direct or indirect mode,
318 # figure out which mode we should be in. We take a conservative
319 # approach: choose direct mode *only* if the current interpreter is
320 # in debug mode and optimize is 0. If we're not in debug mode (-O
321 # or -OO), we don't know which level of optimization this
322 # interpreter is running with, so we can't do direct
323 # byte-compilation and be certain that it's the right thing. Thus,
324 # always compile indirectly if the current interpreter is in either
325 # optimize mode, or if either optimization level was requested by
326 # the caller.
327 if direct is None:
328 direct = (__debug__ and optimize == 0)
329
330 # "Indirect" byte-compilation: write a temporary script and then
331 # run it with the appropriate flags.
332 if not direct:
Marc-André Lemburg03750792002-12-03 08:45:11 +0000333 try:
334 from tempfile import mkstemp
335 (script_fd, script_name) = mkstemp(".py")
336 except ImportError:
337 from tempfile import mktemp
338 (script_fd, script_name) = None, mktemp(".py")
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000339 log.info("writing byte-compilation script '%s'", script_name)
Greg Ward1297b5c2000-09-30 20:37:56 +0000340 if not dry_run:
Marc-André Lemburg03750792002-12-03 08:45:11 +0000341 if script_fd is not None:
342 script = os.fdopen(script_fd, "w")
343 else:
344 script = open(script_name, "w")
Greg Ward1297b5c2000-09-30 20:37:56 +0000345
346 script.write("""\
347from distutils.util import byte_compile
348files = [
349""")
Greg Ward9216cfe2000-10-03 03:31:05 +0000350
351 # XXX would be nice to write absolute filenames, just for
352 # safety's sake (script should be more robust in the face of
353 # chdir'ing before running it). But this requires abspath'ing
354 # 'prefix' as well, and that breaks the hack in build_lib's
355 # 'byte_compile()' method that carefully tacks on a trailing
356 # slash (os.sep really) to make sure the prefix here is "just
357 # right". This whole prefix business is rather delicate -- the
358 # problem is that it's really a directory, but I'm treating it
359 # as a dumb string, so trailing slashes and so forth matter.
360
361 #py_files = map(os.path.abspath, py_files)
362 #if prefix:
363 # prefix = os.path.abspath(prefix)
364
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000365 script.write(",\n".join(map(repr, py_files)) + "]\n")
Greg Ward1297b5c2000-09-30 20:37:56 +0000366 script.write("""
Walter Dörwald70a6b492004-02-12 17:35:32 +0000367byte_compile(files, optimize=%r, force=%r,
368 prefix=%r, base_dir=%r,
369 verbose=%r, dry_run=0,
Greg Ward1297b5c2000-09-30 20:37:56 +0000370 direct=1)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000371""" % (optimize, force, prefix, base_dir, verbose))
Greg Ward1297b5c2000-09-30 20:37:56 +0000372
373 script.close()
374
375 cmd = [sys.executable, script_name]
376 if optimize == 1:
377 cmd.insert(1, "-O")
378 elif optimize == 2:
379 cmd.insert(1, "-OO")
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000380 spawn(cmd, dry_run=dry_run)
Greg Ward9216cfe2000-10-03 03:31:05 +0000381 execute(os.remove, (script_name,), "removing %s" % script_name,
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000382 dry_run=dry_run)
Fred Drakeb94b8492001-12-06 20:51:35 +0000383
Greg Ward1297b5c2000-09-30 20:37:56 +0000384 # "Direct" byte-compilation: use the py_compile module to compile
385 # right here, right now. Note that the script generated in indirect
386 # mode simply calls 'byte_compile()' in direct mode, a weird sort of
387 # cross-process recursion. Hey, it works!
388 else:
389 from py_compile import compile
390
391 for file in py_files:
392 if file[-3:] != ".py":
Greg Wardf217e212000-10-01 23:49:30 +0000393 # This lets us be lazy and not filter filenames in
394 # the "install_lib" command.
395 continue
Greg Ward1297b5c2000-09-30 20:37:56 +0000396
397 # Terminology from the py_compile module:
398 # cfile - byte-compiled file
399 # dfile - purported source filename (same as 'file' by default)
400 cfile = file + (__debug__ and "c" or "o")
401 dfile = file
402 if prefix:
403 if file[:len(prefix)] != prefix:
Tarek Ziadé905a2572009-07-02 14:25:23 +0000404 raise ValueError("invalid prefix: filename %r doesn't "
405 "start with %r" % (file, prefix))
Greg Ward1297b5c2000-09-30 20:37:56 +0000406 dfile = dfile[len(prefix):]
407 if base_dir:
408 dfile = os.path.join(base_dir, dfile)
409
410 cfile_base = os.path.basename(cfile)
411 if direct:
412 if force or newer(file, cfile):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000413 log.info("byte-compiling %s to %s", file, cfile_base)
Greg Ward1297b5c2000-09-30 20:37:56 +0000414 if not dry_run:
415 compile(file, cfile, dfile)
416 else:
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000417 log.debug("skipping byte-compilation of %s to %s",
418 file, cfile_base)
Greg Ward1297b5c2000-09-30 20:37:56 +0000419
Andrew M. Kuchlingdf66df02001-03-22 03:03:41 +0000420
Tarek Ziadé905a2572009-07-02 14:25:23 +0000421def rfc822_escape(header):
Andrew M. Kuchlingdf66df02001-03-22 03:03:41 +0000422 """Return a version of the string escaped for inclusion in an
Andrew M. Kuchling88b08842001-03-23 17:30:26 +0000423 RFC-822 header, by ensuring there are 8 spaces space after each newline.
Andrew M. Kuchlingdf66df02001-03-22 03:03:41 +0000424 """
Tarek Ziadédf872d42009-12-06 09:28:17 +0000425 lines = header.split('\n')
426 sep = '\n' + 8 * ' '
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000427 return sep.join(lines)
Martin v. Löwis6178db62008-12-01 04:38:52 +0000428
Tarek Ziadéf8926b22009-07-16 16:18:19 +0000429_RE_VERSION = re.compile(b'(\d+\.\d+(\.\d+)*)')
430_MAC_OS_X_LD_VERSION = re.compile(b'^@\(#\)PROGRAM:ld PROJECT:ld64-((\d+)(\.\d+)*)')
431
432def _find_ld_version():
433 """Finds the ld version. The version scheme differs under Mac OSX."""
434 if sys.platform == 'darwin':
435 return _find_exe_version('ld -v', _MAC_OS_X_LD_VERSION)
436 else:
437 return _find_exe_version('ld -v')
438
439def _find_exe_version(cmd, pattern=_RE_VERSION):
440 """Find the version of an executable by running `cmd` in the shell.
441
442 `pattern` is a compiled regular expression. If not provided, default
443 to _RE_VERSION. If the command is not found, or the output does not
444 match the mattern, returns None.
445 """
446 from subprocess import Popen, PIPE
447 executable = cmd.split()[0]
448 if find_executable(executable) is None:
449 return None
450 pipe = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
451 try:
452 stdout, stderr = pipe.stdout.read(), pipe.stderr.read()
453 finally:
454 pipe.stdout.close()
455 pipe.stderr.close()
456 # some commands like ld under MacOS X, will give the
457 # output in the stderr, rather than stdout.
458 if stdout != b'':
459 out_string = stdout
460 else:
461 out_string = stderr
462
463 result = pattern.search(out_string)
464 if result is None:
465 return None
466 return LooseVersion(result.group(1).decode())
467
468def get_compiler_versions():
469 """Returns a tuple providing the versions of gcc, ld and dllwrap
470
471 For each command, if a command is not found, None is returned.
472 Otherwise a LooseVersion instance is returned.
473 """
474 gcc = _find_exe_version('gcc -dumpversion')
475 ld = _find_ld_version()
476 dllwrap = _find_exe_version('dllwrap --version')
477 return gcc, ld, dllwrap
478
Martin v. Löwis6178db62008-12-01 04:38:52 +0000479# 2to3 support
480
481def run_2to3(files, fixer_names=None, options=None, explicit=None):
482 """Invoke 2to3 on a list of Python files.
483 The files should all come from the build area, as the
484 modification is done in-place. To reduce the build time,
485 only files modified since the last invocation of this
486 function should be passed in the files argument."""
487
488 if not files:
489 return
490
491 # Make this class local, to delay import of 2to3
492 from lib2to3.refactor import RefactoringTool, get_fixers_from_package
493 class DistutilsRefactoringTool(RefactoringTool):
494 def log_error(self, msg, *args, **kw):
495 log.error(msg, *args)
496
497 def log_message(self, msg, *args):
498 log.info(msg, *args)
499
500 def log_debug(self, msg, *args):
501 log.debug(msg, *args)
502
503 if fixer_names is None:
504 fixer_names = get_fixers_from_package('lib2to3.fixes')
505 r = DistutilsRefactoringTool(fixer_names, options=options)
506 r.refactor(files, write=True)
507
Georg Brandl6d4a9cf2009-03-31 00:34:54 +0000508def copydir_run_2to3(src, dest, template=None, fixer_names=None,
509 options=None, explicit=None):
510 """Recursively copy a directory, only copying new and changed files,
511 running run_2to3 over all newly copied Python modules afterward.
512
513 If you give a template string, it's parsed like a MANIFEST.in.
514 """
515 from distutils.dir_util import mkpath
516 from distutils.file_util import copy_file
517 from distutils.filelist import FileList
518 filelist = FileList()
519 curdir = os.getcwd()
520 os.chdir(src)
521 try:
522 filelist.findall()
523 finally:
524 os.chdir(curdir)
525 filelist.files[:] = filelist.allfiles
526 if template:
527 for line in template.splitlines():
528 line = line.strip()
529 if not line: continue
530 filelist.process_template_line(line)
531 copied = []
532 for filename in filelist.files:
533 outname = os.path.join(dest, filename)
534 mkpath(os.path.dirname(outname))
535 res = copy_file(os.path.join(src, filename), outname, update=1)
536 if res[1]: copied.append(outname)
537 run_2to3([fn for fn in copied if fn.lower().endswith('.py')],
538 fixer_names=fixer_names, options=options, explicit=explicit)
539 return copied
540
Martin v. Löwis6178db62008-12-01 04:38:52 +0000541class Mixin2to3:
542 '''Mixin class for commands that run 2to3.
543 To configure 2to3, setup scripts may either change
544 the class variables, or inherit from individual commands
545 to override how 2to3 is invoked.'''
546
547 # provide list of fixers to run;
548 # defaults to all from lib2to3.fixers
549 fixer_names = None
550
551 # options dictionary
552 options = None
553
554 # list of fixers to invoke even though they are marked as explicit
555 explicit = None
556
557 def run_2to3(self, files):
558 return run_2to3(files, self.fixer_names, self.options, self.explicit)