Skip to content

Type add_message and add MessageLocationTuple #5050

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Sep 21, 2021
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions pylint/checkers/base_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,14 @@
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
import functools
from inspect import cleandoc
from typing import Any
from typing import Any, Optional, Tuple, Union

from astroid import nodes

from pylint.config import OptionsProviderMixIn
from pylint.constants import _MSG_ORDER, WarningScope
from pylint.exceptions import InvalidMessageError
from pylint.interfaces import UNDEFINED, IRawChecker, ITokenChecker, implements
from pylint.interfaces import Confidence, IRawChecker, ITokenChecker, implements
from pylint.message.message_definition import MessageDefinition
from pylint.typing import CheckerStats
from pylint.utils import get_rst_section, get_rst_title
Expand Down Expand Up @@ -109,10 +111,14 @@ def get_full_documentation(self, msgs, options, reports, doc=None, module=None):
return result

def add_message(
self, msgid, line=None, node=None, args=None, confidence=None, col_offset=None
):
if not confidence:
confidence = UNDEFINED
self,
msgid: str,
line: Optional[int] = None,
node: Optional[nodes.NodeNG] = None,
args: Union[str, Tuple[Union[str, int], ...], None] = None,
confidence: Optional[Confidence] = None,
col_offset: Optional[int] = None,
) -> None:
self.linter.add_message(msgid, line, node, args, confidence, col_offset)

def check_consistency(self):
Expand Down
40 changes: 39 additions & 1 deletion pylint/message/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@


import collections
from typing import Optional, Tuple, Union, overload
from warnings import warn

from pylint.constants import MSG_TYPES
from pylint.interfaces import Confidence
from pylint.typing import MessageLocationTuple

_MsgBase = collections.namedtuple(
"_MsgBase",
Expand All @@ -28,7 +32,41 @@
class Message(_MsgBase):
"""This class represent a message to be issued by the reporters"""

def __new__(cls, msg_id, symbol, location, msg, confidence):
@overload
def __new__(
cls,
msg_id: str,
symbol: str,
location: MessageLocationTuple,
msg: str,
confidence: Optional[Confidence],
) -> "Message":
...

@overload
def __new__(
cls,
msg_id: str,
symbol: str,
location: Tuple[str, str, str, str, int, int],
msg: str,
confidence: Optional[Confidence],
) -> "Message":
...

def __new__(
cls,
msg_id: str,
symbol: str,
location: Union[Tuple[str, str, str, str, int, int], MessageLocationTuple],
msg: str,
confidence: Optional[Confidence],
) -> "Message":
if not isinstance(location, MessageLocationTuple):
warn(
"In pylint 3.0, Messages will only accept a MessageLocationTuple as location parameter",
DeprecationWarning,
)
return _MsgBase.__new__(
cls,
msg_id,
Expand Down
46 changes: 32 additions & 14 deletions pylint/message/message_handler_mix_in.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@

import sys
from io import TextIOWrapper
from typing import List, TextIO, Tuple, Union
from typing import TYPE_CHECKING, List, Optional, TextIO, Tuple, Union

from astroid import nodes

from pylint.constants import (
_SCOPE_EXEMPT,
Expand All @@ -21,10 +23,14 @@
NoLineSuppliedError,
UnknownMessageError,
)
from pylint.interfaces import UNDEFINED
from pylint.interfaces import UNDEFINED, Confidence
from pylint.message.message import Message
from pylint.utils import get_module_and_frameid, get_rst_section, get_rst_title

if TYPE_CHECKING:
from pylint.lint.pylinter import PyLinter
from pylint.message import MessageDefinition


class MessagesHandlerMixIn:
"""A mix-in class containing all the messages related methods for the main lint class."""
Expand Down Expand Up @@ -226,9 +232,15 @@ def is_one_message_enabled(self, msgid, line):
return self._msgs_state.get(msgid, fallback)
return self._msgs_state.get(msgid, True)

def add_message(
self, msgid, line=None, node=None, args=None, confidence=None, col_offset=None
):
def add_message( # type: ignore # MessagesHandlerMixIn is always mixed with PyLinter
self: "PyLinter",
msgid: str,
line: Optional[int] = None,
node: Optional[nodes.NodeNG] = None,
args: Union[str, Tuple[Union[str, int], ...], None] = None,
confidence: Optional[Confidence] = None,
col_offset: Optional[int] = None,
) -> None:
"""Adds a message given by ID or name.

If provided, the message string is expanded using args.
Expand Down Expand Up @@ -267,14 +279,20 @@ def check_message_definition(message_definition, line, node):
f"Message {message_definition.msgid} must provide Node, got None"
)

def add_one_message(
self, message_definition, line, node, args, confidence, col_offset
):
def add_one_message( # type: ignore # MessagesHandlerMixIn is always mixed with PyLinter
self: "PyLinter",
message_definition: "MessageDefinition",
line: Optional[int],
node: Optional[nodes.NodeNG],
args: Union[str, Tuple[Union[str, int], ...], None],
confidence: Optional[Confidence],
col_offset: Optional[int],
) -> None:
self.check_message_definition(message_definition, line, node)
if line is None and node is not None:
line = node.fromlineno
if col_offset is None and hasattr(node, "col_offset"):
col_offset = node.col_offset
col_offset = node.col_offset # type: ignore

# should this message be displayed
if not self.is_message_enabled(message_definition.msgid, line, confidence):
Expand Down Expand Up @@ -303,13 +321,13 @@ def add_one_message(
"by_module": {self.current_name: {msg_cat: 0}},
"by_msg": {},
}
self.stats[msg_cat] += 1
self.stats["by_module"][self.current_name][msg_cat] += 1
self.stats[msg_cat] += 1 # type: ignore
self.stats["by_module"][self.current_name][msg_cat] += 1 # type: ignore
try:
self.stats["by_msg"][message_definition.symbol] += 1
self.stats["by_msg"][message_definition.symbol] += 1 # type: ignore
except KeyError:
self.stats["by_msg"][message_definition.symbol] = 1
# expand message ?
self.stats["by_msg"][message_definition.symbol] = 1 # type: ignore
# Interpolate arguments into message string
msg = message_definition.msg
if args:
msg %= args
Expand Down
15 changes: 13 additions & 2 deletions pylint/testutils/unittest_linter.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE

from typing import Optional, Tuple, Union

from astroid import nodes

from pylint.interfaces import Confidence
from pylint.testutils.global_test_linter import linter
from pylint.testutils.output_line import TestMessage
from pylint.typing import CheckerStats
Expand All @@ -22,8 +27,14 @@ def release_messages(self):
self._messages = []

def add_message(
self, msg_id, line=None, node=None, args=None, confidence=None, col_offset=None
):
self,
msg_id: str,
line: Optional[int] = None,
node: Optional[nodes.NodeNG] = None,
args: Union[str, Tuple[Union[str, int], ...], None] = None,
confidence: Optional[Confidence] = None,
col_offset: Optional[int] = None,
) -> None:
# Do not test col_offset for now since changing Message breaks everything
self._messages.append(TestMessage(msg_id, line, node, args, confidence))

Expand Down
11 changes: 11 additions & 0 deletions pylint/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,14 @@ class ErrorDescriptionDict(TypedDict):
CheckerStats = Dict[
str, Union[int, "Counter[str]", List, Dict[str, Union[int, str, Dict[str, int]]]]
]


class MessageLocationTuple(NamedTuple):
"""Tuple with information about the location of a to-be-displayed message"""

abspath: str
path: str
module: str
obj: str
line: int
column: int
49 changes: 22 additions & 27 deletions tests/message/unittest_message.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,24 @@
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE

from typing import Dict, ValuesView
from typing import ValuesView

from pylint.interfaces import HIGH
from pylint.message import Message
from pylint.message.message_definition import MessageDefinition
from pylint.typing import MessageLocationTuple


def test_new_message(message_definitions: ValuesView[MessageDefinition]) -> None:
def build_message(
message_definition: MessageDefinition, location_value: Dict[str, str]
message_definition: MessageDefinition, location_value: MessageLocationTuple
) -> Message:
return Message(
symbol=message_definition.symbol,
msg_id=message_definition.msgid,
location=[
location_value["abspath"],
location_value["path"],
location_value["module"],
location_value["obj"],
location_value["line"],
location_value["column"],
],
location=location_value,
msg=message_definition.msg,
confidence="high",
confidence=HIGH,
)

template = "{path}:{line}:{column}: {msg_id}: {msg} ({symbol})"
Expand All @@ -32,22 +27,22 @@ def build_message(
e1234_message_definition = message_definition
if message_definition.msgid == "W1234":
w1234_message_definition = message_definition
e1234_location_values = {
"abspath": "1",
"path": "2",
"module": "3",
"obj": "4",
"line": "5",
"column": "6",
}
w1234_location_values = {
"abspath": "7",
"path": "8",
"module": "9",
"obj": "10",
"line": "11",
"column": "12",
}
e1234_location_values = MessageLocationTuple(
abspath="1",
path="2",
module="3",
obj="4",
line=5,
column=6,
)
w1234_location_values = MessageLocationTuple(
abspath="7",
path="8",
module="9",
obj="10",
line=11,
column=12,
)
expected = (
"2:5:6: E1234: Duplicate keyword argument %r in %s call (duplicate-keyword-arg)"
)
Expand Down
2 changes: 1 addition & 1 deletion tests/testutils/test_output_line.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def inner(confidence: Confidence = HIGH) -> Message:
return Message(
symbol="missing-docstring",
msg_id="C0123",
location=[
location=[ # type: ignore
"abspath",
"path",
"module",
Expand Down