You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Add Error format support, and JSON output option (#11396)
### Description
Resolves#10816
The changes this PR makes are relatively small.
It currently:
- Adds an `--output` option to mypy CLI
- Adds a `ErrorFormatter` abstract base class, which can be subclassed
to create new output formats
- Adds a `MypyError` class that represents the external format of a mypy
error.
- Adds a check for `--output` being `'json'`, in which case the
`JSONFormatter` is used to produce the reported output.
#### Demo:
```console
$ mypy mytest.py
mytest.py:2: error: Incompatible types in assignment (expression has type "str", variable has type "int")
mytest.py:3: error: Name "z" is not defined
Found 2 errors in 1 file (checked 1 source file)
$ mypy mytest.py --output=json
{"file": "mytest.py", "line": 2, "column": 4, "severity": "error", "message": "Incompatible types in assignment (expression has type \"str\", variable has type \"int\")", "code": "assignment"}
{"file": "mytest.py", "line": 3, "column": 4, "severity": "error", "message": "Name \"z\" is not defined", "code": "name-defined"}
```
---
A few notes regarding the changes:
- I chose to re-use the intermediate `ErrorTuple`s created during error
reporting, instead of using the more general `ErrorInfo` class, because
a lot of machinery already exists in mypy for sorting and removing
duplicate error reports, which produces `ErrorTuple`s at the end. The
error sorting and duplicate removal logic could perhaps be separated out
from the rest of the code, to be able to use `ErrorInfo` objects more
freely.
- `ErrorFormatter` doesn't really need to be an abstract class, but I
think it would be better this way. If there's a different method that
would be preferred, I'd be happy to know.
- The `--output` CLI option is, most probably, not added in the correct
place. Any help in how to do it properly would be appreciated, the mypy
option parsing code seems very complex.
- The ability to add custom output formats can be simply added by
subclassing the `ErrorFormatter` class inside a mypy plugin, and adding
a `name` field to the formatters. The mypy runtime can then check
through the `__subclasses__` of the formatter and determine if such a
formatter is present.
The "checking for the `name` field" part of this code might be
appropriate to add within this PR itself, instead of hard-coding
`JSONFormatter`. Does that sound like a good idea?
---------
Co-authored-by: Tushar Sadhwani <[email protected]>
Co-authored-by: Tushar Sadhwani <[email protected]>
0 commit comments