From 22bd3a657353c907ba4803a855f5c793aaeaa713 Mon Sep 17 00:00:00 2001 From: SerageLdin Date: Tue, 24 Nov 2026 15:12:05 +0300 Subject: [PATCH] Only scan line 2 for encoding declaration after blank or comment lines --- babel/util.py | 20 ++++++-------------- tests/messages/test_extract_python.py | 6 ++++++ tests/test_util.py | 8 ++++++++ 3 files changed, 20 insertions(+), 14 deletions(-) diff --git a/babel/util.py b/babel/util.py index a2bf728cc..3cb7a6c67 100644 --- a/babel/util.py +++ b/babel/util.py @@ -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. @@ -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: diff --git a/tests/messages/test_extract_python.py b/tests/messages/test_extract_python.py index be1cf970f..385ae6072 100644 --- a/tests/messages/test_extract_python.py +++ b/tests/messages/test_extract_python.py @@ -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') diff --git a/tests/test_util.py b/tests/test_util.py index f51626e25..24b1f11fd 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -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,