PageRenderTime 36ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/pymode/libs/pylint/utils.py

https://gitlab.com/vim-IDE/python-mode
Python | 924 lines | 829 code | 30 blank | 65 comment | 14 complexity | 98e5472ef9b47b2db24849db63823852 MD5 | raw file
  1. # Copyright (c) 2003-2014 LOGILAB S.A. (Paris, FRANCE).
  2. # http://www.logilab.fr/ -- mailto:contact@logilab.fr
  3. #
  4. # This program is free software; you can redistribute it and/or modify it under
  5. # the terms of the GNU General Public License as published by the Free Software
  6. # Foundation; either version 2 of the License, or (at your option) any later
  7. # version.
  8. #
  9. # This program is distributed in the hope that it will be useful, but WITHOUT
  10. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  11. # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details
  12. #
  13. # You should have received a copy of the GNU General Public License along with
  14. # this program; if not, write to the Free Software Foundation, Inc.,
  15. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  16. """some various utilities and helper classes, most of them used in the
  17. main pylint class
  18. """
  19. from __future__ import print_function
  20. import collections
  21. import os
  22. import re
  23. import sys
  24. import tokenize
  25. import warnings
  26. from os.path import dirname, basename, splitext, exists, isdir, join, normpath
  27. import six
  28. from six.moves import zip # pylint: disable=redefined-builtin
  29. from logilab.common.interface import implements
  30. from logilab.common.textutils import normalize_text
  31. from logilab.common.configuration import rest_format_section
  32. from logilab.common.ureports import Section
  33. from astroid import nodes, Module
  34. from astroid.modutils import modpath_from_file, get_module_files, \
  35. file_from_modpath, load_module_from_file
  36. from pylint.interfaces import IRawChecker, ITokenChecker, UNDEFINED
  37. class UnknownMessage(Exception):
  38. """raised when a unregistered message id is encountered"""
  39. class EmptyReport(Exception):
  40. """raised when a report is empty and so should not be displayed"""
  41. MSG_TYPES = {
  42. 'I' : 'info',
  43. 'C' : 'convention',
  44. 'R' : 'refactor',
  45. 'W' : 'warning',
  46. 'E' : 'error',
  47. 'F' : 'fatal'
  48. }
  49. MSG_TYPES_LONG = {v: k for k, v in six.iteritems(MSG_TYPES)}
  50. MSG_TYPES_STATUS = {
  51. 'I' : 0,
  52. 'C' : 16,
  53. 'R' : 8,
  54. 'W' : 4,
  55. 'E' : 2,
  56. 'F' : 1
  57. }
  58. _MSG_ORDER = 'EWRCIF'
  59. MSG_STATE_SCOPE_CONFIG = 0
  60. MSG_STATE_SCOPE_MODULE = 1
  61. MSG_STATE_CONFIDENCE = 2
  62. OPTION_RGX = re.compile(r'\s*#.*\bpylint:(.*)')
  63. # The line/node distinction does not apply to fatal errors and reports.
  64. _SCOPE_EXEMPT = 'FR'
  65. class WarningScope(object):
  66. LINE = 'line-based-msg'
  67. NODE = 'node-based-msg'
  68. _MsgBase = collections.namedtuple(
  69. '_MsgBase',
  70. ['msg_id', 'symbol', 'msg', 'C', 'category', 'confidence',
  71. 'abspath', 'path', 'module', 'obj', 'line', 'column'])
  72. class Message(_MsgBase):
  73. """This class represent a message to be issued by the reporters"""
  74. def __new__(cls, msg_id, symbol, location, msg, confidence):
  75. return _MsgBase.__new__(
  76. cls, msg_id, symbol, msg, msg_id[0], MSG_TYPES[msg_id[0]],
  77. confidence, *location)
  78. def format(self, template):
  79. """Format the message according to the given template.
  80. The template format is the one of the format method :
  81. cf. http://docs.python.org/2/library/string.html#formatstrings
  82. """
  83. # For some reason, _asdict on derived namedtuples does not work with
  84. # Python 3.4. Needs some investigation.
  85. return template.format(**dict(zip(self._fields, self)))
  86. def get_module_and_frameid(node):
  87. """return the module name and the frame id in the module"""
  88. frame = node.frame()
  89. module, obj = '', []
  90. while frame:
  91. if isinstance(frame, Module):
  92. module = frame.name
  93. else:
  94. obj.append(getattr(frame, 'name', '<lambda>'))
  95. try:
  96. frame = frame.parent.frame()
  97. except AttributeError:
  98. frame = None
  99. obj.reverse()
  100. return module, '.'.join(obj)
  101. def category_id(cid):
  102. cid = cid.upper()
  103. if cid in MSG_TYPES:
  104. return cid
  105. return MSG_TYPES_LONG.get(cid)
  106. def _decoding_readline(stream, module):
  107. return lambda: stream.readline().decode(module.file_encoding,
  108. 'replace')
  109. def tokenize_module(module):
  110. with module.stream() as stream:
  111. readline = stream.readline
  112. if sys.version_info < (3, 0):
  113. if module.file_encoding is not None:
  114. readline = _decoding_readline(stream, module)
  115. return list(tokenize.generate_tokens(readline))
  116. return list(tokenize.tokenize(readline))
  117. def build_message_def(checker, msgid, msg_tuple):
  118. if implements(checker, (IRawChecker, ITokenChecker)):
  119. default_scope = WarningScope.LINE
  120. else:
  121. default_scope = WarningScope.NODE
  122. options = {}
  123. if len(msg_tuple) > 3:
  124. (msg, symbol, descr, options) = msg_tuple
  125. elif len(msg_tuple) > 2:
  126. (msg, symbol, descr) = msg_tuple[:3]
  127. else:
  128. # messages should have a symbol, but for backward compatibility
  129. # they may not.
  130. (msg, descr) = msg_tuple
  131. warnings.warn("[pylint 0.26] description of message %s doesn't include "
  132. "a symbolic name" % msgid, DeprecationWarning)
  133. symbol = None
  134. options.setdefault('scope', default_scope)
  135. return MessageDefinition(checker, msgid, msg, descr, symbol, **options)
  136. class MessageDefinition(object):
  137. def __init__(self, checker, msgid, msg, descr, symbol, scope,
  138. minversion=None, maxversion=None, old_names=None):
  139. self.checker = checker
  140. assert len(msgid) == 5, 'Invalid message id %s' % msgid
  141. assert msgid[0] in MSG_TYPES, \
  142. 'Bad message type %s in %r' % (msgid[0], msgid)
  143. self.msgid = msgid
  144. self.msg = msg
  145. self.descr = descr
  146. self.symbol = symbol
  147. self.scope = scope
  148. self.minversion = minversion
  149. self.maxversion = maxversion
  150. self.old_names = old_names or []
  151. def may_be_emitted(self):
  152. """return True if message may be emitted using the current interpreter"""
  153. if self.minversion is not None and self.minversion > sys.version_info:
  154. return False
  155. if self.maxversion is not None and self.maxversion <= sys.version_info:
  156. return False
  157. return True
  158. def format_help(self, checkerref=False):
  159. """return the help string for the given message id"""
  160. desc = self.descr
  161. if checkerref:
  162. desc += ' This message belongs to the %s checker.' % \
  163. self.checker.name
  164. title = self.msg
  165. if self.symbol:
  166. msgid = '%s (%s)' % (self.symbol, self.msgid)
  167. else:
  168. msgid = self.msgid
  169. if self.minversion or self.maxversion:
  170. restr = []
  171. if self.minversion:
  172. restr.append('< %s' % '.'.join([str(n) for n in self.minversion]))
  173. if self.maxversion:
  174. restr.append('>= %s' % '.'.join([str(n) for n in self.maxversion]))
  175. restr = ' or '.join(restr)
  176. if checkerref:
  177. desc += " It can't be emitted when using Python %s." % restr
  178. else:
  179. desc += " This message can't be emitted when using Python %s." % restr
  180. desc = normalize_text(' '.join(desc.split()), indent=' ')
  181. if title != '%s':
  182. title = title.splitlines()[0]
  183. return ':%s: *%s*\n%s' % (msgid, title, desc)
  184. return ':%s:\n%s' % (msgid, desc)
  185. class MessagesHandlerMixIn(object):
  186. """a mix-in class containing all the messages related methods for the main
  187. lint class
  188. """
  189. def __init__(self):
  190. self._msgs_state = {}
  191. self.msg_status = 0
  192. def _checker_messages(self, checker):
  193. for checker in self._checkers[checker.lower()]:
  194. for msgid in checker.msgs:
  195. yield msgid
  196. def disable(self, msgid, scope='package', line=None, ignore_unknown=False):
  197. """don't output message of the given id"""
  198. assert scope in ('package', 'module')
  199. # handle disable=all by disabling all categories
  200. if msgid == 'all':
  201. for msgid in MSG_TYPES:
  202. self.disable(msgid, scope, line)
  203. return
  204. # msgid is a category?
  205. catid = category_id(msgid)
  206. if catid is not None:
  207. for _msgid in self.msgs_store._msgs_by_category.get(catid):
  208. self.disable(_msgid, scope, line)
  209. return
  210. # msgid is a checker name?
  211. if msgid.lower() in self._checkers:
  212. msgs_store = self.msgs_store
  213. for checker in self._checkers[msgid.lower()]:
  214. for _msgid in checker.msgs:
  215. if _msgid in msgs_store._alternative_names:
  216. self.disable(_msgid, scope, line)
  217. return
  218. # msgid is report id?
  219. if msgid.lower().startswith('rp'):
  220. self.disable_report(msgid)
  221. return
  222. try:
  223. # msgid is a symbolic or numeric msgid.
  224. msg = self.msgs_store.check_message_id(msgid)
  225. except UnknownMessage:
  226. if ignore_unknown:
  227. return
  228. raise
  229. if scope == 'module':
  230. self.file_state.set_msg_status(msg, line, False)
  231. if msg.symbol != 'locally-disabled':
  232. self.add_message('locally-disabled', line=line,
  233. args=(msg.symbol, msg.msgid))
  234. else:
  235. msgs = self._msgs_state
  236. msgs[msg.msgid] = False
  237. # sync configuration object
  238. self.config.disable = [mid for mid, val in six.iteritems(msgs)
  239. if not val]
  240. def enable(self, msgid, scope='package', line=None, ignore_unknown=False):
  241. """reenable message of the given id"""
  242. assert scope in ('package', 'module')
  243. catid = category_id(msgid)
  244. # msgid is a category?
  245. if catid is not None:
  246. for msgid in self.msgs_store._msgs_by_category.get(catid):
  247. self.enable(msgid, scope, line)
  248. return
  249. # msgid is a checker name?
  250. if msgid.lower() in self._checkers:
  251. for checker in self._checkers[msgid.lower()]:
  252. for msgid_ in checker.msgs:
  253. self.enable(msgid_, scope, line)
  254. return
  255. # msgid is report id?
  256. if msgid.lower().startswith('rp'):
  257. self.enable_report(msgid)
  258. return
  259. try:
  260. # msgid is a symbolic or numeric msgid.
  261. msg = self.msgs_store.check_message_id(msgid)
  262. except UnknownMessage:
  263. if ignore_unknown:
  264. return
  265. raise
  266. if scope == 'module':
  267. self.file_state.set_msg_status(msg, line, True)
  268. self.add_message('locally-enabled', line=line, args=(msg.symbol, msg.msgid))
  269. else:
  270. msgs = self._msgs_state
  271. msgs[msg.msgid] = True
  272. # sync configuration object
  273. self.config.enable = [mid for mid, val in six.iteritems(msgs) if val]
  274. def get_message_state_scope(self, msgid, line=None, confidence=UNDEFINED):
  275. """Returns the scope at which a message was enabled/disabled."""
  276. if self.config.confidence and confidence.name not in self.config.confidence:
  277. return MSG_STATE_CONFIDENCE
  278. try:
  279. if line in self.file_state._module_msgs_state[msgid]:
  280. return MSG_STATE_SCOPE_MODULE
  281. except (KeyError, TypeError):
  282. return MSG_STATE_SCOPE_CONFIG
  283. def is_message_enabled(self, msg_descr, line=None, confidence=None):
  284. """return true if the message associated to the given message id is
  285. enabled
  286. msgid may be either a numeric or symbolic message id.
  287. """
  288. if self.config.confidence and confidence:
  289. if confidence.name not in self.config.confidence:
  290. return False
  291. try:
  292. msgid = self.msgs_store.check_message_id(msg_descr).msgid
  293. except UnknownMessage:
  294. # The linter checks for messages that are not registered
  295. # due to version mismatch, just treat them as message IDs
  296. # for now.
  297. msgid = msg_descr
  298. if line is None:
  299. return self._msgs_state.get(msgid, True)
  300. try:
  301. return self.file_state._module_msgs_state[msgid][line]
  302. except KeyError:
  303. return self._msgs_state.get(msgid, True)
  304. def add_message(self, msg_descr, line=None, node=None, args=None, confidence=UNDEFINED):
  305. """Adds a message given by ID or name.
  306. If provided, the message string is expanded using args
  307. AST checkers should must the node argument (but may optionally
  308. provide line if the line number is different), raw and token checkers
  309. must provide the line argument.
  310. """
  311. msg_info = self.msgs_store.check_message_id(msg_descr)
  312. msgid = msg_info.msgid
  313. # backward compatibility, message may not have a symbol
  314. symbol = msg_info.symbol or msgid
  315. # Fatal messages and reports are special, the node/scope distinction
  316. # does not apply to them.
  317. if msgid[0] not in _SCOPE_EXEMPT:
  318. if msg_info.scope == WarningScope.LINE:
  319. assert node is None and line is not None, (
  320. 'Message %s must only provide line, got line=%s, node=%s' % (msgid, line, node))
  321. elif msg_info.scope == WarningScope.NODE:
  322. # Node-based warnings may provide an override line.
  323. assert node is not None, 'Message %s must provide Node, got None'
  324. if line is None and node is not None:
  325. line = node.fromlineno
  326. if hasattr(node, 'col_offset'):
  327. col_offset = node.col_offset # XXX measured in bytes for utf-8, divide by two for chars?
  328. else:
  329. col_offset = None
  330. # should this message be displayed
  331. if not self.is_message_enabled(msgid, line, confidence):
  332. self.file_state.handle_ignored_message(
  333. self.get_message_state_scope(msgid, line, confidence),
  334. msgid, line, node, args, confidence)
  335. return
  336. # update stats
  337. msg_cat = MSG_TYPES[msgid[0]]
  338. self.msg_status |= MSG_TYPES_STATUS[msgid[0]]
  339. self.stats[msg_cat] += 1
  340. self.stats['by_module'][self.current_name][msg_cat] += 1
  341. try:
  342. self.stats['by_msg'][symbol] += 1
  343. except KeyError:
  344. self.stats['by_msg'][symbol] = 1
  345. # expand message ?
  346. msg = msg_info.msg
  347. if args:
  348. msg %= args
  349. # get module and object
  350. if node is None:
  351. module, obj = self.current_name, ''
  352. abspath = self.current_file
  353. else:
  354. module, obj = get_module_and_frameid(node)
  355. abspath = node.root().file
  356. path = abspath.replace(self.reporter.path_strip_prefix, '')
  357. # add the message
  358. self.reporter.handle_message(
  359. Message(msgid, symbol,
  360. (abspath, path, module, obj, line or 1, col_offset or 0), msg, confidence))
  361. def print_full_documentation(self):
  362. """output a full documentation in ReST format"""
  363. print("Pylint global options and switches")
  364. print("----------------------------------")
  365. print("")
  366. print("Pylint provides global options and switches.")
  367. print("")
  368. by_checker = {}
  369. for checker in self.get_checkers():
  370. if checker.name == 'master':
  371. if checker.options:
  372. for section, options in checker.options_by_section():
  373. if section is None:
  374. title = 'General options'
  375. else:
  376. title = '%s options' % section.capitalize()
  377. print(title)
  378. print('~' * len(title))
  379. rest_format_section(sys.stdout, None, options)
  380. print("")
  381. else:
  382. try:
  383. by_checker[checker.name][0] += checker.options_and_values()
  384. by_checker[checker.name][1].update(checker.msgs)
  385. by_checker[checker.name][2] += checker.reports
  386. except KeyError:
  387. by_checker[checker.name] = [list(checker.options_and_values()),
  388. dict(checker.msgs),
  389. list(checker.reports)]
  390. print("Pylint checkers' options and switches")
  391. print("-------------------------------------")
  392. print("")
  393. print("Pylint checkers can provide three set of features:")
  394. print("")
  395. print("* options that control their execution,")
  396. print("* messages that they can raise,")
  397. print("* reports that they can generate.")
  398. print("")
  399. print("Below is a list of all checkers and their features.")
  400. print("")
  401. for checker, (options, msgs, reports) in six.iteritems(by_checker):
  402. title = '%s checker' % (checker.replace("_", " ").title())
  403. print(title)
  404. print('~' * len(title))
  405. print("")
  406. print("Verbatim name of the checker is ``%s``." % checker)
  407. print("")
  408. if options:
  409. title = 'Options'
  410. print(title)
  411. print('^' * len(title))
  412. rest_format_section(sys.stdout, None, options)
  413. print("")
  414. if msgs:
  415. title = 'Messages'
  416. print(title)
  417. print('~' * len(title))
  418. for msgid, msg in sorted(six.iteritems(msgs),
  419. key=lambda kv: (_MSG_ORDER.index(kv[0][0]), kv[1])):
  420. msg = build_message_def(checker, msgid, msg)
  421. print(msg.format_help(checkerref=False))
  422. print("")
  423. if reports:
  424. title = 'Reports'
  425. print(title)
  426. print('~' * len(title))
  427. for report in reports:
  428. print(':%s: %s' % report[:2])
  429. print("")
  430. print("")
  431. class FileState(object):
  432. """Hold internal state specific to the currently analyzed file"""
  433. def __init__(self, modname=None):
  434. self.base_name = modname
  435. self._module_msgs_state = {}
  436. self._raw_module_msgs_state = {}
  437. self._ignored_msgs = collections.defaultdict(set)
  438. self._suppression_mapping = {}
  439. def collect_block_lines(self, msgs_store, module_node):
  440. """Walk the AST to collect block level options line numbers."""
  441. for msg, lines in six.iteritems(self._module_msgs_state):
  442. self._raw_module_msgs_state[msg] = lines.copy()
  443. orig_state = self._module_msgs_state.copy()
  444. self._module_msgs_state = {}
  445. self._suppression_mapping = {}
  446. self._collect_block_lines(msgs_store, module_node, orig_state)
  447. def _collect_block_lines(self, msgs_store, node, msg_state):
  448. """Recursivly walk (depth first) AST to collect block level options line
  449. numbers.
  450. """
  451. for child in node.get_children():
  452. self._collect_block_lines(msgs_store, child, msg_state)
  453. first = node.fromlineno
  454. last = node.tolineno
  455. # first child line number used to distinguish between disable
  456. # which are the first child of scoped node with those defined later.
  457. # For instance in the code below:
  458. #
  459. # 1. def meth8(self):
  460. # 2. """test late disabling"""
  461. # 3. # pylint: disable=E1102
  462. # 4. print self.blip
  463. # 5. # pylint: disable=E1101
  464. # 6. print self.bla
  465. #
  466. # E1102 should be disabled from line 1 to 6 while E1101 from line 5 to 6
  467. #
  468. # this is necessary to disable locally messages applying to class /
  469. # function using their fromlineno
  470. if isinstance(node, (nodes.Module, nodes.Class, nodes.Function)) and node.body:
  471. firstchildlineno = node.body[0].fromlineno
  472. else:
  473. firstchildlineno = last
  474. for msgid, lines in six.iteritems(msg_state):
  475. for lineno, state in list(lines.items()):
  476. original_lineno = lineno
  477. if first <= lineno <= last:
  478. # Set state for all lines for this block, if the
  479. # warning is applied to nodes.
  480. if msgs_store.check_message_id(msgid).scope == WarningScope.NODE:
  481. if lineno > firstchildlineno:
  482. state = True
  483. first_, last_ = node.block_range(lineno)
  484. else:
  485. first_ = lineno
  486. last_ = last
  487. for line in range(first_, last_+1):
  488. # do not override existing entries
  489. if not line in self._module_msgs_state.get(msgid, ()):
  490. if line in lines: # state change in the same block
  491. state = lines[line]
  492. original_lineno = line
  493. if not state:
  494. self._suppression_mapping[(msgid, line)] = original_lineno
  495. try:
  496. self._module_msgs_state[msgid][line] = state
  497. except KeyError:
  498. self._module_msgs_state[msgid] = {line: state}
  499. del lines[lineno]
  500. def set_msg_status(self, msg, line, status):
  501. """Set status (enabled/disable) for a given message at a given line"""
  502. assert line > 0
  503. try:
  504. self._module_msgs_state[msg.msgid][line] = status
  505. except KeyError:
  506. self._module_msgs_state[msg.msgid] = {line: status}
  507. def handle_ignored_message(self, state_scope, msgid, line,
  508. node, args, confidence): # pylint: disable=unused-argument
  509. """Report an ignored message.
  510. state_scope is either MSG_STATE_SCOPE_MODULE or MSG_STATE_SCOPE_CONFIG,
  511. depending on whether the message was disabled locally in the module,
  512. or globally. The other arguments are the same as for add_message.
  513. """
  514. if state_scope == MSG_STATE_SCOPE_MODULE:
  515. try:
  516. orig_line = self._suppression_mapping[(msgid, line)]
  517. self._ignored_msgs[(msgid, orig_line)].add(line)
  518. except KeyError:
  519. pass
  520. def iter_spurious_suppression_messages(self, msgs_store):
  521. for warning, lines in six.iteritems(self._raw_module_msgs_state):
  522. for line, enable in six.iteritems(lines):
  523. if not enable and (warning, line) not in self._ignored_msgs:
  524. yield 'useless-suppression', line, \
  525. (msgs_store.get_msg_display_string(warning),)
  526. # don't use iteritems here, _ignored_msgs may be modified by add_message
  527. for (warning, from_), lines in list(self._ignored_msgs.items()):
  528. for line in lines:
  529. yield 'suppressed-message', line, \
  530. (msgs_store.get_msg_display_string(warning), from_)
  531. class MessagesStore(object):
  532. """The messages store knows information about every possible message but has
  533. no particular state during analysis.
  534. """
  535. def __init__(self):
  536. # Primary registry for all active messages (i.e. all messages
  537. # that can be emitted by pylint for the underlying Python
  538. # version). It contains the 1:1 mapping from symbolic names
  539. # to message definition objects.
  540. self._messages = {}
  541. # Maps alternative names (numeric IDs, deprecated names) to
  542. # message definitions. May contain several names for each definition
  543. # object.
  544. self._alternative_names = {}
  545. self._msgs_by_category = collections.defaultdict(list)
  546. @property
  547. def messages(self):
  548. """The list of all active messages."""
  549. return six.itervalues(self._messages)
  550. def add_renamed_message(self, old_id, old_symbol, new_symbol):
  551. """Register the old ID and symbol for a warning that was renamed.
  552. This allows users to keep using the old ID/symbol in suppressions.
  553. """
  554. msg = self.check_message_id(new_symbol)
  555. msg.old_names.append((old_id, old_symbol))
  556. self._alternative_names[old_id] = msg
  557. self._alternative_names[old_symbol] = msg
  558. def register_messages(self, checker):
  559. """register a dictionary of messages
  560. Keys are message ids, values are a 2-uple with the message type and the
  561. message itself
  562. message ids should be a string of len 4, where the two first characters
  563. are the checker id and the two last the message id in this checker
  564. """
  565. chkid = None
  566. for msgid, msg_tuple in six.iteritems(checker.msgs):
  567. msg = build_message_def(checker, msgid, msg_tuple)
  568. assert msg.symbol not in self._messages, \
  569. 'Message symbol %r is already defined' % msg.symbol
  570. # avoid duplicate / malformed ids
  571. assert msg.msgid not in self._alternative_names, \
  572. 'Message id %r is already defined' % msgid
  573. assert chkid is None or chkid == msg.msgid[1:3], \
  574. 'Inconsistent checker part in message id %r' % msgid
  575. chkid = msg.msgid[1:3]
  576. self._messages[msg.symbol] = msg
  577. self._alternative_names[msg.msgid] = msg
  578. for old_id, old_symbol in msg.old_names:
  579. self._alternative_names[old_id] = msg
  580. self._alternative_names[old_symbol] = msg
  581. self._msgs_by_category[msg.msgid[0]].append(msg.msgid)
  582. def check_message_id(self, msgid):
  583. """returns the Message object for this message.
  584. msgid may be either a numeric or symbolic id.
  585. Raises UnknownMessage if the message id is not defined.
  586. """
  587. if msgid[1:].isdigit():
  588. msgid = msgid.upper()
  589. for source in (self._alternative_names, self._messages):
  590. try:
  591. return source[msgid]
  592. except KeyError:
  593. pass
  594. raise UnknownMessage('No such message id %s' % msgid)
  595. def get_msg_display_string(self, msgid):
  596. """Generates a user-consumable representation of a message.
  597. Can be just the message ID or the ID and the symbol.
  598. """
  599. return repr(self.check_message_id(msgid).symbol)
  600. def help_message(self, msgids):
  601. """display help messages for the given message identifiers"""
  602. for msgid in msgids:
  603. try:
  604. print(self.check_message_id(msgid).format_help(checkerref=True))
  605. print("")
  606. except UnknownMessage as ex:
  607. print(ex)
  608. print("")
  609. continue
  610. def list_messages(self):
  611. """output full messages list documentation in ReST format"""
  612. msgs = sorted(six.itervalues(self._messages), key=lambda msg: msg.msgid)
  613. for msg in msgs:
  614. if not msg.may_be_emitted():
  615. continue
  616. print(msg.format_help(checkerref=False))
  617. print("")
  618. class ReportsHandlerMixIn(object):
  619. """a mix-in class containing all the reports and stats manipulation
  620. related methods for the main lint class
  621. """
  622. def __init__(self):
  623. self._reports = collections.defaultdict(list)
  624. self._reports_state = {}
  625. def report_order(self):
  626. """ Return a list of reports, sorted in the order
  627. in which they must be called.
  628. """
  629. return list(self._reports)
  630. def register_report(self, reportid, r_title, r_cb, checker):
  631. """register a report
  632. reportid is the unique identifier for the report
  633. r_title the report's title
  634. r_cb the method to call to make the report
  635. checker is the checker defining the report
  636. """
  637. reportid = reportid.upper()
  638. self._reports[checker].append((reportid, r_title, r_cb))
  639. def enable_report(self, reportid):
  640. """disable the report of the given id"""
  641. reportid = reportid.upper()
  642. self._reports_state[reportid] = True
  643. def disable_report(self, reportid):
  644. """disable the report of the given id"""
  645. reportid = reportid.upper()
  646. self._reports_state[reportid] = False
  647. def report_is_enabled(self, reportid):
  648. """return true if the report associated to the given identifier is
  649. enabled
  650. """
  651. return self._reports_state.get(reportid, True)
  652. def make_reports(self, stats, old_stats):
  653. """render registered reports"""
  654. sect = Section('Report',
  655. '%s statements analysed.'% (self.stats['statement']))
  656. for checker in self.report_order():
  657. for reportid, r_title, r_cb in self._reports[checker]:
  658. if not self.report_is_enabled(reportid):
  659. continue
  660. report_sect = Section(r_title)
  661. try:
  662. r_cb(report_sect, stats, old_stats)
  663. except EmptyReport:
  664. continue
  665. report_sect.report_id = reportid
  666. sect.append(report_sect)
  667. return sect
  668. def add_stats(self, **kwargs):
  669. """add some stats entries to the statistic dictionary
  670. raise an AssertionError if there is a key conflict
  671. """
  672. for key, value in six.iteritems(kwargs):
  673. if key[-1] == '_':
  674. key = key[:-1]
  675. assert key not in self.stats
  676. self.stats[key] = value
  677. return self.stats
  678. def expand_modules(files_or_modules, black_list):
  679. """take a list of files/modules/packages and return the list of tuple
  680. (file, module name) which have to be actually checked
  681. """
  682. result = []
  683. errors = []
  684. for something in files_or_modules:
  685. if exists(something):
  686. # this is a file or a directory
  687. try:
  688. modname = '.'.join(modpath_from_file(something))
  689. except ImportError:
  690. modname = splitext(basename(something))[0]
  691. if isdir(something):
  692. filepath = join(something, '__init__.py')
  693. else:
  694. filepath = something
  695. else:
  696. # suppose it's a module or package
  697. modname = something
  698. try:
  699. filepath = file_from_modpath(modname.split('.'))
  700. if filepath is None:
  701. errors.append({'key' : 'ignored-builtin-module', 'mod': modname})
  702. continue
  703. except (ImportError, SyntaxError) as ex:
  704. # FIXME p3k : the SyntaxError is a Python bug and should be
  705. # removed as soon as possible http://bugs.python.org/issue10588
  706. errors.append({'key': 'fatal', 'mod': modname, 'ex': ex})
  707. continue
  708. filepath = normpath(filepath)
  709. result.append({'path': filepath, 'name': modname, 'isarg': True,
  710. 'basepath': filepath, 'basename': modname})
  711. if not (modname.endswith('.__init__') or modname == '__init__') \
  712. and '__init__.py' in filepath:
  713. for subfilepath in get_module_files(dirname(filepath), black_list):
  714. if filepath == subfilepath:
  715. continue
  716. submodname = '.'.join(modpath_from_file(subfilepath))
  717. result.append({'path': subfilepath, 'name': submodname,
  718. 'isarg': False,
  719. 'basepath': filepath, 'basename': modname})
  720. return result, errors
  721. class PyLintASTWalker(object):
  722. def __init__(self, linter):
  723. # callbacks per node types
  724. self.nbstatements = 1
  725. self.visit_events = collections.defaultdict(list)
  726. self.leave_events = collections.defaultdict(list)
  727. self.linter = linter
  728. def _is_method_enabled(self, method):
  729. if not hasattr(method, 'checks_msgs'):
  730. return True
  731. for msg_desc in method.checks_msgs:
  732. if self.linter.is_message_enabled(msg_desc):
  733. return True
  734. return False
  735. def add_checker(self, checker):
  736. """walk to the checker's dir and collect visit and leave methods"""
  737. # XXX : should be possible to merge needed_checkers and add_checker
  738. vcids = set()
  739. lcids = set()
  740. visits = self.visit_events
  741. leaves = self.leave_events
  742. for member in dir(checker):
  743. cid = member[6:]
  744. if cid == 'default':
  745. continue
  746. if member.startswith('visit_'):
  747. v_meth = getattr(checker, member)
  748. # don't use visit_methods with no activated message:
  749. if self._is_method_enabled(v_meth):
  750. visits[cid].append(v_meth)
  751. vcids.add(cid)
  752. elif member.startswith('leave_'):
  753. l_meth = getattr(checker, member)
  754. # don't use leave_methods with no activated message:
  755. if self._is_method_enabled(l_meth):
  756. leaves[cid].append(l_meth)
  757. lcids.add(cid)
  758. visit_default = getattr(checker, 'visit_default', None)
  759. if visit_default:
  760. for cls in nodes.ALL_NODE_CLASSES:
  761. cid = cls.__name__.lower()
  762. if cid not in vcids:
  763. visits[cid].append(visit_default)
  764. # for now we have no "leave_default" method in Pylint
  765. def walk(self, astroid):
  766. """call visit events of astroid checkers for the given node, recurse on
  767. its children, then leave events.
  768. """
  769. cid = astroid.__class__.__name__.lower()
  770. if astroid.is_statement:
  771. self.nbstatements += 1
  772. # generate events for this node on each checker
  773. for cb in self.visit_events.get(cid, ()):
  774. cb(astroid)
  775. # recurse on children
  776. for child in astroid.get_children():
  777. self.walk(child)
  778. for cb in self.leave_events.get(cid, ()):
  779. cb(astroid)
  780. PY_EXTS = ('.py', '.pyc', '.pyo', '.pyw', '.so', '.dll')
  781. def register_plugins(linter, directory):
  782. """load all module and package in the given directory, looking for a
  783. 'register' function in each one, used to register pylint checkers
  784. """
  785. imported = {}
  786. for filename in os.listdir(directory):
  787. base, extension = splitext(filename)
  788. if base in imported or base == '__pycache__':
  789. continue
  790. if extension in PY_EXTS and base != '__init__' or (
  791. not extension and isdir(join(directory, base))):
  792. try:
  793. module = load_module_from_file(join(directory, filename))
  794. except ValueError:
  795. # empty module name (usually emacs auto-save files)
  796. continue
  797. except ImportError as exc:
  798. print("Problem importing module %s: %s" % (filename, exc),
  799. file=sys.stderr)
  800. else:
  801. if hasattr(module, 'register'):
  802. module.register(linter)
  803. imported[base] = 1
  804. def get_global_option(checker, option, default=None):
  805. """ Retrieve an option defined by the given *checker* or
  806. by all known option providers.
  807. It will look in the list of all options providers
  808. until the given *option* will be found.
  809. If the option wasn't found, the *default* value will be returned.
  810. """
  811. # First, try in the given checker's config.
  812. # After that, look in the options providers.
  813. try:
  814. return getattr(checker.config, option.replace("-", "_"))
  815. except AttributeError:
  816. pass
  817. for provider in checker.linter.options_providers:
  818. for options in provider.options:
  819. if options[0] == option:
  820. return getattr(provider.config, option.replace("-", "_"))
  821. return default