Skip to content

Instantly share code, notes, and snippets.

@lukpueh
Created October 18, 2022 11:57
Show Gist options
  • Save lukpueh/41026a3a7a594164150faf5afce94774 to your computer and use it in GitHub Desktop.
Save lukpueh/41026a3a7a594164150faf5afce94774 to your computer and use it in GitHub Desktop.
Inline-disable pylint based on logged messages.
"""Inline-disable pylint based on logged messages.
Parses pylint log and adds "# pylint: disable=<msg>, <msg>, .." inline to all flagged
lines, unless the pylint message is of type ERROR or FATAL.
This is useful, to enable a linter on a legacy code base, without the need to address
all warnings right away.
Issues:
- Messages about empty files, e.g. __init__.py are ignored
- Lines that already have an inline-comment are ignored (a warning is printed to stdout)
- Black autoformatting might move the inline comments in a way that pylint ignores them.
https://black.readthedocs.io/en/stable/faq.html#why-does-my-linter-or-typechecker-complain-after-i-format-my-code
Use this command to get expected log file + format:
pylint -j 0 \
--rcfile=pylintrc \
--output=pylint.log \
--msg-template="{path}:{line}:{msg_id}:{symbol}:{C}" \
<PATH>
"""
# Group pylint messages by module path and line number
with open("pylint.log") as pylint_log_fp:
modules = {}
for line in pylint_log_fp:
try:
path, line_number, msg_id, symbol, category = line.rstrip().split(
":"
)
except ValueError:
continue
line_number = int(line_number)
# Skip ERROR and FATAL type pylint messages. They should not be ignored!!
if category in ["E", "F"]:
print(f"FIX:{path}:{line_number}:{symbol}")
continue
if path not in modules:
modules[path] = {}
if line_number not in modules[path]:
modules[path][line_number] = []
modules[path][line_number].append(symbol)
# Add inline comments to disable pylint message types
for module_path, line_numbers in modules.items():
new = ""
with open(module_path) as module_fp:
for line_number, line in enumerate(module_fp, 1):
message_list = line_numbers.get(line_number)
if message_list is None:
new += line
continue
messages = ",".join(message_list)
comment = f"# pylint: disable={messages}"
if "#" in line:
print(f"FIX:{module_path}:{line_number}:{messages}")
new += line
continue
new += line.rstrip() + f" {comment}\n"
with open(module_path, "w") as module_fp:
module_fp.write(new)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment