Skip to content

Commit 646c71f

Browse files
authored
Merge pull request #3613 from JulienPalard/mdk-expand
expand: Give bytes to ast.parse to let it discover encoding cookie.
2 parents 401c184 + 80cce71 commit 646c71f

File tree

3 files changed

+17
-3
lines changed

3 files changed

+17
-3
lines changed

changelog.d/3613.misc.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fixed encoding errors in ``expand.StaticModule`` when system default encoding doesn't match expectations for source files.

setuptools/config/expand.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import importlib
2222
import io
2323
import os
24+
import pathlib
2425
import sys
2526
import warnings
2627
from glob import iglob
@@ -62,9 +63,7 @@ class StaticModule:
6263
"""Proxy to a module object that avoids executing arbitrary code."""
6364

6465
def __init__(self, name: str, spec: ModuleSpec):
65-
with open(spec.origin) as strm: # type: ignore
66-
src = strm.read()
67-
module = ast.parse(src)
66+
module = ast.parse(pathlib.Path(spec.origin).read_bytes())
6867
vars(self).update(locals())
6968
del self.self
7069

setuptools/tests/config/test_expand.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,20 @@ 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+
]
72+
)
73+
def test_read_attr_encoding_cookie(self, example, tmp_path):
74+
(tmp_path / "mod.py").write_bytes(example)
75+
assert expand.read_attr('mod.__version__', root_dir=tmp_path) == 'é'
76+
6377
def test_read_attr(self, tmp_path, monkeypatch):
6478
files = {
6579
"pkg/__init__.py": "",

0 commit comments

Comments
 (0)