Skip to content

Commit

Permalink
Parse multi-line __future__ imports better (python-babel#519)
Browse files Browse the repository at this point in the history
  • Loading branch information
akx authored Aug 21, 2017
1 parent 1da04fd commit 231d337
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
17 changes: 15 additions & 2 deletions babel/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,23 @@ def parse_future_flags(fp, encoding='latin-1'):
flags = 0
try:
body = fp.read().decode(encoding)

# Fix up the source to be (hopefully) parsable by regexpen.
# This will likely do untoward things if the source code itself is broken.

# (1) Fix `import (\n...` to be `import (...`.
body = re.sub(r'import\s*\([\r\n]+', 'import (', body)
# (2) Join line-ending commas with the next line.
body = re.sub(r',\s*[\r\n]+', ', ', body)
# (3) Remove backslash line continuations.
body = re.sub(r'\\\s*[\r\n]+', ' ', body)

for m in PYTHON_FUTURE_IMPORT_re.finditer(body):
names = [x.strip() for x in m.group(1).split(',')]
names = [x.strip().strip('()') for x in m.group(1).split(',')]
for name in names:
flags |= getattr(__future__, name).compiler_flag
feature = getattr(__future__, name, None)
if feature:
flags |= feature.compiler_flag
finally:
fp.seek(pos)
return flags
Expand Down
34 changes: 34 additions & 0 deletions tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@

import unittest

import pytest

from babel import util
from babel._compat import BytesIO
from babel.util import parse_future_flags


def test_distinct():
Expand Down Expand Up @@ -69,3 +72,34 @@ def test_parse_encoding_undefined():

def test_parse_encoding_non_ascii():
assert parse_encoding(u'K\xf6ln') is None


@pytest.mark.parametrize('source, result', [
('''
from __future__ import print_function,
division, with_statement,
unicode_literals
''', 0x10000 | 0x2000 | 0x8000 | 0x20000),
('''
from __future__ import print_function, division
print('hello')
''', 0x10000 | 0x2000),
('''
from __future__ import print_function, division, unknown,,,,,
print 'hello'
''', 0x10000 | 0x2000),
('''
from __future__ import (
print_function,
division)
''', 0x10000 | 0x2000),
('''
from __future__ import \\
print_function, \\
division
''', 0x10000 | 0x2000),
])
def test_parse_future(source, result):
fp = BytesIO(source.encode('latin-1'))
flags = parse_future_flags(fp)
assert flags == result

0 comments on commit 231d337

Please sign in to comment.