Last active
November 29, 2023 15:35
-
-
Save Kilo59/3f140fdbbcd8fb3072c289a94afef1a6 to your computer and use it in GitHub Desktop.
Add `@override` decoraters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import annotations | |
import pathlib | |
import sys | |
from collections import Counter | |
from pprint import pformat as pf | |
from typing import Iterable, Iterator, NamedTuple | |
from mypy import api | |
from typing_extensions import override | |
class Result(NamedTuple): | |
source: pathlib.Path | |
lineno: int | |
message: str | |
error_code: str | |
@override | |
def __repr__(self) -> str: | |
return f"({self.source}, {self.lineno}, {self.error_code})" | |
def iterate_lines(stdout: str, limit: int) -> Iterator[Result]: | |
for i, line in enumerate(stdout.splitlines()): | |
if i >= limit: | |
break | |
try: | |
source, lineno, _, full_message = line.split(":") | |
message, error_code = full_message.split(" ") | |
except ValueError: | |
print(f"skipping line:\n\t{line}") | |
continue | |
if error_code != "[explicit-override]": | |
continue | |
yield Result(pathlib.Path(source), int(lineno), message.lstrip(), error_code) | |
LINENO_MAPPINGS: Counter[pathlib.Path] = Counter() | |
def insert_override(source: pathlib.Path, lineno: int) -> None: | |
LINENO_MAPPINGS.update([source]) | |
with open(source) as f_in: | |
lines = f_in.readlines() | |
lines.insert(lineno - 2 + LINENO_MAPPINGS[source], " @override\n") | |
with open(source, "w") as f_out: | |
f_out.writelines(lines) | |
def add_imports(sources: Iterable[pathlib.Path]): | |
for source in sources: | |
with open(source) as f_in: | |
lines = f_in.readlines() | |
# ruff will take care of duplicates and sorting | |
lines.insert(0, "from typing_extensions import override\n") | |
with open(source, "w") as f_out: | |
f_out.writelines(lines) | |
result = api.run(sys.argv[1:]) | |
stdout = result[0] | |
for error in iterate_lines(stdout, limit=1000): | |
print(error) | |
insert_override(error.source, error.lineno) | |
add_imports(LINENO_MAPPINGS.keys()) | |
print(f"{pf(LINENO_MAPPINGS)}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment