Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 6 additions & 14 deletions babel/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ def distinct(iterable: Iterable[_T]) -> Generator[_T, None, None]:
flags=re.VERBOSE,
)

# Regexp to match a blank or comment-only first line (PEP 263)
PYTHON_BLANK_LINE_re = re.compile(rb'^[ \t\f]*(?:[#\r\n]|$)')


def parse_encoding(fp: IO[bytes]) -> str | None:
"""Deduce the encoding of a source file from magic comment.
Expand All @@ -73,20 +76,9 @@ def parse_encoding(fp: IO[bytes]) -> str | None:
line1 = line1[len(codecs.BOM_UTF8) :]

m = PYTHON_MAGIC_COMMENT_re.match(line1)
if not m:
try:
import ast

ast.parse(line1.decode('latin-1'))
except (ImportError, SyntaxError, UnicodeEncodeError):
# Either it's a real syntax error, in which case the source is
# not valid python source, or line2 is a continuation of line1,
# in which case we don't want to scan line2 for a magic
# comment.
pass
else:
line2 = fp.readline()
m = PYTHON_MAGIC_COMMENT_re.match(line2)
if not m and PYTHON_BLANK_LINE_re.match(line1):
line2 = fp.readline()
m = PYTHON_MAGIC_COMMENT_re.match(line2)

if has_bom:
if m:
Expand Down
6 changes: 6 additions & 0 deletions tests/messages/test_extract_python.py
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,12 @@ def test_utf8_bom_with_latin_magic_comment_fails():
list(extract.extract_python(buf, ('_',), ['NOTE:'], {}))


def test_second_line_encoding_comment_after_code_is_ignored():
buf = BytesIO('x = 1\n# coding: latin-1\n_("café")\n'.encode('utf-8'))
messages = list(extract.extract('python', buf))
assert messages == [(3, 'café', [], None)]


def test_utf8_raw_strings_match_unicode_strings():
buf = BytesIO(codecs.BOM_UTF8 + """
msg = _('Bonjour à tous')
Expand Down
8 changes: 8 additions & 0 deletions tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,14 @@ def test_parse_encoding_non_ascii():
assert parse_encoding('K\xf6ln') is None


def test_parse_encoding_second_line_rules():
assert parse_encoding('#!/usr/bin/env python\n# coding: latin-1\n') == 'latin-1'
assert parse_encoding('\n# coding: latin-1\n') == 'latin-1'
assert parse_encoding(' \t\n# coding: latin-1\n') == 'latin-1'
assert parse_encoding('x = 1\n# coding: latin-1\n') is None
assert parse_encoding('"""docstring"""\n# coding: latin-1\n') is None


@pytest.mark.parametrize(('source', 'result'), [
('''
from __future__ import print_function,
Expand Down