pylinter.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  1. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  2. # For details: https://github.com/pylint-dev/pylint/blob/main/LICENSE
  3. # Copyright (c) https://github.com/pylint-dev/pylint/blob/main/CONTRIBUTORS.txt
  4. from __future__ import annotations
  5. import argparse
  6. import collections
  7. import contextlib
  8. import functools
  9. import os
  10. import sys
  11. import tokenize
  12. import traceback
  13. import warnings
  14. from collections import defaultdict
  15. from collections.abc import Callable, Iterable, Iterator, Sequence
  16. from io import TextIOWrapper
  17. from pathlib import Path
  18. from re import Pattern
  19. from types import ModuleType
  20. from typing import Any, Protocol
  21. import astroid
  22. import astroid.builder
  23. import astroid.modutils
  24. from astroid import nodes
  25. from pylint import checkers, exceptions, interfaces, reporters
  26. from pylint.checkers.base_checker import BaseChecker
  27. from pylint.config.arguments_manager import _ArgumentsManager
  28. from pylint.constants import (
  29. MAIN_CHECKER_NAME,
  30. MSG_TYPES,
  31. MSG_TYPES_STATUS,
  32. WarningScope,
  33. )
  34. from pylint.interfaces import HIGH
  35. from pylint.lint.base_options import _make_linter_options
  36. from pylint.lint.caching import load_results, save_results
  37. from pylint.lint.expand_modules import (
  38. _is_ignored_file,
  39. discover_package_path,
  40. expand_modules,
  41. )
  42. from pylint.lint.message_state_handler import _MessageStateHandler
  43. from pylint.lint.parallel import check_parallel
  44. from pylint.lint.report_functions import (
  45. report_messages_by_module_stats,
  46. report_messages_stats,
  47. report_total_messages_stats,
  48. )
  49. from pylint.lint.utils import (
  50. augmented_sys_path,
  51. get_fatal_error_message,
  52. prepare_crash_report,
  53. )
  54. from pylint.message import Message, MessageDefinition, MessageDefinitionStore
  55. from pylint.reporters.base_reporter import BaseReporter
  56. from pylint.reporters.progress_reporters import ProgressReporter
  57. from pylint.reporters.text import ColorizedTextReporter, TextReporter
  58. from pylint.reporters.ureports import nodes as report_nodes
  59. from pylint.typing import (
  60. DirectoryNamespaceDict,
  61. FileItem,
  62. ManagedMessage,
  63. MessageDefinitionTuple,
  64. MessageLocationTuple,
  65. ModuleDescriptionDict,
  66. Options,
  67. )
  68. from pylint.utils import ASTWalker, FileState, LinterStats, utils
  69. MANAGER = astroid.MANAGER
  70. class GetAstProtocol(Protocol):
  71. def __call__(
  72. self, filepath: str, modname: str, data: str | None = None
  73. ) -> nodes.Module: ...
  74. def _read_stdin() -> str:
  75. # See https://github.com/python/typeshed/pull/5623 for rationale behind assertion
  76. assert isinstance(sys.stdin, TextIOWrapper)
  77. sys.stdin = TextIOWrapper(sys.stdin.detach(), encoding="utf-8")
  78. return sys.stdin.read()
  79. def _load_reporter_by_class(reporter_class: str) -> type[BaseReporter]:
  80. qname = reporter_class
  81. module_part = astroid.modutils.get_module_part(qname)
  82. module = astroid.modutils.load_module_from_name(module_part)
  83. class_name = qname.split(".")[-1]
  84. klass = getattr(module, class_name)
  85. assert issubclass(klass, BaseReporter), f"{klass} is not a BaseReporter"
  86. return klass # type: ignore[no-any-return]
  87. # Python Linter class #########################################################
  88. # pylint: disable-next=consider-using-namedtuple-or-dataclass
  89. MSGS: dict[str, MessageDefinitionTuple] = {
  90. "F0001": (
  91. "%s",
  92. "fatal",
  93. "Used when an error occurred preventing the analysis of a \
  94. module (unable to find it for instance).",
  95. {"scope": WarningScope.LINE},
  96. ),
  97. "F0002": (
  98. "%s: %s",
  99. "astroid-error",
  100. "Used when an unexpected error occurred while building the "
  101. "Astroid representation. This is usually accompanied by a "
  102. "traceback. Please report such errors !",
  103. {"scope": WarningScope.LINE},
  104. ),
  105. "F0010": (
  106. "error while code parsing: %s",
  107. "parse-error",
  108. "Used when an exception occurred while building the Astroid "
  109. "representation which could be handled by astroid.",
  110. {"scope": WarningScope.LINE},
  111. ),
  112. "F0011": (
  113. "error while parsing the configuration: %s",
  114. "config-parse-error",
  115. "Used when an exception occurred while parsing a pylint configuration file.",
  116. {"scope": WarningScope.LINE},
  117. ),
  118. "I0001": (
  119. "Unable to run raw checkers on built-in module %s",
  120. "raw-checker-failed",
  121. "Used to inform that a built-in module has not been checked "
  122. "using the raw checkers.",
  123. {
  124. "scope": WarningScope.LINE,
  125. "default_enabled": False,
  126. },
  127. ),
  128. "I0010": (
  129. "Unable to consider inline option %r",
  130. "bad-inline-option",
  131. "Used when an inline option is either badly formatted or can't "
  132. "be used inside modules.",
  133. {
  134. "scope": WarningScope.LINE,
  135. "default_enabled": False,
  136. },
  137. ),
  138. "I0011": (
  139. "Locally disabling %s (%s)",
  140. "locally-disabled",
  141. "Used when an inline option disables a message or a messages category.",
  142. {
  143. "scope": WarningScope.LINE,
  144. "default_enabled": False,
  145. },
  146. ),
  147. "I0013": (
  148. "Ignoring entire file",
  149. "file-ignored",
  150. "Used to inform that the file will not be checked",
  151. {
  152. "scope": WarningScope.LINE,
  153. "default_enabled": False,
  154. },
  155. ),
  156. "I0020": (
  157. "Suppressed %s (from line %d)",
  158. "suppressed-message",
  159. "A message was triggered on a line, but suppressed explicitly "
  160. "by a disable= comment in the file. This message is not "
  161. "generated for messages that are ignored due to configuration "
  162. "settings.",
  163. {
  164. "scope": WarningScope.LINE,
  165. "default_enabled": False,
  166. },
  167. ),
  168. "I0021": (
  169. "Useless suppression of %s",
  170. "useless-suppression",
  171. "Reported when a message is explicitly disabled for a line or "
  172. "a block of code, but never triggered.",
  173. {
  174. "scope": WarningScope.LINE,
  175. "default_enabled": False,
  176. },
  177. ),
  178. "I0022": (
  179. 'Pragma "%s" is deprecated, use "%s" instead',
  180. "deprecated-pragma",
  181. "Some inline pylint options have been renamed or reworked, "
  182. "only the most recent form should be used. "
  183. "NOTE:skip-all is only available with pylint >= 0.26",
  184. {
  185. "old_names": [("I0014", "deprecated-disable-all")],
  186. "scope": WarningScope.LINE,
  187. "default_enabled": False,
  188. },
  189. ),
  190. "E0001": (
  191. "%s",
  192. "syntax-error",
  193. "Used when a syntax error is raised for a module.",
  194. {"scope": WarningScope.LINE},
  195. ),
  196. "E0011": (
  197. "Unrecognized file option %r",
  198. "unrecognized-inline-option",
  199. "Used when an unknown inline option is encountered.",
  200. {"scope": WarningScope.LINE},
  201. ),
  202. "W0012": (
  203. "Unknown option value for '%s', expected a valid pylint message and got '%s'",
  204. "unknown-option-value",
  205. "Used when an unknown value is encountered for an option.",
  206. {
  207. "scope": WarningScope.LINE,
  208. "old_names": [("E0012", "bad-option-value")],
  209. },
  210. ),
  211. "R0022": (
  212. "Useless option value for '%s', %s",
  213. "useless-option-value",
  214. "Used when a value for an option that is now deleted from pylint"
  215. " is encountered.",
  216. {
  217. "scope": WarningScope.LINE,
  218. "old_names": [("E0012", "bad-option-value")],
  219. },
  220. ),
  221. "E0013": (
  222. "Plugin '%s' is impossible to load, is it installed ? ('%s')",
  223. "bad-plugin-value",
  224. "Used when a bad value is used in 'load-plugins'.",
  225. {"scope": WarningScope.LINE},
  226. ),
  227. "E0014": (
  228. "Out-of-place setting encountered in top level configuration-section '%s' : '%s'",
  229. "bad-configuration-section",
  230. "Used when we detect a setting in the top level of a toml configuration that"
  231. " shouldn't be there.",
  232. {"scope": WarningScope.LINE},
  233. ),
  234. "E0015": (
  235. "Unrecognized option found: %s",
  236. "unrecognized-option",
  237. "Used when we detect an option that we do not recognize.",
  238. {"scope": WarningScope.LINE},
  239. ),
  240. }
  241. # pylint: disable=too-many-instance-attributes,too-many-public-methods
  242. class PyLinter(
  243. _ArgumentsManager,
  244. _MessageStateHandler,
  245. reporters.ReportsHandlerMixIn,
  246. checkers.BaseChecker,
  247. ):
  248. """Lint Python modules using external checkers.
  249. This is the main checker controlling the other ones and the reports
  250. generation. It is itself both a raw checker and an astroid checker in order
  251. to:
  252. * handle message activation / deactivation at the module level
  253. * handle some basic but necessary stats' data (number of classes, methods...)
  254. IDE plugin developers: you may have to call
  255. `astroid.MANAGER.clear_cache()` across runs if you want
  256. to ensure the latest code version is actually checked.
  257. This class needs to support pickling for parallel linting to work. The exception
  258. is reporter member; see check_parallel function for more details.
  259. """
  260. name = MAIN_CHECKER_NAME
  261. msgs = MSGS
  262. # Will be used like this : datetime.now().strftime(crash_file_path)
  263. crash_file_path: str = "pylint-crash-%Y-%m-%d-%H-%M-%S.txt"
  264. option_groups_descs = {
  265. "Messages control": "Options controlling analysis messages",
  266. "Reports": "Options related to output formatting and reporting",
  267. }
  268. def __init__(
  269. self,
  270. options: Options = (),
  271. reporter: reporters.BaseReporter | reporters.MultiReporter | None = None,
  272. option_groups: tuple[tuple[str, str], ...] = (),
  273. pylintrc: str | None = None,
  274. ) -> None:
  275. _ArgumentsManager.__init__(self, prog="pylint")
  276. _MessageStateHandler.__init__(self, self)
  277. if pylintrc is not None:
  278. warnings.warn(
  279. "The pylintrc argument will be removed in pylint 5.0.",
  280. DeprecationWarning,
  281. stacklevel=2,
  282. )
  283. # Some stuff has to be done before initialization of other ancestors...
  284. # messages store / checkers / reporter / astroid manager
  285. # Attributes for reporters
  286. self.reporter: reporters.BaseReporter | reporters.MultiReporter
  287. if reporter:
  288. self.set_reporter(reporter)
  289. else:
  290. self.set_reporter(TextReporter())
  291. self._reporters: dict[str, type[reporters.BaseReporter]] = {}
  292. """Dictionary of possible but non-initialized reporters."""
  293. # Attributes for checkers and plugins
  294. self._checkers: defaultdict[str, list[checkers.BaseChecker]] = (
  295. collections.defaultdict(list)
  296. )
  297. """Dictionary of registered and initialized checkers."""
  298. self._dynamic_plugins: dict[str, ModuleType | ModuleNotFoundError | bool] = {}
  299. """Set of loaded plugin names."""
  300. # Attributes related to stats
  301. self.stats = LinterStats()
  302. # Attributes related to (command-line) options and their parsing
  303. self.options: Options = options + _make_linter_options(self)
  304. for opt_group in option_groups:
  305. self.option_groups_descs[opt_group[0]] = opt_group[1]
  306. self._option_groups: tuple[tuple[str, str], ...] = (
  307. *option_groups,
  308. *PyLinter.option_groups_descs.items(),
  309. )
  310. self.fail_on_symbols: list[str] = []
  311. """List of message symbols on which pylint should fail, set by --fail-on."""
  312. self._error_mode = False
  313. reporters.ReportsHandlerMixIn.__init__(self)
  314. checkers.BaseChecker.__init__(self, self)
  315. # provided reports
  316. self.reports = (
  317. ("RP0001", "Messages by category", report_total_messages_stats),
  318. (
  319. "RP0002",
  320. "% errors / warnings by module",
  321. report_messages_by_module_stats,
  322. ),
  323. ("RP0003", "Messages", report_messages_stats),
  324. )
  325. # Attributes related to registering messages and their handling
  326. self.msgs_store = MessageDefinitionStore(self.config.py_version)
  327. self.msg_status = 0
  328. self._by_id_managed_msgs: list[ManagedMessage] = []
  329. # Attributes related to visiting files
  330. self.file_state = FileState("", self.msgs_store, is_base_filestate=True)
  331. self.current_name: str = ""
  332. self.current_file: str | None = None
  333. self._ignore_file = False
  334. self._ignore_paths: list[Pattern[str]] = []
  335. self.verbose = False
  336. self.register_checker(self)
  337. def load_default_plugins(self) -> None:
  338. checkers.initialize(self)
  339. reporters.initialize(self)
  340. def load_plugin_modules(self, modnames: Iterable[str], force: bool = False) -> None:
  341. """Check a list of pylint plugins modules, load and register them.
  342. If a module cannot be loaded, never try to load it again and instead
  343. store the error message for later use in ``load_plugin_configuration``
  344. below.
  345. If `force` is True (useful when multiprocessing), then the plugin is
  346. reloaded regardless if an entry exists in self._dynamic_plugins.
  347. """
  348. for modname in modnames:
  349. if modname in self._dynamic_plugins and not force:
  350. continue
  351. try:
  352. module = astroid.modutils.load_module_from_name(modname)
  353. module.register(self)
  354. self._dynamic_plugins[modname] = module
  355. except ModuleNotFoundError as mnf_e:
  356. self._dynamic_plugins[modname] = mnf_e
  357. def load_plugin_configuration(self) -> None:
  358. """Call the configuration hook for plugins.
  359. This walks through the list of plugins, grabs the "load_configuration"
  360. hook, if exposed, and calls it to allow plugins to configure specific
  361. settings.
  362. The result of attempting to load the plugin of the given name
  363. is stored in the dynamic plugins dictionary in ``load_plugin_modules`` above.
  364. ..note::
  365. This function previously always tried to load modules again, which
  366. led to some confusion and silent failure conditions as described
  367. in GitHub issue #7264. Making it use the stored result is more efficient, and
  368. means that we avoid the ``init-hook`` problems from before.
  369. """
  370. for modname, module_or_error in self._dynamic_plugins.items():
  371. if isinstance(module_or_error, ModuleNotFoundError):
  372. self.add_message(
  373. "bad-plugin-value", args=(modname, module_or_error), line=0
  374. )
  375. elif hasattr(module_or_error, "load_configuration"):
  376. module_or_error.load_configuration(self)
  377. # We re-set all the dictionary values to True here to make sure the dict
  378. # is pickle-able. This is only a problem in multiprocessing/parallel mode.
  379. # (e.g. invoking pylint -j 2)
  380. self._dynamic_plugins = {
  381. modname: not isinstance(val, ModuleNotFoundError)
  382. for modname, val in self._dynamic_plugins.items()
  383. }
  384. def _load_reporters(self, reporter_names: str) -> None:
  385. """Load the reporters if they are available on _reporters."""
  386. if not self._reporters:
  387. return
  388. sub_reporters = []
  389. output_files = []
  390. with contextlib.ExitStack() as stack:
  391. for reporter_name in reporter_names.split(","):
  392. reporter_name, *reporter_output = reporter_name.split(":", 1)
  393. reporter = self._load_reporter_by_name(reporter_name)
  394. sub_reporters.append(reporter)
  395. if reporter_output:
  396. output_file = stack.enter_context(
  397. open(reporter_output[0], "w", encoding="utf-8")
  398. )
  399. reporter.out = output_file
  400. output_files.append(output_file)
  401. # Extend the lifetime of all opened output files
  402. close_output_files = stack.pop_all().close
  403. if len(sub_reporters) > 1 or output_files:
  404. self.set_reporter(
  405. reporters.MultiReporter(
  406. sub_reporters,
  407. close_output_files,
  408. )
  409. )
  410. else:
  411. self.set_reporter(sub_reporters[0])
  412. def _load_reporter_by_name(self, reporter_name: str) -> reporters.BaseReporter:
  413. name = reporter_name.lower()
  414. if name in self._reporters:
  415. return self._reporters[name]()
  416. try:
  417. reporter_class = _load_reporter_by_class(reporter_name)
  418. except (ImportError, AttributeError, AssertionError) as e:
  419. raise exceptions.InvalidReporterError(name) from e
  420. return reporter_class()
  421. def set_reporter(
  422. self, reporter: reporters.BaseReporter | reporters.MultiReporter
  423. ) -> None:
  424. """Set the reporter used to display messages and reports."""
  425. self.reporter = reporter
  426. reporter.linter = self
  427. def register_reporter(self, reporter_class: type[reporters.BaseReporter]) -> None:
  428. """Registers a reporter class on the _reporters attribute."""
  429. self._reporters[reporter_class.name] = reporter_class
  430. def report_order(self) -> list[BaseChecker]:
  431. reports = sorted(self._reports, key=lambda x: getattr(x, "name", ""))
  432. try:
  433. # Remove the current reporter and add it
  434. # at the end of the list.
  435. reports.pop(reports.index(self))
  436. except ValueError:
  437. pass
  438. else:
  439. reports.append(self)
  440. return reports
  441. # checkers manipulation methods ############################################
  442. def register_checker(self, checker: checkers.BaseChecker) -> None:
  443. """This method auto registers the checker."""
  444. self._checkers[checker.name].append(checker)
  445. for r_id, r_title, r_cb in checker.reports:
  446. self.register_report(r_id, r_title, r_cb, checker)
  447. if hasattr(checker, "msgs"):
  448. self.msgs_store.register_messages_from_checker(checker)
  449. for message in checker.messages:
  450. if not message.default_enabled:
  451. self.disable(message.msgid)
  452. # Register the checker, but disable all of its messages.
  453. if not getattr(checker, "enabled", True):
  454. self.disable(checker.name)
  455. def enable_fail_on_messages(self) -> None:
  456. """Enable 'fail on' msgs.
  457. Convert values in config.fail_on (which might be msg category, msg id,
  458. or symbol) to specific msgs, then enable and flag them for later.
  459. """
  460. fail_on_vals = self.config.fail_on
  461. if not fail_on_vals:
  462. return
  463. fail_on_cats = set()
  464. fail_on_msgs = set()
  465. for val in fail_on_vals:
  466. # If value is a category, add category, else add message
  467. if val in MSG_TYPES:
  468. fail_on_cats.add(val)
  469. else:
  470. fail_on_msgs.add(val)
  471. # For every message in every checker, if cat or msg flagged, enable check
  472. for all_checkers in self._checkers.values():
  473. for checker in all_checkers:
  474. for msg in checker.messages:
  475. if msg.msgid in fail_on_msgs or msg.symbol in fail_on_msgs:
  476. # message id/symbol matched, enable and flag it
  477. self.enable(msg.msgid)
  478. self.fail_on_symbols.append(msg.symbol)
  479. elif msg.msgid[0] in fail_on_cats:
  480. # message starts with a category value, flag (but do not enable) it
  481. self.fail_on_symbols.append(msg.symbol)
  482. def any_fail_on_issues(self) -> bool:
  483. return any(x in self.fail_on_symbols for x in self.stats.by_msg.keys())
  484. def pass_fail_on_config_to_color_reporter(self) -> None:
  485. """Pass fail_on symbol configuration to colorized text reporter."""
  486. if isinstance(self.reporter, ColorizedTextReporter):
  487. self.reporter.set_fail_on_symbols(self.fail_on_symbols)
  488. elif isinstance(self.reporter, reporters.MultiReporter):
  489. for reporter in self.reporter._sub_reporters:
  490. if isinstance(reporter, ColorizedTextReporter):
  491. reporter.set_fail_on_symbols(self.fail_on_symbols)
  492. def disable_reporters(self) -> None:
  493. """Disable all reporters."""
  494. for _reporters in self._reports.values():
  495. for report_id, _, _ in _reporters:
  496. self.disable_report(report_id)
  497. def _parse_error_mode(self) -> None:
  498. """Parse the current state of the error mode.
  499. Error mode: enable only errors; no reports, no persistent.
  500. """
  501. if not self._error_mode:
  502. return
  503. self.disable_noerror_messages()
  504. self.disable("miscellaneous")
  505. self.set_option("reports", False)
  506. self.set_option("persistent", False)
  507. self.set_option("score", False)
  508. # code checking methods ###################################################
  509. def get_checkers(self) -> list[BaseChecker]:
  510. """Return all available checkers as an ordered list."""
  511. return sorted(c for _checkers in self._checkers.values() for c in _checkers)
  512. def get_checker_names(self) -> list[str]:
  513. """Get all the checker names that this linter knows about."""
  514. return sorted(
  515. {
  516. checker.name
  517. for checker in self.get_checkers()
  518. if checker.name != MAIN_CHECKER_NAME
  519. }
  520. )
  521. def prepare_checkers(self) -> list[BaseChecker]:
  522. """Return checkers needed for activated messages and reports."""
  523. if not self.config.reports:
  524. self.disable_reporters()
  525. # get needed checkers
  526. needed_checkers: list[BaseChecker] = [self]
  527. for checker in self.get_checkers()[1:]:
  528. messages = {msg for msg in checker.msgs if self.is_message_enabled(msg)}
  529. if messages or any(self.report_is_enabled(r[0]) for r in checker.reports):
  530. needed_checkers.append(checker)
  531. return needed_checkers
  532. # pylint: disable=unused-argument
  533. @staticmethod
  534. def should_analyze_file(modname: str, path: str, is_argument: bool = False) -> bool:
  535. """Returns whether a module should be checked.
  536. This implementation returns True for all python source files (.py and .pyi),
  537. indicating that all files should be linted.
  538. Subclasses may override this method to indicate that modules satisfying
  539. certain conditions should not be linted.
  540. :param str modname: The name of the module to be checked.
  541. :param str path: The full path to the source code of the module.
  542. :param bool is_argument: Whether the file is an argument to pylint or not.
  543. Files which respect this property are always
  544. checked, since the user requested it explicitly.
  545. :returns: True if the module should be checked.
  546. """
  547. if is_argument:
  548. return True
  549. return path.endswith((".py", ".pyi"))
  550. # pylint: enable=unused-argument
  551. def initialize(self) -> None:
  552. """Initialize linter for linting.
  553. This method is called before any linting is done.
  554. """
  555. self._ignore_paths = self.config.ignore_paths
  556. # initialize msgs_state now that all messages have been registered into
  557. # the store
  558. for msg in self.msgs_store.messages:
  559. if not msg.may_be_emitted(self.config.py_version):
  560. self._msgs_state[msg.msgid] = False
  561. def _discover_files(self, files_or_modules: Sequence[str]) -> Iterator[str]:
  562. """Discover python modules and packages in sub-directory.
  563. Returns iterator of paths to discovered modules and packages.
  564. """
  565. for something in files_or_modules:
  566. if os.path.isdir(something) and not os.path.isfile(
  567. os.path.join(something, "__init__.py")
  568. ):
  569. skip_subtrees: list[str] = []
  570. for root, _, files in os.walk(something):
  571. if any(root.startswith(s) for s in skip_subtrees):
  572. # Skip subtree of already discovered package.
  573. continue
  574. if _is_ignored_file(
  575. root,
  576. self.config.ignore,
  577. self.config.ignore_patterns,
  578. self.config.ignore_paths,
  579. ):
  580. skip_subtrees.append(root)
  581. continue
  582. if "__init__.py" in files:
  583. skip_subtrees.append(root)
  584. yield root
  585. else:
  586. yield from (
  587. os.path.join(root, file)
  588. for file in files
  589. if file.endswith((".py", ".pyi"))
  590. )
  591. else:
  592. yield something
  593. def check(self, files_or_modules: Sequence[str]) -> None:
  594. """Main checking entry: check a list of files or modules from their name.
  595. files_or_modules is either a string or list of strings presenting modules to check.
  596. """
  597. self.initialize()
  598. if self.config.recursive:
  599. files_or_modules = tuple(self._discover_files(files_or_modules))
  600. if self.config.from_stdin:
  601. if len(files_or_modules) != 1:
  602. raise exceptions.InvalidArgsError(
  603. "Missing filename required for --from-stdin"
  604. )
  605. extra_packages_paths = list(
  606. dict.fromkeys(
  607. [
  608. discover_package_path(file_or_module, self.config.source_roots)
  609. for file_or_module in files_or_modules
  610. ]
  611. ).keys()
  612. )
  613. # TODO: Move the parallel invocation into step 3 of the checking process
  614. if not self.config.from_stdin and self.config.jobs > 1:
  615. original_sys_path = sys.path[:]
  616. check_parallel(
  617. self,
  618. self.config.jobs,
  619. self._iterate_file_descrs(files_or_modules),
  620. extra_packages_paths,
  621. )
  622. sys.path = original_sys_path
  623. return
  624. progress_reporter = ProgressReporter(self.verbose)
  625. # 1) Get all FileItems
  626. with augmented_sys_path(extra_packages_paths):
  627. if self.config.from_stdin:
  628. fileitems = self._get_file_descr_from_stdin(files_or_modules[0])
  629. data: str | None = _read_stdin()
  630. else:
  631. fileitems = self._iterate_file_descrs(files_or_modules)
  632. data = None
  633. # The contextmanager also opens all checkers and sets up the PyLinter class
  634. with augmented_sys_path(extra_packages_paths):
  635. with self._astroid_module_checker() as check_astroid_module:
  636. # 2) Get the AST for each FileItem
  637. ast_per_fileitem = self._get_asts(fileitems, data, progress_reporter)
  638. # 3) Lint each ast
  639. self._lint_files(
  640. ast_per_fileitem, check_astroid_module, progress_reporter
  641. )
  642. def _get_asts(
  643. self,
  644. fileitems: Iterator[FileItem],
  645. data: str | None,
  646. progress_reporter: ProgressReporter,
  647. ) -> dict[FileItem, nodes.Module | None]:
  648. """Get the AST for all given FileItems."""
  649. ast_per_fileitem: dict[FileItem, nodes.Module | None] = {}
  650. progress_reporter.start_get_asts()
  651. for fileitem in fileitems:
  652. progress_reporter.get_ast_for_file(fileitem.filepath)
  653. self.set_current_module(fileitem.name, fileitem.filepath)
  654. try:
  655. ast_per_fileitem[fileitem] = self.get_ast(
  656. fileitem.filepath, fileitem.name, data
  657. )
  658. except astroid.AstroidBuildingError as ex:
  659. template_path = prepare_crash_report(
  660. ex, fileitem.filepath, self.crash_file_path
  661. )
  662. msg = get_fatal_error_message(fileitem.filepath, template_path)
  663. self.add_message(
  664. "astroid-error",
  665. args=(fileitem.filepath, msg),
  666. confidence=HIGH,
  667. )
  668. return ast_per_fileitem
  669. def check_single_file_item(self, file: FileItem) -> None:
  670. """Check single file item.
  671. The arguments are the same that are documented in _check_files
  672. initialize() should be called before calling this method
  673. """
  674. with self._astroid_module_checker() as check_astroid_module:
  675. self._check_file(self.get_ast, check_astroid_module, file)
  676. def _lint_files(
  677. self,
  678. ast_mapping: dict[FileItem, nodes.Module | None],
  679. check_astroid_module: Callable[[nodes.Module], bool | None],
  680. progress_reporter: ProgressReporter,
  681. ) -> None:
  682. """Lint all AST modules from a mapping.."""
  683. progress_reporter.start_linting()
  684. for fileitem, module in ast_mapping.items():
  685. progress_reporter.lint_file(fileitem.filepath)
  686. if module is None:
  687. continue
  688. try:
  689. self._lint_file(fileitem, module, check_astroid_module)
  690. self.stats.modules_names.add(fileitem.filepath)
  691. except Exception as ex: # pylint: disable=broad-except
  692. template_path = prepare_crash_report(
  693. ex, fileitem.filepath, self.crash_file_path
  694. )
  695. msg = get_fatal_error_message(fileitem.filepath, template_path)
  696. if isinstance(ex, astroid.AstroidError):
  697. self.add_message(
  698. "astroid-error", args=(fileitem.filepath, msg), confidence=HIGH
  699. )
  700. else:
  701. self.add_message("fatal", args=msg, confidence=HIGH)
  702. def _lint_file(
  703. self,
  704. file: FileItem,
  705. module: nodes.Module,
  706. check_astroid_module: Callable[[nodes.Module], bool | None],
  707. ) -> None:
  708. """Lint a file using the passed utility function check_astroid_module).
  709. :param FileItem file: data about the file
  710. :param nodes.Module module: the ast module to lint
  711. :param Callable check_astroid_module: callable checking an AST taking the following
  712. arguments
  713. - ast: AST of the module
  714. :raises AstroidError: for any failures stemming from astroid
  715. """
  716. self.set_current_module(file.name, file.filepath)
  717. self._ignore_file = False
  718. self.file_state = FileState(file.modpath, self.msgs_store, module)
  719. # fix the current file (if the source file was not available or
  720. # if it's actually a c extension)
  721. self.current_file = module.file
  722. try:
  723. check_astroid_module(module)
  724. except Exception as e:
  725. raise astroid.AstroidError from e
  726. # warn about spurious inline messages handling
  727. spurious_messages = self.file_state.iter_spurious_suppression_messages(
  728. self.msgs_store
  729. )
  730. for msgid, line, args in spurious_messages:
  731. self.add_message(msgid, line, None, args)
  732. def _check_file(
  733. self,
  734. get_ast: GetAstProtocol,
  735. check_astroid_module: Callable[[nodes.Module], bool | None],
  736. file: FileItem,
  737. ) -> None:
  738. """Check a file using the passed utility functions (get_ast and
  739. check_astroid_module).
  740. :param callable get_ast: callable returning AST from defined file taking the
  741. following arguments
  742. - filepath: path to the file to check
  743. - name: Python module name
  744. :param callable check_astroid_module: callable checking an AST taking the following
  745. arguments
  746. - ast: AST of the module
  747. :param FileItem file: data about the file
  748. :raises AstroidError: for any failures stemming from astroid
  749. """
  750. self.set_current_module(file.name, file.filepath)
  751. # get the module representation
  752. ast_node = get_ast(file.filepath, file.name)
  753. if ast_node is None:
  754. return
  755. self._ignore_file = False
  756. self.file_state = FileState(file.modpath, self.msgs_store, ast_node)
  757. # fix the current file (if the source file was not available or
  758. # if it's actually a c extension)
  759. self.current_file = ast_node.file
  760. try:
  761. check_astroid_module(ast_node)
  762. except Exception as e: # pragma: no cover
  763. raise astroid.AstroidError from e
  764. # warn about spurious inline messages handling
  765. spurious_messages = self.file_state.iter_spurious_suppression_messages(
  766. self.msgs_store
  767. )
  768. for msgid, line, args in spurious_messages:
  769. self.add_message(msgid, line, None, args)
  770. def _get_file_descr_from_stdin(self, filepath: str) -> Iterator[FileItem]:
  771. """Return file description (tuple of module name, file path, base name) from
  772. given file path.
  773. This method is used for creating suitable file description for _check_files when the
  774. source is standard input.
  775. """
  776. if _is_ignored_file(
  777. filepath,
  778. self.config.ignore,
  779. self.config.ignore_patterns,
  780. self.config.ignore_paths,
  781. ):
  782. self.stats.skipped += 1
  783. return
  784. try:
  785. # Note that this function does not really perform an
  786. # __import__ but may raise an ImportError exception, which
  787. # we want to catch here.
  788. modname = ".".join(astroid.modutils.modpath_from_file(filepath))
  789. except ImportError:
  790. modname = os.path.splitext(os.path.basename(filepath))[0]
  791. yield FileItem(modname, filepath, filepath)
  792. def _iterate_file_descrs(
  793. self, files_or_modules: Sequence[str]
  794. ) -> Iterator[FileItem]:
  795. """Return generator yielding file descriptions (tuples of module name, file
  796. path, base name).
  797. The returned generator yield one item for each Python module that should be linted.
  798. """
  799. for descr in self._expand_files(files_or_modules).values():
  800. name, filepath, is_arg = descr["name"], descr["path"], descr["isarg"]
  801. if descr["isignored"]:
  802. self.stats.skipped += 1
  803. elif self.should_analyze_file(name, filepath, is_argument=is_arg):
  804. yield FileItem(name, filepath, descr["basename"])
  805. def _expand_files(
  806. self, files_or_modules: Sequence[str]
  807. ) -> dict[str, ModuleDescriptionDict]:
  808. """Get modules and errors from a list of modules and handle errors."""
  809. result, errors = expand_modules(
  810. files_or_modules,
  811. self.config.source_roots,
  812. self.config.ignore,
  813. self.config.ignore_patterns,
  814. self._ignore_paths,
  815. )
  816. for error in errors:
  817. message = modname = error["mod"]
  818. key = error["key"]
  819. self.set_current_module(modname)
  820. if key == "fatal":
  821. message = str(error["ex"]).replace(os.getcwd() + os.sep, "")
  822. self.add_message(key, args=message)
  823. return result
  824. def set_current_module(self, modname: str, filepath: str | None = None) -> None:
  825. """Set the name of the currently analyzed module and
  826. init statistics for it.
  827. """
  828. if not modname and filepath is None:
  829. return
  830. self.reporter.on_set_current_module(modname or "", filepath)
  831. self.current_name = modname
  832. self.current_file = filepath or modname
  833. self.stats.init_single_module(modname or "")
  834. # If there is an actual filepath we might need to update the config attribute
  835. if filepath:
  836. namespace = self._get_namespace_for_file(
  837. Path(filepath), self._directory_namespaces
  838. )
  839. if namespace:
  840. self.config = namespace or self._base_config
  841. def _get_namespace_for_file(
  842. self, filepath: Path, namespaces: DirectoryNamespaceDict
  843. ) -> argparse.Namespace | None:
  844. for directory in namespaces:
  845. if Path.is_relative_to(filepath, directory):
  846. namespace = self._get_namespace_for_file(
  847. filepath, namespaces[directory][1]
  848. )
  849. if namespace is None:
  850. return namespaces[directory][0]
  851. return None
  852. @contextlib.contextmanager
  853. def _astroid_module_checker(
  854. self,
  855. ) -> Iterator[Callable[[nodes.Module], bool | None]]:
  856. """Context manager for checking ASTs.
  857. The value in the context is callable accepting AST as its only argument.
  858. """
  859. walker = ASTWalker(self)
  860. _checkers = self.prepare_checkers()
  861. tokencheckers = [
  862. c for c in _checkers if isinstance(c, checkers.BaseTokenChecker)
  863. ]
  864. rawcheckers = [
  865. c for c in _checkers if isinstance(c, checkers.BaseRawFileChecker)
  866. ]
  867. for checker in _checkers:
  868. checker.open()
  869. walker.add_checker(checker)
  870. yield functools.partial(
  871. self.check_astroid_module,
  872. walker=walker,
  873. tokencheckers=tokencheckers,
  874. rawcheckers=rawcheckers,
  875. )
  876. # notify global end
  877. self.stats.statement = walker.nbstatements
  878. for checker in reversed(_checkers):
  879. checker.close()
  880. def get_ast(
  881. self, filepath: str, modname: str, data: str | None = None
  882. ) -> nodes.Module | None:
  883. """Return an ast(roid) representation of a module or a string.
  884. :param filepath: path to checked file.
  885. :param str modname: The name of the module to be checked.
  886. :param str data: optional contents of the checked file.
  887. :returns: the AST
  888. :rtype: astroid.nodes.Module
  889. :raises AstroidBuildingError: Whenever we encounter an unexpected exception
  890. """
  891. try:
  892. if data is None:
  893. return MANAGER.ast_from_file(filepath, modname, source=True)
  894. return astroid.builder.AstroidBuilder(MANAGER).string_build(
  895. data, modname, filepath
  896. )
  897. except astroid.AstroidSyntaxError as ex:
  898. line = getattr(ex.error, "lineno", None)
  899. if line is None:
  900. line = 0
  901. self.add_message(
  902. "syntax-error",
  903. line=line,
  904. col_offset=getattr(ex.error, "offset", None),
  905. args=f"Parsing failed: '{ex.error}'",
  906. confidence=HIGH,
  907. )
  908. except astroid.AstroidBuildingError as ex:
  909. self.add_message("parse-error", args=ex)
  910. except Exception as ex:
  911. traceback.print_exc()
  912. # We raise BuildingError here as this is essentially an astroid issue
  913. # Creating an issue template and adding the 'astroid-error' message is handled
  914. # by caller: _check_files
  915. raise astroid.AstroidBuildingError(
  916. "Building error when trying to create ast representation of module '{modname}'",
  917. modname=modname,
  918. ) from ex
  919. return None
  920. def check_astroid_module(
  921. self,
  922. ast_node: nodes.Module,
  923. walker: ASTWalker,
  924. rawcheckers: list[checkers.BaseRawFileChecker],
  925. tokencheckers: list[checkers.BaseTokenChecker],
  926. ) -> bool | None:
  927. """Check a module from its astroid representation.
  928. For return value see _check_astroid_module
  929. """
  930. before_check_statements = walker.nbstatements
  931. retval = self._check_astroid_module(
  932. ast_node, walker, rawcheckers, tokencheckers
  933. )
  934. self.stats.by_module[self.current_name]["statement"] = (
  935. walker.nbstatements - before_check_statements
  936. )
  937. return retval
  938. def _check_astroid_module(
  939. self,
  940. node: nodes.Module,
  941. walker: ASTWalker,
  942. rawcheckers: list[checkers.BaseRawFileChecker],
  943. tokencheckers: list[checkers.BaseTokenChecker],
  944. ) -> bool | None:
  945. """Check given AST node with given walker and checkers.
  946. :param astroid.nodes.Module node: AST node of the module to check
  947. :param pylint.utils.ast_walker.ASTWalker walker: AST walker
  948. :param list rawcheckers: List of token checkers to use
  949. :param list tokencheckers: List of raw checkers to use
  950. :returns: True if the module was checked, False if ignored,
  951. None if the module contents could not be parsed
  952. """
  953. try:
  954. tokens = utils.tokenize_module(node)
  955. except tokenize.TokenError as ex:
  956. self.add_message(
  957. "syntax-error",
  958. line=ex.args[1][0],
  959. col_offset=ex.args[1][1],
  960. args=ex.args[0],
  961. confidence=HIGH,
  962. )
  963. return None
  964. if not node.pure_python:
  965. self.add_message("raw-checker-failed", args=node.name)
  966. else:
  967. # assert astroid.file.endswith('.py')
  968. # Parse module/block level option pragma's
  969. self.process_tokens(tokens)
  970. if self._ignore_file:
  971. return False
  972. # run raw and tokens checkers
  973. for raw_checker in rawcheckers:
  974. raw_checker.process_module(node)
  975. for token_checker in tokencheckers:
  976. token_checker.process_tokens(tokens)
  977. # generate events to astroid checkers
  978. walker.walk(node)
  979. return True
  980. def open(self) -> None:
  981. """Initialize counters."""
  982. MANAGER.always_load_extensions = self.config.unsafe_load_any_extension
  983. MANAGER.max_inferable_values = self.config.limit_inference_results
  984. MANAGER.extension_package_whitelist.update(self.config.extension_pkg_allow_list)
  985. MANAGER.module_denylist.update(self.config.ignored_modules)
  986. MANAGER.prefer_stubs = self.config.prefer_stubs
  987. if self.config.extension_pkg_whitelist:
  988. MANAGER.extension_package_whitelist.update(
  989. self.config.extension_pkg_whitelist
  990. )
  991. self.stats.reset_message_count()
  992. def generate_reports(self, verbose: bool = False) -> int | None:
  993. """Close the whole package /module, it's time to make reports !
  994. if persistent run, pickle results for later comparison
  995. """
  996. # Display whatever messages are left on the reporter.
  997. self.reporter.display_messages(report_nodes.Section())
  998. if not self.file_state._is_base_filestate:
  999. # load previous results if any
  1000. previous_stats = load_results(self.file_state.base_name)
  1001. self.reporter.on_close(self.stats, previous_stats)
  1002. if self.config.reports:
  1003. sect = self.make_reports(self.stats, previous_stats)
  1004. else:
  1005. sect = report_nodes.Section()
  1006. if self.config.reports:
  1007. self.reporter.display_reports(sect)
  1008. score_value = self._report_evaluation(verbose)
  1009. # save results if persistent run
  1010. if self.config.persistent:
  1011. save_results(self.stats, self.file_state.base_name)
  1012. else:
  1013. self.reporter.on_close(self.stats, LinterStats())
  1014. score_value = None
  1015. return score_value
  1016. def _report_evaluation(self, verbose: bool = False) -> int | None:
  1017. """Make the global evaluation report."""
  1018. # check with at least a statement (usually 0 when there is a
  1019. # syntax error preventing pylint from further processing)
  1020. note = None
  1021. previous_stats = load_results(self.file_state.base_name)
  1022. if self.stats.statement == 0:
  1023. return note
  1024. # get a global note for the code
  1025. evaluation = self.config.evaluation
  1026. try:
  1027. stats_dict = {
  1028. "fatal": self.stats.fatal,
  1029. "error": self.stats.error,
  1030. "warning": self.stats.warning,
  1031. "refactor": self.stats.refactor,
  1032. "convention": self.stats.convention,
  1033. "statement": self.stats.statement,
  1034. "info": self.stats.info,
  1035. }
  1036. note = eval(evaluation, {}, stats_dict) # pylint: disable=eval-used
  1037. except Exception as ex: # pylint: disable=broad-except
  1038. msg = f"An exception occurred while rating: {ex}"
  1039. else:
  1040. self.stats.global_note = note
  1041. msg = f"Your code has been rated at {note:.2f}/10"
  1042. if previous_stats:
  1043. pnote = previous_stats.global_note
  1044. if pnote is not None:
  1045. msg += f" (previous run: {pnote:.2f}/10, {note - pnote:+.2f})"
  1046. if verbose:
  1047. checked_files_count = self.stats.node_count["module"]
  1048. unchecked_files_count = self.stats.undocumented["module"]
  1049. checked_files = ", ".join(self.stats.modules_names)
  1050. msg += (
  1051. f"\nChecked {checked_files_count} files/modules ({checked_files}),"
  1052. f" skipped {unchecked_files_count} files/modules"
  1053. )
  1054. if self.config.score:
  1055. sect = report_nodes.EvaluationSection(msg)
  1056. self.reporter.display_reports(sect)
  1057. return note
  1058. def _add_one_message(
  1059. self,
  1060. message_definition: MessageDefinition,
  1061. line: int | None,
  1062. node: nodes.NodeNG | None,
  1063. args: Any | None,
  1064. confidence: interfaces.Confidence | None,
  1065. col_offset: int | None,
  1066. end_lineno: int | None,
  1067. end_col_offset: int | None,
  1068. ) -> None:
  1069. """After various checks have passed a single Message is
  1070. passed to the reporter and added to stats.
  1071. """
  1072. message_definition.check_message_definition(line, node)
  1073. # Look up "location" data of node if not yet supplied
  1074. if node:
  1075. if node.position:
  1076. if not line:
  1077. line = node.position.lineno
  1078. if not col_offset:
  1079. col_offset = node.position.col_offset
  1080. if not end_lineno:
  1081. end_lineno = node.position.end_lineno
  1082. if not end_col_offset:
  1083. end_col_offset = node.position.end_col_offset
  1084. else:
  1085. if not line:
  1086. line = node.fromlineno
  1087. if not col_offset:
  1088. col_offset = node.col_offset
  1089. if not end_lineno:
  1090. end_lineno = node.end_lineno
  1091. if not end_col_offset:
  1092. end_col_offset = node.end_col_offset
  1093. # should this message be displayed
  1094. if not self.is_message_enabled(message_definition.msgid, line, confidence):
  1095. self.file_state.handle_ignored_message(
  1096. self._get_message_state_scope(
  1097. message_definition.msgid, line, confidence
  1098. ),
  1099. message_definition.msgid,
  1100. line,
  1101. )
  1102. return
  1103. # update stats
  1104. msg_cat = MSG_TYPES[message_definition.msgid[0]]
  1105. self.msg_status |= MSG_TYPES_STATUS[message_definition.msgid[0]]
  1106. self.stats.increase_single_message_count(msg_cat, 1)
  1107. self.stats.increase_single_module_message_count(self.current_name, msg_cat, 1)
  1108. try:
  1109. self.stats.by_msg[message_definition.symbol] += 1
  1110. except KeyError:
  1111. self.stats.by_msg[message_definition.symbol] = 1
  1112. # Interpolate arguments into message string
  1113. msg = message_definition.msg
  1114. if args is not None:
  1115. msg %= args
  1116. # get module and object
  1117. if node is None:
  1118. module, obj = self.current_name, ""
  1119. abspath = self.current_file
  1120. else:
  1121. module, obj = utils.get_module_and_frameid(node)
  1122. abspath = node.root().file
  1123. if abspath is not None:
  1124. path = abspath.replace(self.reporter.path_strip_prefix, "", 1)
  1125. else:
  1126. path = "configuration"
  1127. # add the message
  1128. self.reporter.handle_message(
  1129. Message(
  1130. message_definition.msgid,
  1131. message_definition.symbol,
  1132. MessageLocationTuple(
  1133. abspath or "",
  1134. path,
  1135. module or "",
  1136. obj,
  1137. line or 1,
  1138. col_offset or 0,
  1139. end_lineno,
  1140. end_col_offset,
  1141. ),
  1142. msg,
  1143. confidence,
  1144. )
  1145. )
  1146. def add_message(
  1147. self,
  1148. msgid: str,
  1149. line: int | None = None,
  1150. node: nodes.NodeNG | None = None,
  1151. args: Any | None = None,
  1152. confidence: interfaces.Confidence | None = None,
  1153. col_offset: int | None = None,
  1154. end_lineno: int | None = None,
  1155. end_col_offset: int | None = None,
  1156. ) -> None:
  1157. """Adds a message given by ID or name.
  1158. If provided, the message string is expanded using args.
  1159. AST checkers must provide the node argument (but may optionally
  1160. provide line if the line number is different), raw and token checkers
  1161. must provide the line argument.
  1162. """
  1163. if confidence is None:
  1164. confidence = interfaces.UNDEFINED
  1165. message_definitions = self.msgs_store.get_message_definitions(msgid)
  1166. for message_definition in message_definitions:
  1167. self._add_one_message(
  1168. message_definition,
  1169. line,
  1170. node,
  1171. args,
  1172. confidence,
  1173. col_offset,
  1174. end_lineno,
  1175. end_col_offset,
  1176. )
  1177. def add_ignored_message(
  1178. self,
  1179. msgid: str,
  1180. line: int,
  1181. node: nodes.NodeNG | None = None,
  1182. confidence: interfaces.Confidence | None = interfaces.UNDEFINED,
  1183. ) -> None:
  1184. """Prepares a message to be added to the ignored message storage.
  1185. Some checks return early in special cases and never reach add_message(),
  1186. even though they would normally issue a message.
  1187. This creates false positives for useless-suppression.
  1188. This function avoids this by adding those message to the ignored msgs attribute
  1189. """
  1190. message_definitions = self.msgs_store.get_message_definitions(msgid)
  1191. for message_definition in message_definitions:
  1192. message_definition.check_message_definition(line, node)
  1193. self.file_state.handle_ignored_message(
  1194. self._get_message_state_scope(
  1195. message_definition.msgid, line, confidence
  1196. ),
  1197. message_definition.msgid,
  1198. line,
  1199. )
  1200. def _emit_stashed_messages(self) -> None:
  1201. for keys, values in self._stashed_messages.items():
  1202. modname, symbol = keys
  1203. self.linter.set_current_module(modname)
  1204. for args in values:
  1205. self.add_message(
  1206. symbol,
  1207. args=args,
  1208. line=0,
  1209. confidence=HIGH,
  1210. )
  1211. self._stashed_messages = collections.defaultdict(list)