Skip to content

Commit

Permalink
fix crash issue when using shadowfile with pretty #17853 (#17894)
Browse files Browse the repository at this point in the history
- 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
  • Loading branch information
changhoetyng authored Oct 11, 2024
1 parent 54f4954 commit b1701e5
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
18 changes: 17 additions & 1 deletion mypy/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -922,9 +922,25 @@ def file_messages(self, path: str, formatter: ErrorFormatter | None = None) -> l
self.flushed_files.add(path)
source_lines = None
if self.options.pretty and self.read_source:
source_lines = self.read_source(path)
# Find shadow file mapping and read source lines if a shadow file exists for the given path.
# If shadow file mapping is not found, read source lines
mapped_path = self.find_shadow_file_mapping(path)
if mapped_path:
source_lines = self.read_source(mapped_path)
else:
source_lines = self.read_source(path)
return self.format_messages(error_tuples, source_lines)

def find_shadow_file_mapping(self, path: str) -> str | None:
"""Return the shadow file path for a given source file path or None."""
if self.options.shadow_file is None:
return None

for i in self.options.shadow_file:
if i[0] == path:
return i[1]
return None

def new_messages(self) -> list[str]:
"""Return a string list of new error messages.
Expand Down
17 changes: 17 additions & 0 deletions test-data/unit/cmdline.test
Original file line number Diff line number Diff line change
Expand Up @@ -914,6 +914,23 @@ s4.py:2: error: Incompatible return value type (got "int", expected "str")
s3.py:2: error: Incompatible return value type (got "List[int]", expected "int")
s1.py:2: error: Incompatible return value type (got "int", expected "str")

[case testShadowFileWithPretty]
# cmd: mypy a.py --pretty --shadow-file a.py b.py
[file a.py]
b: bytes
[file b.py]
a: int = ""
b: bytes = 1
[out]
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
^

[case testConfigWarnUnusedSection1]
# cmd: mypy foo.py quux.py spam/eggs.py
[file mypy.ini]
Expand Down

0 comments on commit b1701e5

Please sign in to comment.