pylinter.py 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702
  1. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  2. # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
  3. import collections
  4. import contextlib
  5. import functools
  6. import operator
  7. import os
  8. import sys
  9. import tokenize
  10. import traceback
  11. import warnings
  12. from io import TextIOWrapper
  13. from typing import Any, Dict, Iterable, Iterator, List, Optional, Sequence, Union
  14. import astroid
  15. from astroid import AstroidError, nodes
  16. from pylint import checkers, config, exceptions, interfaces, reporters
  17. from pylint.constants import (
  18. MAIN_CHECKER_NAME,
  19. MSG_STATE_CONFIDENCE,
  20. MSG_STATE_SCOPE_CONFIG,
  21. MSG_STATE_SCOPE_MODULE,
  22. MSG_TYPES,
  23. MSG_TYPES_LONG,
  24. MSG_TYPES_STATUS,
  25. )
  26. from pylint.lint.expand_modules import expand_modules
  27. from pylint.lint.parallel import check_parallel
  28. from pylint.lint.report_functions import (
  29. report_messages_by_module_stats,
  30. report_messages_stats,
  31. report_total_messages_stats,
  32. )
  33. from pylint.lint.utils import (
  34. fix_import_path,
  35. get_fatal_error_message,
  36. prepare_crash_report,
  37. )
  38. from pylint.message import Message, MessageDefinition, MessageDefinitionStore
  39. from pylint.reporters.ureports import nodes as report_nodes
  40. from pylint.typing import (
  41. FileItem,
  42. ManagedMessage,
  43. MessageLocationTuple,
  44. ModuleDescriptionDict,
  45. )
  46. from pylint.utils import ASTWalker, FileState, LinterStats, get_global_option, utils
  47. from pylint.utils.pragma_parser import (
  48. OPTION_PO,
  49. InvalidPragmaError,
  50. UnRecognizedOptionError,
  51. parse_pragma,
  52. )
  53. if sys.version_info >= (3, 8):
  54. from typing import Literal
  55. else:
  56. from typing_extensions import Literal
  57. MANAGER = astroid.MANAGER
  58. def _read_stdin():
  59. # https://mail.python.org/pipermail/python-list/2012-November/634424.html
  60. sys.stdin = TextIOWrapper(sys.stdin.detach(), encoding="utf-8")
  61. return sys.stdin.read()
  62. def _load_reporter_by_class(reporter_class: str) -> type:
  63. qname = reporter_class
  64. module_part = astroid.modutils.get_module_part(qname)
  65. module = astroid.modutils.load_module_from_name(module_part)
  66. class_name = qname.split(".")[-1]
  67. return getattr(module, class_name)
  68. # Python Linter class #########################################################
  69. MSGS = {
  70. "F0001": (
  71. "%s",
  72. "fatal",
  73. "Used when an error occurred preventing the analysis of a \
  74. module (unable to find it for instance).",
  75. ),
  76. "F0002": (
  77. "%s: %s",
  78. "astroid-error",
  79. "Used when an unexpected error occurred while building the "
  80. "Astroid representation. This is usually accompanied by a "
  81. "traceback. Please report such errors !",
  82. ),
  83. "F0010": (
  84. "error while code parsing: %s",
  85. "parse-error",
  86. "Used when an exception occurred while building the Astroid "
  87. "representation which could be handled by astroid.",
  88. ),
  89. "F0011": (
  90. "error while parsing the configuration: %s",
  91. "config-parse-error",
  92. "Used when an exception occurred while parsing a pylint configuration file.",
  93. ),
  94. "I0001": (
  95. "Unable to run raw checkers on built-in module %s",
  96. "raw-checker-failed",
  97. "Used to inform that a built-in module has not been checked "
  98. "using the raw checkers.",
  99. ),
  100. "I0010": (
  101. "Unable to consider inline option %r",
  102. "bad-inline-option",
  103. "Used when an inline option is either badly formatted or can't "
  104. "be used inside modules.",
  105. ),
  106. "I0011": (
  107. "Locally disabling %s (%s)",
  108. "locally-disabled",
  109. "Used when an inline option disables a message or a messages category.",
  110. ),
  111. "I0013": (
  112. "Ignoring entire file",
  113. "file-ignored",
  114. "Used to inform that the file will not be checked",
  115. ),
  116. "I0020": (
  117. "Suppressed %s (from line %d)",
  118. "suppressed-message",
  119. "A message was triggered on a line, but suppressed explicitly "
  120. "by a disable= comment in the file. This message is not "
  121. "generated for messages that are ignored due to configuration "
  122. "settings.",
  123. ),
  124. "I0021": (
  125. "Useless suppression of %s",
  126. "useless-suppression",
  127. "Reported when a message is explicitly disabled for a line or "
  128. "a block of code, but never triggered.",
  129. ),
  130. "I0022": (
  131. 'Pragma "%s" is deprecated, use "%s" instead',
  132. "deprecated-pragma",
  133. "Some inline pylint options have been renamed or reworked, "
  134. "only the most recent form should be used. "
  135. "NOTE:skip-all is only available with pylint >= 0.26",
  136. {"old_names": [("I0014", "deprecated-disable-all")]},
  137. ),
  138. "E0001": ("%s", "syntax-error", "Used when a syntax error is raised for a module."),
  139. "E0011": (
  140. "Unrecognized file option %r",
  141. "unrecognized-inline-option",
  142. "Used when an unknown inline option is encountered.",
  143. ),
  144. "E0012": (
  145. "Bad option value %r",
  146. "bad-option-value",
  147. "Used when a bad value for an inline option is encountered.",
  148. ),
  149. "E0013": (
  150. "Plugin '%s' is impossible to load, is it installed ? ('%s')",
  151. "bad-plugin-value",
  152. "Used when a bad value is used in 'load-plugins'.",
  153. ),
  154. "E0014": (
  155. "Out-of-place setting encountered in top level configuration-section '%s' : '%s'",
  156. "bad-configuration-section",
  157. "Used when we detect a setting in the top level of a toml configuration that shouldn't be there.",
  158. ),
  159. }
  160. # pylint: disable=too-many-instance-attributes,too-many-public-methods
  161. class PyLinter(
  162. config.OptionsManagerMixIn,
  163. reporters.ReportsHandlerMixIn,
  164. checkers.BaseTokenChecker,
  165. ):
  166. """lint Python modules using external checkers.
  167. This is the main checker controlling the other ones and the reports
  168. generation. It is itself both a raw checker and an astroid checker in order
  169. to:
  170. * handle message activation / deactivation at the module level
  171. * handle some basic but necessary stats'data (number of classes, methods...)
  172. IDE plugin developers: you may have to call
  173. `astroid.builder.MANAGER.astroid_cache.clear()` across runs if you want
  174. to ensure the latest code version is actually checked.
  175. This class needs to support pickling for parallel linting to work. The exception
  176. is reporter member; see check_parallel function for more details.
  177. """
  178. __implements__ = (interfaces.ITokenChecker,)
  179. name = MAIN_CHECKER_NAME
  180. priority = 0
  181. level = 0
  182. msgs = MSGS
  183. # Will be used like this : datetime.now().strftime(crash_file_path)
  184. crash_file_path: str = "pylint-crash-%Y-%m-%d-%H.txt"
  185. @staticmethod
  186. def make_options():
  187. return (
  188. (
  189. "ignore",
  190. {
  191. "type": "csv",
  192. "metavar": "<file>[,<file>...]",
  193. "dest": "black_list",
  194. "default": ("CVS",),
  195. "help": "Files or directories to be skipped. "
  196. "They should be base names, not paths.",
  197. },
  198. ),
  199. (
  200. "ignore-patterns",
  201. {
  202. "type": "regexp_csv",
  203. "metavar": "<pattern>[,<pattern>...]",
  204. "dest": "black_list_re",
  205. "default": (),
  206. "help": "Files or directories matching the regex patterns are"
  207. " skipped. The regex matches against base names, not paths.",
  208. },
  209. ),
  210. (
  211. "ignore-paths",
  212. {
  213. "type": "regexp_paths_csv",
  214. "metavar": "<pattern>[,<pattern>...]",
  215. "default": [],
  216. "help": "Add files or directories matching the regex patterns to the "
  217. "ignore-list. The regex matches against paths and can be in "
  218. "Posix or Windows format.",
  219. },
  220. ),
  221. (
  222. "persistent",
  223. {
  224. "default": True,
  225. "type": "yn",
  226. "metavar": "<y or n>",
  227. "level": 1,
  228. "help": "Pickle collected data for later comparisons.",
  229. },
  230. ),
  231. (
  232. "load-plugins",
  233. {
  234. "type": "csv",
  235. "metavar": "<modules>",
  236. "default": (),
  237. "level": 1,
  238. "help": "List of plugins (as comma separated values of "
  239. "python module names) to load, usually to register "
  240. "additional checkers.",
  241. },
  242. ),
  243. (
  244. "output-format",
  245. {
  246. "default": "text",
  247. "type": "string",
  248. "metavar": "<format>",
  249. "short": "f",
  250. "group": "Reports",
  251. "help": "Set the output format. Available formats are text,"
  252. " parseable, colorized, json and msvs (visual studio)."
  253. " You can also give a reporter class, e.g. mypackage.mymodule."
  254. "MyReporterClass.",
  255. },
  256. ),
  257. (
  258. "reports",
  259. {
  260. "default": False,
  261. "type": "yn",
  262. "metavar": "<y or n>",
  263. "short": "r",
  264. "group": "Reports",
  265. "help": "Tells whether to display a full report or only the "
  266. "messages.",
  267. },
  268. ),
  269. (
  270. "evaluation",
  271. {
  272. "type": "string",
  273. "metavar": "<python_expression>",
  274. "group": "Reports",
  275. "level": 1,
  276. "default": "10.0 - ((float(5 * error + warning + refactor + "
  277. "convention) / statement) * 10)",
  278. "help": "Python expression which should return a score less "
  279. "than or equal to 10. You have access to the variables "
  280. "'error', 'warning', 'refactor', and 'convention' which "
  281. "contain the number of messages in each category, as well as "
  282. "'statement' which is the total number of statements "
  283. "analyzed. This score is used by the global "
  284. "evaluation report (RP0004).",
  285. },
  286. ),
  287. (
  288. "score",
  289. {
  290. "default": True,
  291. "type": "yn",
  292. "metavar": "<y or n>",
  293. "short": "s",
  294. "group": "Reports",
  295. "help": "Activate the evaluation score.",
  296. },
  297. ),
  298. (
  299. "fail-under",
  300. {
  301. "default": 10,
  302. "type": "float",
  303. "metavar": "<score>",
  304. "help": "Specify a score threshold to be exceeded before program exits with error.",
  305. },
  306. ),
  307. (
  308. "fail-on",
  309. {
  310. "default": "",
  311. "type": "csv",
  312. "metavar": "<msg ids>",
  313. "help": "Return non-zero exit code if any of these messages/categories are detected,"
  314. " even if score is above --fail-under value. Syntax same as enable."
  315. " Messages specified are enabled, while categories only check already-enabled messages.",
  316. },
  317. ),
  318. (
  319. "confidence",
  320. {
  321. "type": "multiple_choice",
  322. "metavar": "<levels>",
  323. "default": "",
  324. "choices": [c.name for c in interfaces.CONFIDENCE_LEVELS],
  325. "group": "Messages control",
  326. "help": "Only show warnings with the listed confidence levels."
  327. f" Leave empty to show all. Valid levels: {', '.join(c.name for c in interfaces.CONFIDENCE_LEVELS)}.",
  328. },
  329. ),
  330. (
  331. "enable",
  332. {
  333. "type": "csv",
  334. "metavar": "<msg ids>",
  335. "short": "e",
  336. "group": "Messages control",
  337. "help": "Enable the message, report, category or checker with the "
  338. "given id(s). You can either give multiple identifier "
  339. "separated by comma (,) or put this option multiple time "
  340. "(only on the command line, not in the configuration file "
  341. "where it should appear only once). "
  342. 'See also the "--disable" option for examples.',
  343. },
  344. ),
  345. (
  346. "disable",
  347. {
  348. "type": "csv",
  349. "metavar": "<msg ids>",
  350. "short": "d",
  351. "group": "Messages control",
  352. "help": "Disable the message, report, category or checker "
  353. "with the given id(s). You can either give multiple identifiers "
  354. "separated by comma (,) or put this option multiple times "
  355. "(only on the command line, not in the configuration file "
  356. "where it should appear only once). "
  357. 'You can also use "--disable=all" to disable everything first '
  358. "and then reenable specific checks. For example, if you want "
  359. "to run only the similarities checker, you can use "
  360. '"--disable=all --enable=similarities". '
  361. "If you want to run only the classes checker, but have no "
  362. "Warning level messages displayed, use "
  363. '"--disable=all --enable=classes --disable=W".',
  364. },
  365. ),
  366. (
  367. "msg-template",
  368. {
  369. "type": "string",
  370. "metavar": "<template>",
  371. "group": "Reports",
  372. "help": (
  373. "Template used to display messages. "
  374. "This is a python new-style format string "
  375. "used to format the message information. "
  376. "See doc for all details."
  377. ),
  378. },
  379. ),
  380. (
  381. "jobs",
  382. {
  383. "type": "int",
  384. "metavar": "<n-processes>",
  385. "short": "j",
  386. "default": 1,
  387. "help": "Use multiple processes to speed up Pylint. Specifying 0 will "
  388. "auto-detect the number of processors available to use.",
  389. },
  390. ),
  391. (
  392. "unsafe-load-any-extension",
  393. {
  394. "type": "yn",
  395. "metavar": "<y or n>",
  396. "default": False,
  397. "hide": True,
  398. "help": (
  399. "Allow loading of arbitrary C extensions. Extensions"
  400. " are imported into the active Python interpreter and"
  401. " may run arbitrary code."
  402. ),
  403. },
  404. ),
  405. (
  406. "limit-inference-results",
  407. {
  408. "type": "int",
  409. "metavar": "<number-of-results>",
  410. "default": 100,
  411. "help": (
  412. "Control the amount of potential inferred values when inferring "
  413. "a single object. This can help the performance when dealing with "
  414. "large functions or complex, nested conditions. "
  415. ),
  416. },
  417. ),
  418. (
  419. "extension-pkg-allow-list",
  420. {
  421. "type": "csv",
  422. "metavar": "<pkg[,pkg]>",
  423. "default": [],
  424. "help": (
  425. "A comma-separated list of package or module names"
  426. " from where C extensions may be loaded. Extensions are"
  427. " loading into the active Python interpreter and may run"
  428. " arbitrary code."
  429. ),
  430. },
  431. ),
  432. (
  433. "extension-pkg-whitelist",
  434. {
  435. "type": "csv",
  436. "metavar": "<pkg[,pkg]>",
  437. "default": [],
  438. "help": (
  439. "A comma-separated list of package or module names"
  440. " from where C extensions may be loaded. Extensions are"
  441. " loading into the active Python interpreter and may run"
  442. " arbitrary code. (This is an alternative name to"
  443. " extension-pkg-allow-list for backward compatibility.)"
  444. ),
  445. },
  446. ),
  447. (
  448. "suggestion-mode",
  449. {
  450. "type": "yn",
  451. "metavar": "<y or n>",
  452. "default": True,
  453. "help": (
  454. "When enabled, pylint would attempt to guess common "
  455. "misconfiguration and emit user-friendly hints instead "
  456. "of false-positive error messages."
  457. ),
  458. },
  459. ),
  460. (
  461. "exit-zero",
  462. {
  463. "action": "store_true",
  464. "help": (
  465. "Always return a 0 (non-error) status code, even if "
  466. "lint errors are found. This is primarily useful in "
  467. "continuous integration scripts."
  468. ),
  469. },
  470. ),
  471. (
  472. "from-stdin",
  473. {
  474. "action": "store_true",
  475. "help": (
  476. "Interpret the stdin as a python script, whose filename "
  477. "needs to be passed as the module_or_package argument."
  478. ),
  479. },
  480. ),
  481. (
  482. "py-version",
  483. {
  484. "default": sys.version_info[:2],
  485. "type": "py_version",
  486. "metavar": "<py_version>",
  487. "help": (
  488. "Minimum Python version to use for version dependent checks. "
  489. "Will default to the version used to run pylint."
  490. ),
  491. },
  492. ),
  493. )
  494. option_groups = (
  495. ("Messages control", "Options controlling analysis messages"),
  496. ("Reports", "Options related to output formatting and reporting"),
  497. )
  498. def __init__(self, options=(), reporter=None, option_groups=(), pylintrc=None):
  499. """Some stuff has to be done before ancestors initialization...
  500. messages store / checkers / reporter / astroid manager"""
  501. self.msgs_store = MessageDefinitionStore()
  502. self.reporter = None
  503. self._reporter_names = None
  504. self._reporters = {}
  505. self._checkers = collections.defaultdict(list)
  506. self._pragma_lineno = {}
  507. self._ignore_file = False
  508. # visit variables
  509. self.file_state = FileState()
  510. self.current_name: Optional[str] = None
  511. self.current_file = None
  512. self.stats = LinterStats()
  513. self.fail_on_symbols = []
  514. # init options
  515. self._external_opts = options
  516. self.options = options + PyLinter.make_options()
  517. self.option_groups = option_groups + PyLinter.option_groups
  518. self._options_methods = {
  519. "enable": self.enable,
  520. "disable": self.disable,
  521. "disable-next": self.disable_next,
  522. }
  523. self._bw_options_methods = {
  524. "disable-msg": self._options_methods["disable"],
  525. "enable-msg": self._options_methods["enable"],
  526. }
  527. # Attributes related to message (state) handling
  528. self.msg_status = 0
  529. self._msgs_state: Dict[str, bool] = {}
  530. self._by_id_managed_msgs: List[ManagedMessage] = []
  531. reporters.ReportsHandlerMixIn.__init__(self)
  532. super().__init__(
  533. usage=__doc__,
  534. config_file=pylintrc or next(config.find_default_config_files(), None),
  535. )
  536. checkers.BaseTokenChecker.__init__(self)
  537. # provided reports
  538. self.reports = (
  539. ("RP0001", "Messages by category", report_total_messages_stats),
  540. (
  541. "RP0002",
  542. "% errors / warnings by module",
  543. report_messages_by_module_stats,
  544. ),
  545. ("RP0003", "Messages", report_messages_stats),
  546. )
  547. self.register_checker(self)
  548. self._dynamic_plugins = set()
  549. self._error_mode = False
  550. self.load_provider_defaults()
  551. if reporter:
  552. self.set_reporter(reporter)
  553. def load_default_plugins(self):
  554. checkers.initialize(self)
  555. reporters.initialize(self)
  556. # Make sure to load the default reporter, because
  557. # the option has been set before the plugins had been loaded.
  558. if not self.reporter:
  559. self._load_reporters()
  560. def load_plugin_modules(self, modnames):
  561. """take a list of module names which are pylint plugins and load
  562. and register them
  563. """
  564. for modname in modnames:
  565. if modname in self._dynamic_plugins:
  566. continue
  567. self._dynamic_plugins.add(modname)
  568. try:
  569. module = astroid.modutils.load_module_from_name(modname)
  570. module.register(self)
  571. except ModuleNotFoundError:
  572. pass
  573. def load_plugin_configuration(self):
  574. """Call the configuration hook for plugins
  575. This walks through the list of plugins, grabs the "load_configuration"
  576. hook, if exposed, and calls it to allow plugins to configure specific
  577. settings.
  578. """
  579. for modname in self._dynamic_plugins:
  580. try:
  581. module = astroid.modutils.load_module_from_name(modname)
  582. if hasattr(module, "load_configuration"):
  583. module.load_configuration(self)
  584. except ModuleNotFoundError as e:
  585. self.add_message("bad-plugin-value", args=(modname, e), line=0)
  586. def _load_reporters(self) -> None:
  587. sub_reporters = []
  588. output_files = []
  589. with contextlib.ExitStack() as stack:
  590. for reporter_name in self._reporter_names.split(","):
  591. reporter_name, *reporter_output = reporter_name.split(":", 1)
  592. reporter = self._load_reporter_by_name(reporter_name)
  593. sub_reporters.append(reporter)
  594. if reporter_output:
  595. (reporter_output,) = reporter_output
  596. output_file = stack.enter_context(
  597. open(reporter_output, "w", encoding="utf-8")
  598. )
  599. reporter.out = output_file
  600. output_files.append(output_file)
  601. # Extend the lifetime of all opened output files
  602. close_output_files = stack.pop_all().close
  603. if len(sub_reporters) > 1 or output_files:
  604. self.set_reporter(
  605. reporters.MultiReporter(
  606. sub_reporters,
  607. close_output_files,
  608. )
  609. )
  610. else:
  611. self.set_reporter(sub_reporters[0])
  612. def _load_reporter_by_name(self, reporter_name: str) -> reporters.BaseReporter:
  613. name = reporter_name.lower()
  614. if name in self._reporters:
  615. return self._reporters[name]()
  616. try:
  617. reporter_class = _load_reporter_by_class(reporter_name)
  618. except (ImportError, AttributeError) as e:
  619. raise exceptions.InvalidReporterError(name) from e
  620. else:
  621. return reporter_class()
  622. def set_reporter(self, reporter):
  623. """set the reporter used to display messages and reports"""
  624. self.reporter = reporter
  625. reporter.linter = self
  626. def set_option(self, optname, value, action=None, optdict=None):
  627. """overridden from config.OptionsProviderMixin to handle some
  628. special options
  629. """
  630. if optname in self._options_methods or optname in self._bw_options_methods:
  631. if value:
  632. try:
  633. meth = self._options_methods[optname]
  634. except KeyError:
  635. meth = self._bw_options_methods[optname]
  636. warnings.warn(
  637. f"{optname} is deprecated, replace it by {optname.split('-')[0]}",
  638. DeprecationWarning,
  639. )
  640. value = utils._check_csv(value)
  641. if isinstance(value, (list, tuple)):
  642. for _id in value:
  643. meth(_id, ignore_unknown=True)
  644. else:
  645. meth(value)
  646. return # no need to call set_option, disable/enable methods do it
  647. elif optname == "output-format":
  648. self._reporter_names = value
  649. # If the reporters are already available, load
  650. # the reporter class.
  651. if self._reporters:
  652. self._load_reporters()
  653. try:
  654. checkers.BaseTokenChecker.set_option(self, optname, value, action, optdict)
  655. except config.UnsupportedAction:
  656. print(f"option {optname} can't be read from config file", file=sys.stderr)
  657. def register_reporter(self, reporter_class):
  658. self._reporters[reporter_class.name] = reporter_class
  659. def report_order(self):
  660. reports = sorted(self._reports, key=lambda x: getattr(x, "name", ""))
  661. try:
  662. # Remove the current reporter and add it
  663. # at the end of the list.
  664. reports.pop(reports.index(self))
  665. except ValueError:
  666. pass
  667. else:
  668. reports.append(self)
  669. return reports
  670. # checkers manipulation methods ############################################
  671. def register_checker(self, checker):
  672. """register a new checker
  673. checker is an object implementing IRawChecker or / and IAstroidChecker
  674. """
  675. assert checker.priority <= 0, "checker priority can't be >= 0"
  676. self._checkers[checker.name].append(checker)
  677. for r_id, r_title, r_cb in checker.reports:
  678. self.register_report(r_id, r_title, r_cb, checker)
  679. self.register_options_provider(checker)
  680. if hasattr(checker, "msgs"):
  681. self.msgs_store.register_messages_from_checker(checker)
  682. checker.load_defaults()
  683. # Register the checker, but disable all of its messages.
  684. if not getattr(checker, "enabled", True):
  685. self.disable(checker.name)
  686. def enable_fail_on_messages(self):
  687. """enable 'fail on' msgs
  688. Convert values in config.fail_on (which might be msg category, msg id,
  689. or symbol) to specific msgs, then enable and flag them for later.
  690. """
  691. fail_on_vals = self.config.fail_on
  692. if not fail_on_vals:
  693. return
  694. fail_on_cats = set()
  695. fail_on_msgs = set()
  696. for val in fail_on_vals:
  697. # If value is a cateogry, add category, else add message
  698. if val in MSG_TYPES:
  699. fail_on_cats.add(val)
  700. else:
  701. fail_on_msgs.add(val)
  702. # For every message in every checker, if cat or msg flagged, enable check
  703. for all_checkers in self._checkers.values():
  704. for checker in all_checkers:
  705. for msg in checker.messages:
  706. if msg.msgid in fail_on_msgs or msg.symbol in fail_on_msgs:
  707. # message id/symbol matched, enable and flag it
  708. self.enable(msg.msgid)
  709. self.fail_on_symbols.append(msg.symbol)
  710. elif msg.msgid[0] in fail_on_cats:
  711. # message starts with a cateogry value, flag (but do not enable) it
  712. self.fail_on_symbols.append(msg.symbol)
  713. def any_fail_on_issues(self):
  714. return self.stats and any(
  715. x in self.fail_on_symbols for x in self.stats.by_msg.keys()
  716. )
  717. def disable_noerror_messages(self):
  718. for msgcat, msgids in self.msgs_store._msgs_by_category.items():
  719. # enable only messages with 'error' severity and above ('fatal')
  720. if msgcat in {"E", "F"}:
  721. for msgid in msgids:
  722. self.enable(msgid)
  723. else:
  724. for msgid in msgids:
  725. self.disable(msgid)
  726. def disable_reporters(self):
  727. """disable all reporters"""
  728. for _reporters in self._reports.values():
  729. for report_id, _, _ in _reporters:
  730. self.disable_report(report_id)
  731. def error_mode(self):
  732. """error mode: enable only errors; no reports, no persistent"""
  733. self._error_mode = True
  734. self.disable_noerror_messages()
  735. self.disable("miscellaneous")
  736. self.set_option("reports", False)
  737. self.set_option("persistent", False)
  738. self.set_option("score", False)
  739. def list_messages_enabled(self):
  740. emittable, non_emittable = self.msgs_store.find_emittable_messages()
  741. enabled = []
  742. disabled = []
  743. for message in emittable:
  744. if self.is_message_enabled(message.msgid):
  745. enabled.append(f" {message.symbol} ({message.msgid})")
  746. else:
  747. disabled.append(f" {message.symbol} ({message.msgid})")
  748. print("Enabled messages:")
  749. for msg in enabled:
  750. print(msg)
  751. print("\nDisabled messages:")
  752. for msg in disabled:
  753. print(msg)
  754. print("\nNon-emittable messages with current interpreter:")
  755. for msg in non_emittable:
  756. print(f" {msg.symbol} ({msg.msgid})")
  757. print("")
  758. # block level option handling #############################################
  759. # see func_block_disable_msg.py test case for expected behaviour
  760. def process_tokens(self, tokens):
  761. """Process tokens from the current module to search for module/block level
  762. options."""
  763. control_pragmas = {"disable", "disable-next", "enable"}
  764. prev_line = None
  765. saw_newline = True
  766. seen_newline = True
  767. for (tok_type, content, start, _, _) in tokens:
  768. if prev_line and prev_line != start[0]:
  769. saw_newline = seen_newline
  770. seen_newline = False
  771. prev_line = start[0]
  772. if tok_type in (tokenize.NL, tokenize.NEWLINE):
  773. seen_newline = True
  774. if tok_type != tokenize.COMMENT:
  775. continue
  776. match = OPTION_PO.search(content)
  777. if match is None:
  778. continue
  779. try:
  780. for pragma_repr in parse_pragma(match.group(2)):
  781. if pragma_repr.action in {"disable-all", "skip-file"}:
  782. if pragma_repr.action == "disable-all":
  783. self.add_message(
  784. "deprecated-pragma",
  785. line=start[0],
  786. args=("disable-all", "skip-file"),
  787. )
  788. self.add_message("file-ignored", line=start[0])
  789. self._ignore_file = True
  790. return
  791. try:
  792. meth = self._options_methods[pragma_repr.action]
  793. except KeyError:
  794. meth = self._bw_options_methods[pragma_repr.action]
  795. # found a "(dis|en)able-msg" pragma deprecated suppression
  796. self.add_message(
  797. "deprecated-pragma",
  798. line=start[0],
  799. args=(
  800. pragma_repr.action,
  801. pragma_repr.action.replace("-msg", ""),
  802. ),
  803. )
  804. for msgid in pragma_repr.messages:
  805. # Add the line where a control pragma was encountered.
  806. if pragma_repr.action in control_pragmas:
  807. self._pragma_lineno[msgid] = start[0]
  808. if (pragma_repr.action, msgid) == ("disable", "all"):
  809. self.add_message(
  810. "deprecated-pragma",
  811. line=start[0],
  812. args=("disable=all", "skip-file"),
  813. )
  814. self.add_message("file-ignored", line=start[0])
  815. self._ignore_file = True
  816. return
  817. # If we did not see a newline between the previous line and now,
  818. # we saw a backslash so treat the two lines as one.
  819. l_start = start[0]
  820. if not saw_newline:
  821. l_start -= 1
  822. try:
  823. meth(msgid, "module", l_start)
  824. except exceptions.UnknownMessageError:
  825. self.add_message(
  826. "bad-option-value", args=msgid, line=start[0]
  827. )
  828. except UnRecognizedOptionError as err:
  829. self.add_message(
  830. "unrecognized-inline-option", args=err.token, line=start[0]
  831. )
  832. continue
  833. except InvalidPragmaError as err:
  834. self.add_message("bad-inline-option", args=err.token, line=start[0])
  835. continue
  836. # code checking methods ###################################################
  837. def get_checkers(self):
  838. """return all available checkers as a list"""
  839. return [self] + [
  840. c
  841. for _checkers in self._checkers.values()
  842. for c in _checkers
  843. if c is not self
  844. ]
  845. def get_checker_names(self):
  846. """Get all the checker names that this linter knows about."""
  847. current_checkers = self.get_checkers()
  848. return sorted(
  849. {
  850. checker.name
  851. for checker in current_checkers
  852. if checker.name != MAIN_CHECKER_NAME
  853. }
  854. )
  855. def prepare_checkers(self):
  856. """return checkers needed for activated messages and reports"""
  857. if not self.config.reports:
  858. self.disable_reporters()
  859. # get needed checkers
  860. needed_checkers = [self]
  861. for checker in self.get_checkers()[1:]:
  862. messages = {msg for msg in checker.msgs if self.is_message_enabled(msg)}
  863. if messages or any(self.report_is_enabled(r[0]) for r in checker.reports):
  864. needed_checkers.append(checker)
  865. # Sort checkers by priority
  866. needed_checkers = sorted(
  867. needed_checkers, key=operator.attrgetter("priority"), reverse=True
  868. )
  869. return needed_checkers
  870. # pylint: disable=unused-argument
  871. @staticmethod
  872. def should_analyze_file(modname, path, is_argument=False):
  873. """Returns whether or not a module should be checked.
  874. This implementation returns True for all python source file, indicating
  875. that all files should be linted.
  876. Subclasses may override this method to indicate that modules satisfying
  877. certain conditions should not be linted.
  878. :param str modname: The name of the module to be checked.
  879. :param str path: The full path to the source code of the module.
  880. :param bool is_argument: Whether the file is an argument to pylint or not.
  881. Files which respect this property are always
  882. checked, since the user requested it explicitly.
  883. :returns: True if the module should be checked.
  884. :rtype: bool
  885. """
  886. if is_argument:
  887. return True
  888. return path.endswith(".py")
  889. # pylint: enable=unused-argument
  890. def initialize(self):
  891. """Initialize linter for linting
  892. This method is called before any linting is done.
  893. """
  894. # initialize msgs_state now that all messages have been registered into
  895. # the store
  896. for msg in self.msgs_store.messages:
  897. if not msg.may_be_emitted():
  898. self._msgs_state[msg.msgid] = False
  899. def check(self, files_or_modules: Union[Sequence[str], str]) -> None:
  900. """main checking entry: check a list of files or modules from their name.
  901. files_or_modules is either a string or list of strings presenting modules to check.
  902. """
  903. self.initialize()
  904. if not isinstance(files_or_modules, (list, tuple)):
  905. # pylint: disable-next=fixme
  906. # TODO: Update typing and docstring for 'files_or_modules' when removing the deprecation
  907. warnings.warn(
  908. "In pylint 3.0, the checkers check function will only accept sequence of string",
  909. DeprecationWarning,
  910. )
  911. files_or_modules = (files_or_modules,) # type: ignore[assignment]
  912. if self.config.from_stdin:
  913. if len(files_or_modules) != 1:
  914. raise exceptions.InvalidArgsError(
  915. "Missing filename required for --from-stdin"
  916. )
  917. filepath = files_or_modules[0]
  918. with fix_import_path(files_or_modules):
  919. self._check_files(
  920. functools.partial(self.get_ast, data=_read_stdin()),
  921. [self._get_file_descr_from_stdin(filepath)],
  922. )
  923. elif self.config.jobs == 1:
  924. with fix_import_path(files_or_modules):
  925. self._check_files(
  926. self.get_ast, self._iterate_file_descrs(files_or_modules)
  927. )
  928. else:
  929. check_parallel(
  930. self,
  931. self.config.jobs,
  932. self._iterate_file_descrs(files_or_modules),
  933. files_or_modules,
  934. )
  935. def check_single_file(self, name: str, filepath: str, modname: str) -> None:
  936. warnings.warn(
  937. "In pylint 3.0, the checkers check_single_file function will be removed. "
  938. "Use check_single_file_item instead.",
  939. DeprecationWarning,
  940. )
  941. self.check_single_file_item(FileItem(name, filepath, modname))
  942. def check_single_file_item(self, file: FileItem) -> None:
  943. """Check single file item
  944. The arguments are the same that are documented in _check_files
  945. The initialize() method should be called before calling this method
  946. """
  947. with self._astroid_module_checker() as check_astroid_module:
  948. self._check_file(self.get_ast, check_astroid_module, file)
  949. def _check_files(
  950. self,
  951. get_ast,
  952. file_descrs: Iterable[FileItem],
  953. ) -> None:
  954. """Check all files from file_descrs"""
  955. with self._astroid_module_checker() as check_astroid_module:
  956. for file in file_descrs:
  957. try:
  958. self._check_file(get_ast, check_astroid_module, file)
  959. except Exception as ex: # pylint: disable=broad-except
  960. template_path = prepare_crash_report(
  961. ex, file.filepath, self.crash_file_path
  962. )
  963. msg = get_fatal_error_message(file.filepath, template_path)
  964. if isinstance(ex, AstroidError):
  965. symbol = "astroid-error"
  966. self.add_message(symbol, args=(file.filepath, msg))
  967. else:
  968. symbol = "fatal"
  969. self.add_message(symbol, args=msg)
  970. def _check_file(self, get_ast, check_astroid_module, file: FileItem):
  971. """Check a file using the passed utility functions (get_ast and check_astroid_module)
  972. :param callable get_ast: callable returning AST from defined file taking the following arguments
  973. - filepath: path to the file to check
  974. - name: Python module name
  975. :param callable check_astroid_module: callable checking an AST taking the following arguments
  976. - ast: AST of the module
  977. :param FileItem file: data about the file
  978. """
  979. self.set_current_module(file.name, file.filepath)
  980. # get the module representation
  981. ast_node = get_ast(file.filepath, file.name)
  982. if ast_node is None:
  983. return
  984. self._ignore_file = False
  985. self.file_state = FileState(file.modpath)
  986. # fix the current file (if the source file was not available or
  987. # if it's actually a c extension)
  988. self.current_file = ast_node.file
  989. check_astroid_module(ast_node)
  990. # warn about spurious inline messages handling
  991. spurious_messages = self.file_state.iter_spurious_suppression_messages(
  992. self.msgs_store
  993. )
  994. for msgid, line, args in spurious_messages:
  995. self.add_message(msgid, line, None, args)
  996. @staticmethod
  997. def _get_file_descr_from_stdin(filepath: str) -> FileItem:
  998. """Return file description (tuple of module name, file path, base name) from given file path
  999. This method is used for creating suitable file description for _check_files when the
  1000. source is standard input.
  1001. """
  1002. try:
  1003. # Note that this function does not really perform an
  1004. # __import__ but may raise an ImportError exception, which
  1005. # we want to catch here.
  1006. modname = ".".join(astroid.modutils.modpath_from_file(filepath))
  1007. except ImportError:
  1008. modname = os.path.splitext(os.path.basename(filepath))[0]
  1009. return FileItem(modname, filepath, filepath)
  1010. def _iterate_file_descrs(self, files_or_modules) -> Iterator[FileItem]:
  1011. """Return generator yielding file descriptions (tuples of module name, file path, base name)
  1012. The returned generator yield one item for each Python module that should be linted.
  1013. """
  1014. for descr in self._expand_files(files_or_modules):
  1015. name, filepath, is_arg = descr["name"], descr["path"], descr["isarg"]
  1016. if self.should_analyze_file(name, filepath, is_argument=is_arg):
  1017. yield FileItem(name, filepath, descr["basename"])
  1018. def _expand_files(self, modules) -> List[ModuleDescriptionDict]:
  1019. """get modules and errors from a list of modules and handle errors"""
  1020. result, errors = expand_modules(
  1021. modules,
  1022. self.config.black_list,
  1023. self.config.black_list_re,
  1024. self._ignore_paths,
  1025. )
  1026. for error in errors:
  1027. message = modname = error["mod"]
  1028. key = error["key"]
  1029. self.set_current_module(modname)
  1030. if key == "fatal":
  1031. message = str(error["ex"]).replace(os.getcwd() + os.sep, "")
  1032. self.add_message(key, args=message)
  1033. return result
  1034. def set_current_module(self, modname, filepath: Optional[str] = None):
  1035. """set the name of the currently analyzed module and
  1036. init statistics for it
  1037. """
  1038. if not modname and filepath is None:
  1039. return
  1040. self.reporter.on_set_current_module(modname, filepath)
  1041. self.current_name = modname
  1042. self.current_file = filepath or modname
  1043. self.stats.init_single_module(modname)
  1044. @contextlib.contextmanager
  1045. def _astroid_module_checker(self):
  1046. """Context manager for checking ASTs
  1047. The value in the context is callable accepting AST as its only argument.
  1048. """
  1049. walker = ASTWalker(self)
  1050. _checkers = self.prepare_checkers()
  1051. tokencheckers = [
  1052. c
  1053. for c in _checkers
  1054. if interfaces.implements(c, interfaces.ITokenChecker) and c is not self
  1055. ]
  1056. rawcheckers = [
  1057. c for c in _checkers if interfaces.implements(c, interfaces.IRawChecker)
  1058. ]
  1059. # notify global begin
  1060. for checker in _checkers:
  1061. checker.open()
  1062. if interfaces.implements(checker, interfaces.IAstroidChecker):
  1063. walker.add_checker(checker)
  1064. yield functools.partial(
  1065. self.check_astroid_module,
  1066. walker=walker,
  1067. tokencheckers=tokencheckers,
  1068. rawcheckers=rawcheckers,
  1069. )
  1070. # notify global end
  1071. self.stats.statement = walker.nbstatements
  1072. for checker in reversed(_checkers):
  1073. checker.close()
  1074. def get_ast(self, filepath, modname, data=None):
  1075. """Return an ast(roid) representation of a module or a string.
  1076. :param str filepath: path to checked file.
  1077. :param str modname: The name of the module to be checked.
  1078. :param str data: optional contents of the checked file.
  1079. :returns: the AST
  1080. :rtype: astroid.nodes.Module
  1081. """
  1082. try:
  1083. if data is None:
  1084. return MANAGER.ast_from_file(filepath, modname, source=True)
  1085. return astroid.builder.AstroidBuilder(MANAGER).string_build(
  1086. data, modname, filepath
  1087. )
  1088. except astroid.AstroidSyntaxError as ex:
  1089. # pylint: disable=no-member
  1090. self.add_message(
  1091. "syntax-error",
  1092. line=getattr(ex.error, "lineno", 0),
  1093. col_offset=getattr(ex.error, "offset", None),
  1094. args=str(ex.error),
  1095. )
  1096. except astroid.AstroidBuildingException as ex:
  1097. self.add_message("parse-error", args=ex)
  1098. except Exception as ex: # pylint: disable=broad-except
  1099. traceback.print_exc()
  1100. self.add_message("astroid-error", args=(ex.__class__, ex))
  1101. return None
  1102. def check_astroid_module(self, ast_node, walker, rawcheckers, tokencheckers):
  1103. """Check a module from its astroid representation.
  1104. For return value see _check_astroid_module
  1105. """
  1106. before_check_statements = walker.nbstatements
  1107. retval = self._check_astroid_module(
  1108. ast_node, walker, rawcheckers, tokencheckers
  1109. )
  1110. self.stats.by_module[self.current_name]["statement"] = (
  1111. walker.nbstatements - before_check_statements
  1112. )
  1113. return retval
  1114. def _check_astroid_module(
  1115. self, node: nodes.Module, walker, rawcheckers, tokencheckers
  1116. ):
  1117. """Check given AST node with given walker and checkers
  1118. :param astroid.nodes.Module node: AST node of the module to check
  1119. :param pylint.utils.ast_walker.ASTWalker walker: AST walker
  1120. :param list rawcheckers: List of token checkers to use
  1121. :param list tokencheckers: List of raw checkers to use
  1122. :returns: True if the module was checked, False if ignored,
  1123. None if the module contents could not be parsed
  1124. :rtype: bool
  1125. """
  1126. try:
  1127. tokens = utils.tokenize_module(node)
  1128. except tokenize.TokenError as ex:
  1129. self.add_message("syntax-error", line=ex.args[1][0], args=ex.args[0])
  1130. return None
  1131. if not node.pure_python:
  1132. self.add_message("raw-checker-failed", args=node.name)
  1133. else:
  1134. # assert astroid.file.endswith('.py')
  1135. # invoke ITokenChecker interface on self to fetch module/block
  1136. # level options
  1137. self.process_tokens(tokens)
  1138. if self._ignore_file:
  1139. return False
  1140. # walk ast to collect line numbers
  1141. self.file_state.collect_block_lines(self.msgs_store, node)
  1142. # run raw and tokens checkers
  1143. for checker in rawcheckers:
  1144. checker.process_module(node)
  1145. for checker in tokencheckers:
  1146. checker.process_tokens(tokens)
  1147. # generate events to astroid checkers
  1148. walker.walk(node)
  1149. return True
  1150. # IAstroidChecker interface #################################################
  1151. def open(self):
  1152. """initialize counters"""
  1153. self.stats = LinterStats()
  1154. MANAGER.always_load_extensions = self.config.unsafe_load_any_extension
  1155. MANAGER.max_inferable_values = self.config.limit_inference_results
  1156. MANAGER.extension_package_whitelist.update(self.config.extension_pkg_allow_list)
  1157. if self.config.extension_pkg_whitelist:
  1158. MANAGER.extension_package_whitelist.update(
  1159. self.config.extension_pkg_whitelist
  1160. )
  1161. self.stats.reset_message_count()
  1162. self._ignore_paths = get_global_option(self, "ignore-paths")
  1163. def generate_reports(self):
  1164. """close the whole package /module, it's time to make reports !
  1165. if persistent run, pickle results for later comparison
  1166. """
  1167. # Display whatever messages are left on the reporter.
  1168. self.reporter.display_messages(report_nodes.Section())
  1169. if self.file_state.base_name is not None:
  1170. # load previous results if any
  1171. previous_stats = config.load_results(self.file_state.base_name)
  1172. self.reporter.on_close(self.stats, previous_stats)
  1173. if self.config.reports:
  1174. sect = self.make_reports(self.stats, previous_stats)
  1175. else:
  1176. sect = report_nodes.Section()
  1177. if self.config.reports:
  1178. self.reporter.display_reports(sect)
  1179. score_value = self._report_evaluation()
  1180. # save results if persistent run
  1181. if self.config.persistent:
  1182. config.save_results(self.stats, self.file_state.base_name)
  1183. else:
  1184. self.reporter.on_close(self.stats, LinterStats())
  1185. score_value = None
  1186. return score_value
  1187. def _report_evaluation(self):
  1188. """make the global evaluation report"""
  1189. # check with at least check 1 statements (usually 0 when there is a
  1190. # syntax error preventing pylint from further processing)
  1191. note = None
  1192. previous_stats = config.load_results(self.file_state.base_name)
  1193. if self.stats.statement == 0:
  1194. return note
  1195. # get a global note for the code
  1196. evaluation = self.config.evaluation
  1197. try:
  1198. stats_dict = {
  1199. "error": self.stats.error,
  1200. "warning": self.stats.warning,
  1201. "refactor": self.stats.refactor,
  1202. "convention": self.stats.convention,
  1203. "statement": self.stats.statement,
  1204. "info": self.stats.info,
  1205. }
  1206. note = eval(evaluation, {}, stats_dict) # pylint: disable=eval-used
  1207. except Exception as ex: # pylint: disable=broad-except
  1208. msg = f"An exception occurred while rating: {ex}"
  1209. else:
  1210. self.stats.global_note = note
  1211. msg = f"Your code has been rated at {note:.2f}/10"
  1212. if previous_stats:
  1213. pnote = previous_stats.global_note
  1214. if pnote is not None:
  1215. msg += f" (previous run: {pnote:.2f}/10, {note - pnote:+.2f})"
  1216. if self.config.score:
  1217. sect = report_nodes.EvaluationSection(msg)
  1218. self.reporter.display_reports(sect)
  1219. return note
  1220. # Adding (ignored) messages to the Message Reporter
  1221. def _get_message_state_scope(
  1222. self,
  1223. msgid: str,
  1224. line: Optional[int] = None,
  1225. confidence: Optional[interfaces.Confidence] = None,
  1226. ) -> Optional[Literal[0, 1, 2]]:
  1227. """Returns the scope at which a message was enabled/disabled."""
  1228. if confidence is None:
  1229. confidence = interfaces.UNDEFINED
  1230. if self.config.confidence and confidence.name not in self.config.confidence:
  1231. return MSG_STATE_CONFIDENCE # type: ignore[return-value] # mypy does not infer Literal correctly
  1232. try:
  1233. if line in self.file_state._module_msgs_state[msgid]:
  1234. return MSG_STATE_SCOPE_MODULE # type: ignore[return-value]
  1235. except (KeyError, TypeError):
  1236. return MSG_STATE_SCOPE_CONFIG # type: ignore[return-value]
  1237. return None
  1238. def _is_one_message_enabled(self, msgid: str, line: Optional[int]) -> bool:
  1239. """Checks state of a single message"""
  1240. if line is None:
  1241. return self._msgs_state.get(msgid, True)
  1242. try:
  1243. return self.file_state._module_msgs_state[msgid][line]
  1244. except KeyError:
  1245. # Check if the message's line is after the maximum line existing in ast tree.
  1246. # This line won't appear in the ast tree and won't be referred in
  1247. # self.file_state._module_msgs_state
  1248. # This happens for example with a commented line at the end of a module.
  1249. max_line_number = self.file_state.get_effective_max_line_number()
  1250. if max_line_number and line > max_line_number:
  1251. fallback = True
  1252. lines = self.file_state._raw_module_msgs_state.get(msgid, {})
  1253. # Doesn't consider scopes, as a disable can be in a different scope
  1254. # than that of the current line.
  1255. closest_lines = reversed(
  1256. [
  1257. (message_line, enable)
  1258. for message_line, enable in lines.items()
  1259. if message_line <= line
  1260. ]
  1261. )
  1262. _, fallback_iter = next(closest_lines, (None, None))
  1263. if fallback_iter is not None:
  1264. fallback = fallback_iter
  1265. return self._msgs_state.get(msgid, fallback)
  1266. return self._msgs_state.get(msgid, True)
  1267. def is_message_enabled(
  1268. self,
  1269. msg_descr: str,
  1270. line: Optional[int] = None,
  1271. confidence: Optional[interfaces.Confidence] = None,
  1272. ) -> bool:
  1273. """return whether the message associated to the given message id is
  1274. enabled
  1275. msgid may be either a numeric or symbolic message id.
  1276. """
  1277. if self.config.confidence and confidence:
  1278. if confidence.name not in self.config.confidence:
  1279. return False
  1280. try:
  1281. message_definitions = self.msgs_store.get_message_definitions(msg_descr)
  1282. msgids = [md.msgid for md in message_definitions]
  1283. except exceptions.UnknownMessageError:
  1284. # The linter checks for messages that are not registered
  1285. # due to version mismatch, just treat them as message IDs
  1286. # for now.
  1287. msgids = [msg_descr]
  1288. return any(self._is_one_message_enabled(msgid, line) for msgid in msgids)
  1289. def _add_one_message(
  1290. self,
  1291. message_definition: MessageDefinition,
  1292. line: Optional[int],
  1293. node: Optional[nodes.NodeNG],
  1294. args: Optional[Any],
  1295. confidence: Optional[interfaces.Confidence],
  1296. col_offset: Optional[int],
  1297. end_lineno: Optional[int],
  1298. end_col_offset: Optional[int],
  1299. ) -> None:
  1300. """After various checks have passed a single Message is
  1301. passed to the reporter and added to stats"""
  1302. message_definition.check_message_definition(line, node)
  1303. # Look up "location" data of node if not yet supplied
  1304. if node:
  1305. if not line:
  1306. line = node.fromlineno
  1307. # pylint: disable=fixme
  1308. # TODO: Initialize col_offset on every node (can be None) -> astroid
  1309. if not col_offset and hasattr(node, "col_offset"):
  1310. col_offset = node.col_offset
  1311. # pylint: disable=fixme
  1312. # TODO: Initialize end_lineno on every node (can be None) -> astroid
  1313. # See https://github.com/PyCQA/astroid/issues/1273
  1314. if not end_lineno and hasattr(node, "end_lineno"):
  1315. end_lineno = node.end_lineno
  1316. # pylint: disable=fixme
  1317. # TODO: Initialize end_col_offset on every node (can be None) -> astroid
  1318. if not end_col_offset and hasattr(node, "end_col_offset"):
  1319. end_col_offset = node.end_col_offset
  1320. # should this message be displayed
  1321. if not self.is_message_enabled(message_definition.msgid, line, confidence):
  1322. self.file_state.handle_ignored_message(
  1323. self._get_message_state_scope(
  1324. message_definition.msgid, line, confidence
  1325. ),
  1326. message_definition.msgid,
  1327. line,
  1328. )
  1329. return
  1330. # update stats
  1331. msg_cat = MSG_TYPES[message_definition.msgid[0]]
  1332. self.msg_status |= MSG_TYPES_STATUS[message_definition.msgid[0]]
  1333. self.stats.increase_single_message_count(msg_cat, 1)
  1334. self.stats.increase_single_module_message_count(self.current_name, msg_cat, 1)
  1335. try:
  1336. self.stats.by_msg[message_definition.symbol] += 1
  1337. except KeyError:
  1338. self.stats.by_msg[message_definition.symbol] = 1
  1339. # Interpolate arguments into message string
  1340. msg = message_definition.msg
  1341. if args:
  1342. msg %= args
  1343. # get module and object
  1344. if node is None:
  1345. module, obj = self.current_name, ""
  1346. abspath = self.current_file
  1347. else:
  1348. module, obj = utils.get_module_and_frameid(node)
  1349. abspath = node.root().file
  1350. if abspath is not None:
  1351. path = abspath.replace(self.reporter.path_strip_prefix, "", 1)
  1352. else:
  1353. path = "configuration"
  1354. # add the message
  1355. self.reporter.handle_message(
  1356. Message(
  1357. message_definition.msgid,
  1358. message_definition.symbol,
  1359. MessageLocationTuple(
  1360. abspath,
  1361. path,
  1362. module or "",
  1363. obj,
  1364. line or 1,
  1365. col_offset or 0,
  1366. end_lineno,
  1367. end_col_offset,
  1368. ),
  1369. msg,
  1370. confidence,
  1371. )
  1372. )
  1373. def add_message(
  1374. self,
  1375. msgid: str,
  1376. line: Optional[int] = None,
  1377. node: Optional[nodes.NodeNG] = None,
  1378. args: Optional[Any] = None,
  1379. confidence: Optional[interfaces.Confidence] = None,
  1380. col_offset: Optional[int] = None,
  1381. end_lineno: Optional[int] = None,
  1382. end_col_offset: Optional[int] = None,
  1383. ) -> None:
  1384. """Adds a message given by ID or name.
  1385. If provided, the message string is expanded using args.
  1386. AST checkers must provide the node argument (but may optionally
  1387. provide line if the line number is different), raw and token checkers
  1388. must provide the line argument.
  1389. """
  1390. if confidence is None:
  1391. confidence = interfaces.UNDEFINED
  1392. message_definitions = self.msgs_store.get_message_definitions(msgid)
  1393. for message_definition in message_definitions:
  1394. self._add_one_message(
  1395. message_definition,
  1396. line,
  1397. node,
  1398. args,
  1399. confidence,
  1400. col_offset,
  1401. end_lineno,
  1402. end_col_offset,
  1403. )
  1404. def add_ignored_message(
  1405. self,
  1406. msgid: str,
  1407. line: int,
  1408. node: Optional[nodes.NodeNG] = None,
  1409. confidence: Optional[interfaces.Confidence] = interfaces.UNDEFINED,
  1410. ) -> None:
  1411. """Prepares a message to be added to the ignored message storage
  1412. Some checks return early in special cases and never reach add_message(),
  1413. even though they would normally issue a message.
  1414. This creates false positives for useless-suppression.
  1415. This function avoids this by adding those message to the ignored msgs attribute
  1416. """
  1417. message_definitions = self.msgs_store.get_message_definitions(msgid)
  1418. for message_definition in message_definitions:
  1419. message_definition.check_message_definition(line, node)
  1420. self.file_state.handle_ignored_message(
  1421. self._get_message_state_scope(
  1422. message_definition.msgid, line, confidence
  1423. ),
  1424. message_definition.msgid,
  1425. line,
  1426. )
  1427. # Setting the state (disabled/enabled) of messages and registering them
  1428. def _message_symbol(self, msgid: str) -> List[str]:
  1429. """Get the message symbol of the given message id
  1430. Return the original message id if the message does not
  1431. exist.
  1432. """
  1433. try:
  1434. return [md.symbol for md in self.msgs_store.get_message_definitions(msgid)]
  1435. except exceptions.UnknownMessageError:
  1436. return [msgid]
  1437. def _set_one_msg_status(
  1438. self, scope: str, msg: MessageDefinition, line: Optional[int], enable: bool
  1439. ) -> None:
  1440. """Set the status of an individual message"""
  1441. if scope == "module":
  1442. self.file_state.set_msg_status(msg, line, enable)
  1443. if not enable and msg.symbol != "locally-disabled":
  1444. self.add_message(
  1445. "locally-disabled", line=line, args=(msg.symbol, msg.msgid)
  1446. )
  1447. else:
  1448. msgs = self._msgs_state
  1449. msgs[msg.msgid] = enable
  1450. # sync configuration object
  1451. self.config.enable = [
  1452. self._message_symbol(mid) for mid, val in sorted(msgs.items()) if val
  1453. ]
  1454. self.config.disable = [
  1455. self._message_symbol(mid)
  1456. for mid, val in sorted(msgs.items())
  1457. if not val
  1458. ]
  1459. def _set_msg_status(
  1460. self,
  1461. msgid: str,
  1462. enable: bool,
  1463. scope: str = "package",
  1464. line: Optional[int] = None,
  1465. ignore_unknown: bool = False,
  1466. ) -> None:
  1467. """Do some tests and then iterate over message defintions to set state"""
  1468. assert scope in {"package", "module"}
  1469. if msgid == "all":
  1470. for _msgid in MSG_TYPES:
  1471. self._set_msg_status(_msgid, enable, scope, line, ignore_unknown)
  1472. return
  1473. # msgid is a category?
  1474. category_id = msgid.upper()
  1475. if category_id not in MSG_TYPES:
  1476. category_id_formatted = MSG_TYPES_LONG.get(category_id)
  1477. else:
  1478. category_id_formatted = category_id
  1479. if category_id_formatted is not None:
  1480. for _msgid in self.msgs_store._msgs_by_category.get(category_id_formatted):
  1481. self._set_msg_status(_msgid, enable, scope, line)
  1482. return
  1483. # msgid is a checker name?
  1484. if msgid.lower() in self._checkers:
  1485. for checker in self._checkers[msgid.lower()]:
  1486. for _msgid in checker.msgs:
  1487. self._set_msg_status(_msgid, enable, scope, line)
  1488. return
  1489. # msgid is report id?
  1490. if msgid.lower().startswith("rp"):
  1491. if enable:
  1492. self.enable_report(msgid)
  1493. else:
  1494. self.disable_report(msgid)
  1495. return
  1496. try:
  1497. # msgid is a symbolic or numeric msgid.
  1498. message_definitions = self.msgs_store.get_message_definitions(msgid)
  1499. except exceptions.UnknownMessageError:
  1500. if ignore_unknown:
  1501. return
  1502. raise
  1503. for message_definition in message_definitions:
  1504. self._set_one_msg_status(scope, message_definition, line, enable)
  1505. def _register_by_id_managed_msg(
  1506. self, msgid_or_symbol: str, line: Optional[int], is_disabled: bool = True
  1507. ) -> None:
  1508. """If the msgid is a numeric one, then register it to inform the user
  1509. it could furnish instead a symbolic msgid."""
  1510. if msgid_or_symbol[1:].isdigit():
  1511. try:
  1512. symbol = self.msgs_store.message_id_store.get_symbol(
  1513. msgid=msgid_or_symbol
  1514. )
  1515. except exceptions.UnknownMessageError:
  1516. return
  1517. managed = ManagedMessage(
  1518. self.current_name, msgid_or_symbol, symbol, line, is_disabled
  1519. )
  1520. self._by_id_managed_msgs.append(managed)
  1521. def disable(
  1522. self,
  1523. msgid: str,
  1524. scope: str = "package",
  1525. line: Optional[int] = None,
  1526. ignore_unknown: bool = False,
  1527. ) -> None:
  1528. """Disable a message for a scope"""
  1529. self._set_msg_status(
  1530. msgid, enable=False, scope=scope, line=line, ignore_unknown=ignore_unknown
  1531. )
  1532. self._register_by_id_managed_msg(msgid, line)
  1533. def disable_next(
  1534. self,
  1535. msgid: str,
  1536. scope: str = "package",
  1537. line: Optional[int] = None,
  1538. ignore_unknown: bool = False,
  1539. ) -> None:
  1540. """Disable a message for the next line"""
  1541. if not line:
  1542. raise exceptions.NoLineSuppliedError
  1543. self._set_msg_status(
  1544. msgid,
  1545. enable=False,
  1546. scope=scope,
  1547. line=line + 1,
  1548. ignore_unknown=ignore_unknown,
  1549. )
  1550. self._register_by_id_managed_msg(msgid, line + 1)
  1551. def enable(
  1552. self,
  1553. msgid: str,
  1554. scope: str = "package",
  1555. line: Optional[int] = None,
  1556. ignore_unknown: bool = False,
  1557. ) -> None:
  1558. """Enable a message for a scope"""
  1559. self._set_msg_status(
  1560. msgid, enable=True, scope=scope, line=line, ignore_unknown=ignore_unknown
  1561. )
  1562. self._register_by_id_managed_msg(msgid, line, is_disabled=False)