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 | else: |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 95 | raise DistutilsPlatformError("nothing known about " |
| 96 | "platform '%s'" % os.name) |
Greg Ward | 67f75d4 | 2000-04-27 01:53:46 +0000 | [diff] [blame] | 97 | |
Gregory P. Smith | e7e35ac | 2000-05-12 00:40:00 +0000 | [diff] [blame] | 98 | _environ_checked = 0 |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 99 | |
| 100 | def 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 Ward | b8b263b | 2000-09-30 18:40:42 +0000 | [diff] [blame] | 104 | 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 Ward | 1b4ede5 | 2000-03-22 00:22:44 +0000 | [diff] [blame] | 108 | """ |
Gregory P. Smith | e7e35ac | 2000-05-12 00:40:00 +0000 | [diff] [blame] | 109 | global _environ_checked |
| 110 | if _environ_checked: |
| 111 | return |
| 112 | |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 113 | if os.name == 'posix' and 'HOME' not in os.environ: |
Greg Ward | 1b4ede5 | 2000-03-22 00:22:44 +0000 | [diff] [blame] | 114 | import pwd |
Greg Ward | be86bde | 2000-09-26 01:56:15 +0000 | [diff] [blame] | 115 | os.environ['HOME'] = pwd.getpwuid(os.getuid())[5] |
Greg Ward | 1b4ede5 | 2000-03-22 00:22:44 +0000 | [diff] [blame] | 116 | |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 117 | if 'PLAT' not in os.environ: |
Tarek Ziadé | edacea3 | 2010-01-29 11:41:03 +0000 | [diff] [blame] | 118 | os.environ['PLAT'] = _sysconfig.get_platform() |
Greg Ward | 1b4ede5 | 2000-03-22 00:22:44 +0000 | [diff] [blame] | 119 | |
Gregory P. Smith | e7e35ac | 2000-05-12 00:40:00 +0000 | [diff] [blame] | 120 | _environ_checked = 1 |
| 121 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 122 | def subst_vars(s, local_vars): |
| 123 | """Perform shell/Perl-style variable substitution on 'string'. |
Greg Ward | 1b4ede5 | 2000-03-22 00:22:44 +0000 | [diff] [blame] | 124 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 125 | Every occurrence of '$' followed by a name is considered a variable, and |
Greg Ward | 4752769 | 2000-09-30 18:49:14 +0000 | [diff] [blame] | 126 | 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 Ward | b8b263b | 2000-09-30 18:40:42 +0000 | [diff] [blame] | 131 | """ |
Greg Ward | be86bde | 2000-09-26 01:56:15 +0000 | [diff] [blame] | 132 | check_environ() |
Greg Ward | 1b4ede5 | 2000-03-22 00:22:44 +0000 | [diff] [blame] | 133 | def _subst (match, local_vars=local_vars): |
| 134 | var_name = match.group(1) |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 135 | if var_name in local_vars: |
Greg Ward | be86bde | 2000-09-26 01:56:15 +0000 | [diff] [blame] | 136 | return str(local_vars[var_name]) |
Greg Ward | 1b4ede5 | 2000-03-22 00:22:44 +0000 | [diff] [blame] | 137 | else: |
| 138 | return os.environ[var_name] |
| 139 | |
Greg Ward | 4752769 | 2000-09-30 18:49:14 +0000 | [diff] [blame] | 140 | try: |
Jeremy Hylton | 5e2d076 | 2001-01-25 20:10:32 +0000 | [diff] [blame] | 141 | 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] | 142 | except KeyError as var: |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 143 | raise ValueError("invalid variable '$%s'" % var) |
Greg Ward | 1b4ede5 | 2000-03-22 00:22:44 +0000 | [diff] [blame] | 144 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 145 | def grok_environment_error(exc, prefix="error: "): |
| 146 | """Generate a useful error message from an EnvironmentError. |
Greg Ward | 7c1a6d4 | 2000-03-29 02:48:40 +0000 | [diff] [blame] | 147 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 148 | This will generate an IOError or an OSError exception object. |
| 149 | Handles Python 1.5.1 and 1.5.2 styles, and |
Greg Ward | e905513 | 2000-06-17 02:16:46 +0000 | [diff] [blame] | 150 | 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 Ward | be86bde | 2000-09-26 01:56:15 +0000 | [diff] [blame] | 156 | if hasattr(exc, 'filename') and hasattr(exc, 'strerror'): |
Greg Ward | e905513 | 2000-06-17 02:16:46 +0000 | [diff] [blame] | 157 | 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 Brandl | 5dfe0de | 2008-01-06 21:41:49 +0000 | [diff] [blame] | 164 | error = prefix + str(exc.args[-1]) |
Greg Ward | e905513 | 2000-06-17 02:16:46 +0000 | [diff] [blame] | 165 | |
| 166 | return error |
Greg Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 167 | |
Greg Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 168 | # Needed by 'split_quoted()' |
Martin v. Löwis | 1c0f1f9 | 2004-03-25 14:58:19 +0000 | [diff] [blame] | 169 | _wordchars_re = _squote_re = _dquote_re = None |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 170 | |
Martin v. Löwis | 1c0f1f9 | 2004-03-25 14:58:19 +0000 | [diff] [blame] | 171 | def _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 Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 176 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 177 | def split_quoted(s): |
Greg Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 178 | """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] | 179 | backslashes. |
| 180 | |
| 181 | In short: words are delimited by spaces, as long as those |
Greg Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 182 | 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 Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 189 | # 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öwis | 1c0f1f9 | 2004-03-25 14:58:19 +0000 | [diff] [blame] | 192 | if _wordchars_re is None: _init_regex() |
Greg Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 193 | |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 194 | s = s.strip() |
Greg Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 195 | 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 Ward | 2b042de | 2000-08-08 14:38:13 +0000 | [diff] [blame] | 205 | if s[end] in string.whitespace: # unescaped, unquoted whitespace: now |
Greg Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 206 | words.append(s[:end]) # we definitely have a word delimiter |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 207 | s = s[end:].lstrip() |
Greg Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 208 | 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 Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 221 | raise RuntimeError("this can't happen (bad char '%c')" % s[end]) |
Greg Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 222 | |
| 223 | if m is None: |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 224 | raise ValueError("bad string (mismatched %s quotes?)" % s[end]) |
Greg Ward | 6a2a3db | 2000-06-24 20:40:02 +0000 | [diff] [blame] | 225 | |
| 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 Ward | 1c16ac3 | 2000-08-02 01:37:30 +0000 | [diff] [blame] | 236 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 237 | def execute(func, args, msg=None, verbose=0, dry_run=0): |
| 238 | """Perform some action that affects the outside world. |
Greg Ward | 1c16ac3 | 2000-08-02 01:37:30 +0000 | [diff] [blame] | 239 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 240 | 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 Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 242 | 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 Ward | 1c16ac3 | 2000-08-02 01:37:30 +0000 | [diff] [blame] | 246 | """ |
Greg Ward | 1c16ac3 | 2000-08-02 01:37:30 +0000 | [diff] [blame] | 247 | if msg is None: |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 248 | msg = "%s%r" % (func.__name__, args) |
Fred Drake | b94b849 | 2001-12-06 20:51:35 +0000 | [diff] [blame] | 249 | if msg[-2:] == ',)': # correct for singleton tuple |
Greg Ward | 1c16ac3 | 2000-08-02 01:37:30 +0000 | [diff] [blame] | 250 | msg = msg[0:-2] + ')' |
| 251 | |
Jeremy Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 252 | log.info(msg) |
Greg Ward | 1c16ac3 | 2000-08-02 01:37:30 +0000 | [diff] [blame] | 253 | if not dry_run: |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 254 | func(*args) |
Greg Ward | 1c16ac3 | 2000-08-02 01:37:30 +0000 | [diff] [blame] | 255 | |
Greg Ward | 817dc09 | 2000-09-25 01:25:06 +0000 | [diff] [blame] | 256 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 257 | def strtobool(val): |
Greg Ward | 817dc09 | 2000-09-25 01:25:06 +0000 | [diff] [blame] | 258 | """Convert a string representation of truth to true (1) or false (0). |
Tim Peters | 182b5ac | 2004-07-18 06:16:08 +0000 | [diff] [blame] | 259 | |
Greg Ward | 817dc09 | 2000-09-25 01:25:06 +0000 | [diff] [blame] | 260 | 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 Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 264 | val = val.lower() |
Greg Ward | 817dc09 | 2000-09-25 01:25:06 +0000 | [diff] [blame] | 265 | 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 Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 270 | raise ValueError("invalid truth value %r" % (val,)) |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 271 | |
| 272 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 273 | def byte_compile(py_files, optimize=0, force=0, prefix=None, base_dir=None, |
| 274 | verbose=1, dry_run=0, direct=None): |
Greg Ward | f217e21 | 2000-10-01 23:49:30 +0000 | [diff] [blame] | 275 | """Byte-compile a collection of Python source files to either .pyc |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 276 | 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 Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 280 | 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 Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 293 | If 'dry_run' is true, doesn't actually do anything that would |
| 294 | affect the filesystem. |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 295 | |
| 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é | 04fe7c0 | 2009-10-25 23:08:47 +0000 | [diff] [blame] | 304 | # 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 Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 308 | # 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é Lemburg | 0375079 | 2002-12-03 08:45:11 +0000 | [diff] [blame] | 324 | 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 Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 330 | log.info("writing byte-compilation script '%s'", script_name) |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 331 | if not dry_run: |
Marc-André Lemburg | 0375079 | 2002-12-03 08:45:11 +0000 | [diff] [blame] | 332 | if script_fd is not None: |
| 333 | script = os.fdopen(script_fd, "w") |
| 334 | else: |
| 335 | script = open(script_name, "w") |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 336 | |
| 337 | script.write("""\ |
| 338 | from distutils.util import byte_compile |
| 339 | files = [ |
| 340 | """) |
Greg Ward | 9216cfe | 2000-10-03 03:31:05 +0000 | [diff] [blame] | 341 | |
| 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 Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 356 | script.write(",\n".join(map(repr, py_files)) + "]\n") |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 357 | script.write(""" |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 358 | byte_compile(files, optimize=%r, force=%r, |
| 359 | prefix=%r, base_dir=%r, |
| 360 | verbose=%r, dry_run=0, |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 361 | direct=1) |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 362 | """ % (optimize, force, prefix, base_dir, verbose)) |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 363 | |
| 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 Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 371 | spawn(cmd, dry_run=dry_run) |
Greg Ward | 9216cfe | 2000-10-03 03:31:05 +0000 | [diff] [blame] | 372 | execute(os.remove, (script_name,), "removing %s" % script_name, |
Jeremy Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 373 | dry_run=dry_run) |
Fred Drake | b94b849 | 2001-12-06 20:51:35 +0000 | [diff] [blame] | 374 | |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 375 | # "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 Ward | f217e21 | 2000-10-01 23:49:30 +0000 | [diff] [blame] | 384 | # This lets us be lazy and not filter filenames in |
| 385 | # the "install_lib" command. |
| 386 | continue |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 387 | |
| 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é | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 395 | raise ValueError("invalid prefix: filename %r doesn't " |
| 396 | "start with %r" % (file, prefix)) |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 397 | 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 Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 404 | log.info("byte-compiling %s to %s", file, cfile_base) |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 405 | if not dry_run: |
| 406 | compile(file, cfile, dfile) |
| 407 | else: |
Jeremy Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 408 | log.debug("skipping byte-compilation of %s to %s", |
| 409 | file, cfile_base) |
Greg Ward | 1297b5c | 2000-09-30 20:37:56 +0000 | [diff] [blame] | 410 | |
Andrew M. Kuchling | df66df0 | 2001-03-22 03:03:41 +0000 | [diff] [blame] | 411 | |
Tarek Ziadé | 905a257 | 2009-07-02 14:25:23 +0000 | [diff] [blame] | 412 | def rfc822_escape(header): |
Andrew M. Kuchling | df66df0 | 2001-03-22 03:03:41 +0000 | [diff] [blame] | 413 | """Return a version of the string escaped for inclusion in an |
Andrew M. Kuchling | 88b0884 | 2001-03-23 17:30:26 +0000 | [diff] [blame] | 414 | 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] | 415 | """ |
Tarek Ziadé | df872d4 | 2009-12-06 09:28:17 +0000 | [diff] [blame] | 416 | lines = header.split('\n') |
| 417 | sep = '\n' + 8 * ' ' |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 418 | return sep.join(lines) |
Martin v. Löwis | 6178db6 | 2008-12-01 04:38:52 +0000 | [diff] [blame] | 419 | |
Tarek Ziadé | f8926b2 | 2009-07-16 16:18:19 +0000 | [diff] [blame] | 420 | _RE_VERSION = re.compile(b'(\d+\.\d+(\.\d+)*)') |
| 421 | _MAC_OS_X_LD_VERSION = re.compile(b'^@\(#\)PROGRAM:ld PROJECT:ld64-((\d+)(\.\d+)*)') |
| 422 | |
| 423 | def _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 | |
| 430 | def _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 | |
| 459 | def 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öwis | 6178db6 | 2008-12-01 04:38:52 +0000 | [diff] [blame] | 470 | # 2to3 support |
| 471 | |
| 472 | def 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 Brandl | 6d4a9cf | 2009-03-31 00:34:54 +0000 | [diff] [blame] | 499 | def 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öwis | 6178db6 | 2008-12-01 04:38:52 +0000 | [diff] [blame] | 532 | class 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) |