Skip to content

Commit 8b20091

Browse files
committed
Read files using UTF-8 in pkg_resources, with fallback to locale
1 parent 9aa9f22 commit 8b20091

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

pkg_resources/__init__.py

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1524,8 +1524,7 @@ def run_script(self, script_name, namespace):
15241524
script_filename = self._fn(self.egg_info, script)
15251525
namespace['__file__'] = script_filename
15261526
if os.path.exists(script_filename):
1527-
with open(script_filename) as fid:
1528-
source = fid.read()
1527+
source = _read_utf8_with_fallback(script_filename)
15291528
code = compile(source, script_filename, 'exec')
15301529
exec(code, namespace, namespace)
15311530
else:
@@ -2175,11 +2174,10 @@ def non_empty_lines(path):
21752174
"""
21762175
Yield non-empty lines from file at path
21772176
"""
2178-
with open(path) as f:
2179-
for line in f:
2180-
line = line.strip()
2181-
if line:
2182-
yield line
2177+
for line in _read_utf8_with_fallback(path).splitlines():
2178+
line = line.strip()
2179+
if line:
2180+
yield line
21832181

21842182

21852183
def resolve_egg_link(path):
@@ -3323,3 +3321,16 @@ def _initialize_master_working_set():
33233321
# match order
33243322
list(map(working_set.add_entry, sys.path))
33253323
globals().update(locals())
3324+
3325+
3326+
# ---- Ported from ``setuptools`` to avoid introducing dependencies ----
3327+
LOCALE_ENCODING = "locale" if sys.version_info >= (3, 10) else None
3328+
3329+
3330+
def _read_utf8_with_fallback(file: str, fallback_encoding=LOCALE_ENCODING) -> str:
3331+
try:
3332+
with open(file, "r", encoding="utf-8") as f:
3333+
return f.read()
3334+
except UnicodeDecodeError: # pragma: no cover
3335+
with open(file, "r", encoding=fallback_encoding) as f:
3336+
return f.read()

0 commit comments

Comments
 (0)