Skip to content

Commit 7e997ac

Browse files
committed
expand: Give bytes to ast.parse to let it discover encoding cookie.
1 parent badd706 commit 7e997ac

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

setuptools/config/expand.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ class StaticModule:
6262
"""Proxy to a module object that avoids executing arbitrary code."""
6363

6464
def __init__(self, name: str, spec: ModuleSpec):
65-
with open(spec.origin) as strm: # type: ignore
65+
with open(spec.origin, mode='rb') as strm: # type: ignore
6666
src = strm.read()
6767
module = ast.parse(src)
6868
vars(self).update(locals())

setuptools/tests/config/test_expand.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,22 @@ def test_read_files(tmp_path, monkeypatch):
6060

6161

6262
class TestReadAttr:
63+
@pytest.mark.parametrize(
64+
"example",
65+
[
66+
# No cookie means UTF-8:
67+
b"__version__ = '\xc3\xa9'\nraise SystemExit(1)\n",
68+
# If a cookie is present, honor it:
69+
b"# -*- coding: utf-8 -*-\n__version__ = '\xc3\xa9'\nraise SystemExit(1)\n",
70+
b"# -*- coding: latin1 -*-\n__version__ = '\xe9'\nraise SystemExit(1)\n",
71+
b"\xff\xfe\x00\x00# -*- coding: utf-32 -*-\n__version__ = '\xe9\x00\x00\x00'\nraise SystemExit(1)\n",
72+
]
73+
)
74+
def test_read_attr_encoding_cookie(self, example, tmp_path):
75+
(tmp_path / "pkg" / "__init__.py").write_text("")
76+
(tmp_path / "pkg" / "mod.py").write_bytes(example)
77+
assert expand.read_attr('pkg.sub.__version__', root_dir=tmp_path) == 'é'
78+
6379
def test_read_attr(self, tmp_path, monkeypatch):
6480
files = {
6581
"pkg/__init__.py": "",

0 commit comments

Comments
 (0)