Skip to content
Open
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
3 changes: 2 additions & 1 deletion babel/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,8 @@ def parse_encoding(fp: IO[bytes]) -> str | None:
if has_bom:
if m:
magic_comment_encoding = m.group(1).decode('latin-1')
if magic_comment_encoding != 'utf-8':
normalized_encoding = magic_comment_encoding.lower().replace('_', '-')
if normalized_encoding != 'utf-8' and not normalized_encoding.startswith('utf-8-'):
raise SyntaxError(f"encoding problem: {magic_comment_encoding} with BOM")
return 'utf-8'
elif m:
Expand Down
21 changes: 21 additions & 0 deletions tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import __future__

import codecs
from io import BytesIO

import pytest
Expand Down Expand Up @@ -73,6 +74,26 @@ def test_parse_encoding_non_ascii():
assert parse_encoding('K\xf6ln') is None


@pytest.mark.parametrize('encoding', ['utf-8', 'UTF-8', 'utf_8', 'UTF_8', 'utf-8-sig'])
@pytest.mark.parametrize('prefix', [b'', b'# source file\n'])
def test_parse_encoding_bom(encoding, prefix):
source = codecs.BOM_UTF8 + prefix + f'# coding: {encoding}\n'.encode('ascii')
compile(source, '<test>', 'exec')
stream = BytesIO(source)
stream.seek(3)
assert util.parse_encoding(stream) == 'utf-8'
assert stream.tell() == 3


@pytest.mark.parametrize('encoding', ['latin-1', 'utf8', 'cp65001'])
def test_parse_encoding_bom_incompatible(encoding):
stream = BytesIO(codecs.BOM_UTF8 + f'# coding: {encoding}\n'.encode('ascii'))
stream.seek(3)
with pytest.raises(SyntaxError, match=f'encoding problem: {encoding} with BOM'):
util.parse_encoding(stream)
assert stream.tell() == 3


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