Greg Ward | 2689e3d | 1999-03-22 14:52:19 +0000 | [diff] [blame] | 1 | """distutils.util |
| 2 | |
Greg Ward | aebf706 | 2000-04-04 02:05:59 +0000 | [diff] [blame] | 3 | Miscellaneous utility functions -- anything that doesn't fit into |
Greg Ward | 4752769 | 2000-09-30 18:49:14 +0000 | [diff] [blame] | 4 | one of the other *util.py modules. |
| 5 | """ |
Greg Ward | 2689e3d | 1999-03-22 14:52:19 +0000 | [diff] [blame] | 6 | |
Greg Ward | 3ce77fd | 2000-03-02 01:49:45 +0000 | [diff] [blame] | 7 | __revision__ = "$Id$" |
Greg Ward | 2689e3d | 1999-03-22 14:52:19 +0000 | [diff] [blame] | 8 | |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 9 | import sys, os, string, re |
Tarek Ziadé | f8926b2 | 2009-07-16 16:18:19 +0000 | [diff] [blame] | 10 | |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 11 | from distutils.errors import DistutilsPlatformError |
| 12 | from distutils.dep_util import newer |
Tarek Ziadé | f8926b2 | 2009-07-16 16:18:19 +0000 | [diff] [blame] | 13 | from distutils.spawn import spawn, find_executable |
Jeremy Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 14 | from distutils import log |
Tarek Ziadé | f8926b2 | 2009-07-16 16:18:19 +0000 | [diff] [blame] | 15 | from distutils.version import LooseVersion |
Tarek Ziadé | 04fe7c0 | 2009-10-25 23:08:47 +0000 | [diff] [blame] | 16 | from distutils.errors import DistutilsByteCompileError |
Greg Ward | aa458bc | 2000-04-22 15:14:58 +0000 | [diff] [blame] | 17 | |
Tarek Ziadé | edacea3 | 2010-01-29 11:41:03 +0000 | [diff] [blame] | 18 | _sysconfig = __import__('sysconfig') |
Tarek Ziadé | 8b441d0 | 2010-01-29 11:46:31 +0000 | [diff] [blame] | 19 | _PLATFORM = None |
| 20 | |
| 21 | def 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 | |
| 32 | def 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 Ward | 5091929 | 2000-03-07 03:27:08 +0000 | [diff] [blame] | 40 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 41 | def convert_path(pathname): |
| 42 | """Return 'pathname' as a name that will work on the native filesystem. |
Greg Ward | 5091929 | 2000-03-07 03:27:08 +0000 | [diff] [blame] | 43 | |
Greg Ward | b8b263b | 2000-09-30 18:40:42 +0000 | [diff] [blame] | 44 | 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 Ward | 4752769 | 2000-09-30 18:49:14 +0000 | [diff] [blame] | 48 | ValueError on non-Unix-ish systems if 'pathname' either starts or |
| 49 | ends with a slash. |
Greg Ward | b8b263b | 2000-09-30 18:40:42 +0000 | [diff] [blame] | 50 | """ |
Greg Ward | 7ec0535 | 2000-09-22 01:05:43 +0000 | [diff] [blame] | 51 | if os.sep == '/': |
| 52 | return pathname |
Neal Norwitz | b0df6a1 | 2002-08-13 17:42:57 +0000 | [diff] [blame] | 53 | if not pathname: |
| 54 | return pathname |
| 55 | if pathname[0] == '/': |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 56 | raise ValueError("path '%s' cannot be absolute" % pathname) |
Neal Norwitz | b0df6a1 | 2002-08-13 17:42:57 +0000 | [diff] [blame] | 57 | if pathname[-1] == '/': |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 58 | raise ValueError("path '%s' cannot end with '/'" % pathname) |
Greg Ward | 7ec0535 | 2000-09-22 01:05:43 +0000 | [diff] [blame] | 59 | |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 60 | paths = pathname.split('/') |
Jack Jansen | b4cd5c1 | 2001-01-28 12:23:32 +0000 | [diff] [blame] | 61 | while '.' in paths: |
| 62 | paths.remove('.') |
| 63 | if not paths: |
| 64 | return os.curdir |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 65 | return os.path.join(*paths) |
Greg Ward | 5091929 | 2000-03-07 03:27:08 +0000 | [diff] [blame] | 66 | |
Greg Ward | 1b4ede5 | 2000-03-22 00:22:44 +0000 | [diff] [blame] | 67 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 68 | def change_root(new_root, pathname): |
| 69 | """Return 'pathname' with 'new_root' prepended. |
Greg Ward | 1b4ede5 | 2000-03-22 00:22:44 +0000 | [diff] [blame] | 70 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 71 | If 'pathname' is relative, this is equivalent to |
| 72 | "os.path.join(new_root,pathname)". |
Greg Ward | 67f75d4 | 2000-04-27 01:53:46 +0000 | [diff] [blame] | 73 | Otherwise, it requires making 'pathname' relative and then joining the |
Greg Ward | 4b46ef9 | 2000-05-31 02:14:32 +0000 | [diff] [blame] | 74 | two, which is tricky on DOS/Windows and Mac OS. |
| 75 | """ |
| 76 | if os.name == 'posix': |
Greg Ward | be86bde | 2000-09-26 01:56:15 +0000 | [diff] [blame] | 77 | if not os.path.isabs(pathname): |
| 78 | return os.path.join(new_root, pathname) |
Greg Ward | 4b46ef9 | 2000-05-31 02:14:32 +0000 | [diff] [blame] | 79 | else: |
Greg Ward | be86bde | 2000-09-26 01:56:15 +0000 | [diff] [blame] | 80 | return os.path.join(new_root, pathname[1:]) |
Greg Ward | 67f75d4 | 2000-04-27 01:53:46 +0000 | [diff] [blame] | 81 | |
| 82 | elif os.name == 'nt': |
Greg Ward | be86bde | 2000-09-26 01:56:15 +0000 | [diff] [blame] | 83 | (drive, path) = os.path.splitdrive(pathname) |
Greg Ward | 4b46ef9 | 2000-05-31 02:14:32 +0000 | [diff] [blame] | 84 | if path[0] == '\\': |
| 85 | path = path[1:] |
Greg Ward | be86bde | 2000-09-26 01:56:15 +0000 | [diff] [blame] | 86 | return os.path.join(new_root, path) |
Greg Ward | 67f75d4 | 2000-04-27 01:53:46 +0000 | [diff] [blame] | 87 | |
Marc-André Lemburg | 2544f51 | 2002-01-31 18:56:00 +0000 | [diff] [blame] | 88 | 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 Ward | 67f75d4 | 2000-04-27 01:53:46 +0000 | [diff] [blame] | 94 | elif os.name == 'mac': |
Greg Ward | f585574 | 2000-09-21 01:23:35 +0000 | [diff] [blame] | 95 | 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 Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 99 | elements = pathname.split(":", 1) |
Greg Ward | f585574 | 2000-09-21 01:23:35 +0000 | [diff] [blame] | 100 | pathname = ":" + elements[1] |
| 101 | return os.path.join(new_root, pathname) |
Greg Ward | 67f75d4 | 2000-04-27 01:53:46 +0000 | [diff] [blame] | 102 | |
| 103 | else: |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 104 | raise DistutilsPlatformError("nothing known about " |
| 105 | "platform '%s'" % os.name) |
Greg Ward | 67f75d4 | 2000-04-27 01:53:46 +0000 | [diff] [blame] | 106 | |
Gregory P. Smith | e7e35ac | 2000-05-12 00:40:00 +0000 | [diff] [blame] | 107 | _environ_checked = 0 |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 108 | |
| 109 | def 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 Ward | b8b263b | 2000-09-30 18:40:42 +0000 | [diff] [blame] | 113 | 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 Ward | 1b4ede5 | 2000-03-22 00:22:44 +0000 | [diff] [blame] | 117 | """ |
Gregory P. Smith | e7e35ac | 2000-05-12 00:40:00 +0000 | [diff] [blame] | 118 | global _environ_checked |
| 119 | if _environ_checked: |
| 120 | return |
| 121 | |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 122 | if os.name == 'posix' and 'HOME' not in os.environ: |
Greg Ward | 1b4ede5 | 2000-03-22 00:22:44 +0000 | [diff] [blame] | 123 | import pwd |
Greg Ward | be86bde | 2000-09-26 01:56:15 +0000 | [diff] [blame] | 124 | os.environ['HOME'] = pwd.getpwuid(os.getuid())[5] |
Greg Ward | 1b4ede5 | 2000-03-22 00:22:44 +0000 | [diff] [blame] | 125 | |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 126 | if 'PLAT' not in os.environ: |
Tarek Ziadé | edacea3 | 2010-01-29 11:41:03 +0000 | [diff] [blame] | 127 | os.environ['PLAT'] = _sysconfig.get_platform() |
Greg Ward | 1b4ede5 | 2000-03-22 00:22:44 +0000 | [diff] [blame] | 128 | |
Gregory P. Smith | e7e35ac | 2000-05-12 00:40:00 +0000 | [diff] [blame] | 129 | _environ_checked = 1 |
| 130 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 131 | def subst_vars(s, local_vars): |
| 132 | """Perform shell/Perl-style variable substitution on 'string'. |
Greg Ward | 1b4ede5 | 2000-03-22 00:22:44 +0000 | [diff] [blame] | 133 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 134 | Every occurrence of '$' followed by a name is considered a variable, and |
Greg Ward | 4752769 | 2000-09-30 18:49:14 +0000 | [diff] [blame] | 135 | 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 Ward | b8b263b | 2000-09-30 18:40:42 +0000 | [diff] [blame] | 140 | """ |
Greg Ward | be86bde | 2000-09-26 01:56:15 +0000 | [diff] [blame] | 141 | check_environ() |
Greg Ward | 1b4ede5 | 2000-03-22 00:22:44 +0000 | [diff] [blame] | 142 | def _subst (match, local_vars=local_vars): |
| 143 | var_name = match.group(1) |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 144 | if var_name in local_vars: |
Greg Ward | be86bde | 2000-09-26 01:56:15 +0000 | [diff] [blame] | 145 | return str(local_vars[var_name]) |
Greg Ward | 1b4ede5 | 2000-03-22 00:22:44 +0000 | [diff] [blame] | 146 | else: |
| 147 | return os.environ[var_name] |
| 148 | |
Greg Ward | 4752769 | 2000-09-30 18:49:14 +0000 | [diff] [blame] | 149 | try: |
Jeremy Hylton | 5e2d076 | 2001-01-25 20:10:32 +0000 | [diff] [blame] | 150 | return re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 151 | except KeyError as var: |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 152 | raise ValueError("invalid variable '$%s'" % var) |
Greg Ward | 1b4ede5 | 2000-03-22 00:22:44 +0000 | [diff] [blame] | 153 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 154 | def grok_environment_error(exc, prefix="error: "): |
| 155 | """Generate a useful error message from an EnvironmentError. |
Greg Ward | 7c1a6d4 | 2000-03-29 02:48:40 +0000 | [diff] [blame] | 156 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 157 | This will generate an IOError or an OSError exception object. |
| 158 | Handles Python 1.5.1 and 1.5.2 styles, and |
Greg Ward | e905513 | 2000-06-17 02:16:46 +0000 | [diff] [blame] | 159 | 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 Ward | be86bde | 2000-09-26 01:56:15 +0000 | [diff] [blame] | 165 | if hasattr(exc, 'filename') and hasattr(exc, 'strerror'): |
Greg Ward | e905513 | 2000-06-17 02:16:46 +0000 | [diff] [blame] | 166 | 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 Brandl | 5dfe0de | 2008-01-06 21:41:49 +0000 | [diff] [blame] | 173 | error = prefix + str(exc.args[-1]) |
Greg Ward | e905513 | 2000-06-17 02:16:46 +0000 | [diff] [blame] | 174 | |
| 175 | return error |
Greg Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 176 | |
Greg Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 177 | # Needed by 'split_quoted()' |
Martin v. Löwis | 1c0f1f9 | 2004-03-25 14:58:19 +0000 | [diff] [blame] | 178 | _wordchars_re = _squote_re = _dquote_re = None |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 179 | |
Martin v. Löwis | 1c0f1f9 | 2004-03-25 14:58:19 +0000 | [diff] [blame] | 180 | def _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 Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 185 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 186 | def split_quoted(s): |
Greg Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 187 | """Split a string up according to Unix shell-like rules for quotes and |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 188 | backslashes. |
| 189 | |
| 190 | In short: words are delimited by spaces, as long as those |
Greg Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 191 | 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 Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 198 | # 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öwis | 1c0f1f9 | 2004-03-25 14:58:19 +0000 | [diff] [blame] | 201 | if _wordchars_re is None: _init_regex() |
Greg Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 202 | |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 203 | s = s.strip() |
Greg Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 204 | 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 Ward | 2b042de | 2000-08-08 14:38:13 +0000 | [diff] [blame] | 214 | if s[end] in string.whitespace: # unescaped, unquoted whitespace: now |
Greg Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 215 | words.append(s[:end]) # we definitely have a word delimiter |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 216 | s = s[end:].lstrip() |
Greg Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 217 | 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 Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 230 | raise RuntimeError("this can't happen (bad char '%c')" % s[end]) |
Greg Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 231 | |
| 232 | if m is None: |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 233 | raise ValueError("bad string (mismatched %s quotes?)" % s[end]) |
Greg Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 234 | |
| 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 Ward | 1c16ac3 | 2000-08-02 01:37:30 +0000 | [diff] [blame] | 245 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 246 | def execute(func, args, msg=None, verbose=0, dry_run=0): |
| 247 | """Perform some action that affects the outside world. |
Greg Ward | 1c16ac3 | 2000-08-02 01:37:30 +0000 | [diff] [blame] | 248 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 249 | 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 Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 251 | 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 Ward | 1c16ac3 | 2000-08-02 01:37:30 +0000 | [diff] [blame] | 255 | """ |
Greg Ward | 1c16ac3 | 2000-08-02 01:37:30 +0000 | [diff] [blame] | 256 | if msg is None: |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 257 | msg = "%s%r" % (func.__name__, args) |
Fred Drake | b94b849 | 2001-12-06 20:51:35 +0000 | [diff] [blame] | 258 | if msg[-2:] == ',)': # correct for singleton tuple |
Greg Ward | 1c16ac3 | 2000-08-02 01:37:30 +0000 | [diff] [blame] | 259 | msg = msg[0:-2] + ')' |
| 260 | |
Jeremy Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 261 | log.info(msg) |
Greg Ward | 1c16ac3 | 2000-08-02 01:37:30 +0000 | [diff] [blame] | 262 | if not dry_run: |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 263 | func(*args) |
Greg Ward | 1c16ac3 | 2000-08-02 01:37:30 +0000 | [diff] [blame] | 264 | |
Greg Ward | 817dc09 | 2000-09-25 01:25:06 +0000 | [diff] [blame] | 265 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 266 | def strtobool(val): |
Greg Ward | 817dc09 | 2000-09-25 01:25:06 +0000 | [diff] [blame] | 267 | """Convert a string representation of truth to true (1) or false (0). |
Tim Peters | 182b5ac | 2004-07-18 06:16:08 +0000 | [diff] [blame] | 268 | |
Greg Ward | 817dc09 | 2000-09-25 01:25:06 +0000 | [diff] [blame] | 269 | 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 Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 273 | val = val.lower() |
Greg Ward | 817dc09 | 2000-09-25 01:25:06 +0000 | [diff] [blame] | 274 | 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 Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 279 | raise ValueError("invalid truth value %r" % (val,)) |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 280 | |
| 281 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 282 | def byte_compile(py_files, optimize=0, force=0, prefix=None, base_dir=None, |
| 283 | verbose=1, dry_run=0, direct=None): |
Greg Ward | f217e21 | 2000-10-01 23:49:30 +0000 | [diff] [blame] | 284 | """Byte-compile a collection of Python source files to either .pyc |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 285 | 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 Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 289 | 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 Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 302 | If 'dry_run' is true, doesn't actually do anything that would |
| 303 | affect the filesystem. |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 304 | |
| 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é | 04fe7c0 | 2009-10-25 23:08:47 +0000 | [diff] [blame] | 313 | # 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 Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 317 | # 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é Lemburg | 0375079 | 2002-12-03 08:45:11 +0000 | [diff] [blame] | 333 | 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 Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 339 | log.info("writing byte-compilation script '%s'", script_name) |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 340 | if not dry_run: |
Marc-André Lemburg | 0375079 | 2002-12-03 08:45:11 +0000 | [diff] [blame] | 341 | if script_fd is not None: |
| 342 | script = os.fdopen(script_fd, "w") |
| 343 | else: |
| 344 | script = open(script_name, "w") |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 345 | |
| 346 | script.write("""\ |
| 347 | from distutils.util import byte_compile |
| 348 | files = [ |
| 349 | """) |
Greg Ward | 9216cfe | 2000-10-03 03:31:05 +0000 | [diff] [blame] | 350 | |
| 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 Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 365 | script.write(",\n".join(map(repr, py_files)) + "]\n") |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 366 | script.write(""" |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 367 | byte_compile(files, optimize=%r, force=%r, |
| 368 | prefix=%r, base_dir=%r, |
| 369 | verbose=%r, dry_run=0, |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 370 | direct=1) |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 371 | """ % (optimize, force, prefix, base_dir, verbose)) |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 372 | |
| 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 Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 380 | spawn(cmd, dry_run=dry_run) |
Greg Ward | 9216cfe | 2000-10-03 03:31:05 +0000 | [diff] [blame] | 381 | execute(os.remove, (script_name,), "removing %s" % script_name, |
Jeremy Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 382 | dry_run=dry_run) |
Fred Drake | b94b849 | 2001-12-06 20:51:35 +0000 | [diff] [blame] | 383 | |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 384 | # "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 Ward | f217e21 | 2000-10-01 23:49:30 +0000 | [diff] [blame] | 393 | # This lets us be lazy and not filter filenames in |
| 394 | # the "install_lib" command. |
| 395 | continue |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 396 | |
| 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é | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 404 | raise ValueError("invalid prefix: filename %r doesn't " |
| 405 | "start with %r" % (file, prefix)) |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 406 | 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 Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 413 | log.info("byte-compiling %s to %s", file, cfile_base) |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 414 | if not dry_run: |
| 415 | compile(file, cfile, dfile) |
| 416 | else: |
Jeremy Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 417 | log.debug("skipping byte-compilation of %s to %s", |
| 418 | file, cfile_base) |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 419 | |
Andrew M. Kuchling | df66df0 | 2001-03-22 03:03:41 +0000 | [diff] [blame] | 420 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 421 | def rfc822_escape(header): |
Andrew M. Kuchling | df66df0 | 2001-03-22 03:03:41 +0000 | [diff] [blame] | 422 | """Return a version of the string escaped for inclusion in an |
Andrew M. Kuchling | 88b0884 | 2001-03-23 17:30:26 +0000 | [diff] [blame] | 423 | RFC-822 header, by ensuring there are 8 spaces space after each newline. |
Andrew M. Kuchling | df66df0 | 2001-03-22 03:03:41 +0000 | [diff] [blame] | 424 | """ |
Tarek Ziadé | df872d4 | 2009-12-06 09:28:17 +0000 | [diff] [blame] | 425 | lines = header.split('\n') |
| 426 | sep = '\n' + 8 * ' ' |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 427 | return sep.join(lines) |
Martin v. Löwis | 6178db6 | 2008-12-01 04:38:52 +0000 | [diff] [blame] | 428 | |
Tarek Ziadé | f8926b2 | 2009-07-16 16:18:19 +0000 | [diff] [blame] | 429 | _RE_VERSION = re.compile(b'(\d+\.\d+(\.\d+)*)') |
| 430 | _MAC_OS_X_LD_VERSION = re.compile(b'^@\(#\)PROGRAM:ld PROJECT:ld64-((\d+)(\.\d+)*)') |
| 431 | |
| 432 | def _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 | |
| 439 | def _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 | |
| 468 | def 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öwis | 6178db6 | 2008-12-01 04:38:52 +0000 | [diff] [blame] | 479 | # 2to3 support |
| 480 | |
| 481 | def 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 Brandl | 6d4a9cf | 2009-03-31 00:34:54 +0000 | [diff] [blame] | 508 | def 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öwis | 6178db6 | 2008-12-01 04:38:52 +0000 | [diff] [blame] | 541 | class 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) |