将新的代码库载入 mypy - 逐一消除错误

问题描述 投票:0回答:1

我目前正在将现有代码库转换为

mypy

有大约 500 个类型错误。 我不熟悉代码,因此修复所有错误将非常耗时。

我愿意:

  1. 奔跑
    mypy
  2. 对于列出的每个错误,编辑代码并添加 `# type:ignore # Legacy types。 暂时忽略。 看 。 如果您编辑此代码,请修复类型。

最好的方法是什么?

mypy
1个回答
0
投票
import re
import subprocess

mypy_command = ["poetry", "run", "mypy", "."]
ignore = " # type: ignore  # IF YOU EDIT THIS LINE, FIX THE TYPE. Do not add more type:ignores. SEE: PR#123"


def do_it() -> None:
    out = subprocess.run(
        mypy_command,
        capture_output=True,
        text=True,
    ).stdout
    for line in out.split("\n"):
        if is_last_line(line):
            print("Processed all lines")
            break
        handle_line(line)


def handle_line(line: str) -> None:
    items = line.split(":")
    file: str = items[0]
    line_num: int = int(items[1])

    print(f"Fixing: {file} --- {line_num}")

    fix_line(file, line_num)


def fix_line(filename: str, line_num: int) -> None:

    line_num -= 1 # File lines are 1 indexed according to mypy but 0 indexed in an array

    with open(filename, 'r') as txt:
        text = txt.readlines()

    if "#" in text[line_num]:
        print("WARNING: This line already has a comment - manual intervention required.")
        return

    new_line = text[line_num][0:-1] + ignore + "\n"

    text[line_num] = new_line

    with open(filename, 'w') as txt:
        txt.writelines(text)


def is_last_line(line: str) -> bool:
    last_line_pattern = "Found [0-9]* errors in [0-9]* files"
    return bool(re.match(last_line_pattern, line))


do_it()
© www.soinside.com 2019 - 2024. All rights reserved.