| 1 | import re |
| 2 | |
| 3 | ASCII_IS_DEFAULT_ENCODING = False |
| 4 | |
| 5 | cookie_re = re.compile(r"^[ \t\f]*#.*coding[:=][ \t]*[-\w.]+") |
| 6 | BOM_UTF8 = '\xef\xbb\xbf' |
| 7 | |
| 8 | def _prepare_source(fn): |
| 9 | """Read the source code for re-writing.""" |
| 10 | try: |
| 11 | stat = fn.stat() |
| 12 | source = fn.read("rb") |
| 13 | except EnvironmentError: |
| 14 | return None, None |
| 15 | if ASCII_IS_DEFAULT_ENCODING: |
| 16 | # ASCII is the default encoding in Python 2. Without a coding |
| 17 | # declaration, Python 2 will complain about any bytes in the file |
| 18 | # outside the ASCII range. Sadly, this behavior does not extend to |
| 19 | # compile() or ast.parse(), which prefer to interpret the bytes as |
| 20 | # latin-1. (At least they properly handle explicit coding cookies.) To |
| 21 | # preserve this error behavior, we could force ast.parse() to use ASCII |
| 22 | # as the encoding by inserting a coding cookie. Unfortunately, that |
| 23 | # messes up line numbers. Thus, we have to check ourselves if anything |
| 24 | # is outside the ASCII range in the case no encoding is explicitly |
| 25 | # declared. For more context, see issue #269. Yay for Python 3 which |
| 26 | # gets this right. |
| 27 | end1 = source.find("\n") |
| 28 | end2 = source.find("\n", end1 + 1) |
| 29 | if (not source.startswith(BOM_UTF8) and |
| 30 | cookie_re.match(source[0:end1]) is None and |
| 31 | cookie_re.match(source[end1 + 1:end2]) is None): |
| 32 | try: |
| 33 | source.decode("ascii") |
| 34 | except UnicodeDecodeError: |
| 35 | # Let it fail in real import. |
| 36 | return None, None |
| 37 | # On Python versions which are not 2.7 and less than or equal to 3.1, the |
| 38 | # parser expects *nix newlines. |
| 39 | return stat, source |