Skip to content

Commit 2824cb5

Browse files
committed
Issue #15343: A lot more than just unicode decoding can go wrong when retrieving a source file
1 parent 8ecf504 commit 2824cb5

File tree

3 files changed

+2135
-2107
lines changed

3 files changed

+2135
-2107
lines changed

Lib/importlib/_bootstrap.py

+13-4
Original file line numberDiff line numberDiff line change
@@ -845,12 +845,21 @@ def get_source(self, fullname):
845845
path = self.get_filename(fullname)
846846
try:
847847
source_bytes = self.get_data(path)
848-
except IOError:
848+
except IOError as exc:
849849
raise ImportError("source not available through get_data()",
850-
name=fullname)
851-
encoding = tokenize.detect_encoding(_io.BytesIO(source_bytes).readline)
850+
name=fullname) from exc
851+
readsource = _io.BytesIO(source_bytes).readline
852+
try:
853+
encoding = tokenize.detect_encoding(readsource)
854+
except SyntaxError as exc:
855+
raise ImportError("Failed to detect encoding",
856+
name=fullname) from exc
852857
newline_decoder = _io.IncrementalNewlineDecoder(None, True)
853-
return newline_decoder.decode(source_bytes.decode(encoding[0]))
858+
try:
859+
return newline_decoder.decode(source_bytes.decode(encoding[0]))
860+
except UnicodeDecodeError as exc:
861+
raise ImportError("Failed to decode source file",
862+
name=fullname) from exc
854863

855864
def get_code(self, fullname):
856865
"""Concrete implementation of InspectLoader.get_code.

Lib/pydoc.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2048,7 +2048,7 @@ def run(self, callback, key=None, completer=None, onerror=None):
20482048
if hasattr(loader, 'get_source'):
20492049
try:
20502050
source = loader.get_source(modname)
2051-
except UnicodeDecodeError:
2051+
except Exception:
20522052
if onerror:
20532053
onerror(modname)
20542054
continue

0 commit comments

Comments
 (0)