Skip to content

Commit 06e06cb

Browse files
committed
fix crash issue when using shadowfile with pretty #17853
1 parent 94c49a8 commit 06e06cb

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

mypy/errors.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -922,9 +922,29 @@ def file_messages(self, path: str, formatter: ErrorFormatter | None = None) -> l
922922
self.flushed_files.add(path)
923923
source_lines = None
924924
if self.options.pretty and self.read_source:
925-
source_lines = self.read_source(path)
925+
"""
926+
Find shadow file mapping and read source lines if a
927+
shadow file exists for the given path.
928+
929+
If shadow file mapping is not found, read source lines
930+
"""
931+
mapped_path = self.find_shadow_file_mapping(path)
932+
if mapped_path:
933+
source_lines = self.read_source(mapped_path)
934+
else:
935+
source_lines = self.read_source(path)
926936
return self.format_messages(error_tuples, source_lines)
927937

938+
def find_shadow_file_mapping(self, path: str) -> str | None:
939+
"""Return the shadow file path for a given source file path or None."""
940+
if self.options.shadow_file is None:
941+
return None
942+
943+
for i in self.options.shadow_file:
944+
if i[0] == path:
945+
return i[1]
946+
return None
947+
928948
def new_messages(self) -> list[str]:
929949
"""Return a string list of new error messages.
930950

test-data/unit/cmdline.test

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -914,6 +914,23 @@ s4.py:2: error: Incompatible return value type (got "int", expected "str")
914914
s3.py:2: error: Incompatible return value type (got "List[int]", expected "int")
915915
s1.py:2: error: Incompatible return value type (got "int", expected "str")
916916

917+
[case testShadowFileWithPretty]
918+
# cmd: mypy a.py --pretty --shadow-file a.py b.py
919+
[file a.py]
920+
b: bytes
921+
[file b.py]
922+
a: int = ""
923+
b: bytes = 1
924+
[out]
925+
a.py:1: error: Incompatible types in assignment (expression has type "str",
926+
variable has type "int")
927+
a: int = ""
928+
^~
929+
a.py:2: error: Incompatible types in assignment (expression has type "int",
930+
variable has type "bytes")
931+
b: bytes = 1
932+
^
933+
917934
[case testConfigWarnUnusedSection1]
918935
# cmd: mypy foo.py quux.py spam/eggs.py
919936
[file mypy.ini]

0 commit comments

Comments
 (0)