Skip to content

Commit b1701e5

Browse files
authored
fix crash issue when using shadowfile with pretty #17853 (#17894)
- Fix crash issue when using <code>--pretty</code> with <code>--shadow-file</code> Example Scenario: <code>a.py</code> ```python b: bytes ``` <code>b.py</code> ```python a: int = "" b: bytes = 1 ``` <code>output</code> ``` $ mypy a.py --pretty --shadow-file a.py b.py a.py:1: error: Incompatible types in assignment (expression has type "str", variable has type "int") a: int = "" ^~ a.py:2: error: Incompatible types in assignment (expression has type "int", variable has type "bytes") b: bytes = 1 ^ ``` Fixes #17853
1 parent 54f4954 commit b1701e5

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

mypy/errors.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -922,9 +922,25 @@ 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+
# Find shadow file mapping and read source lines if a shadow file exists for the given path.
926+
# If shadow file mapping is not found, read source lines
927+
mapped_path = self.find_shadow_file_mapping(path)
928+
if mapped_path:
929+
source_lines = self.read_source(mapped_path)
930+
else:
931+
source_lines = self.read_source(path)
926932
return self.format_messages(error_tuples, source_lines)
927933

934+
def find_shadow_file_mapping(self, path: str) -> str | None:
935+
"""Return the shadow file path for a given source file path or None."""
936+
if self.options.shadow_file is None:
937+
return None
938+
939+
for i in self.options.shadow_file:
940+
if i[0] == path:
941+
return i[1]
942+
return None
943+
928944
def new_messages(self) -> list[str]:
929945
"""Return a string list of new error messages.
930946

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)