Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.py 47KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2006-2014 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
  3. # Copyright (c) 2009 Vincent
  4. # Copyright (c) 2009 Mads Kiilerich <mads@kiilerich.com>
  5. # Copyright (c) 2012-2014 Google, Inc.
  6. # Copyright (c) 2014-2017 Claudiu Popa <pcmanticore@gmail.com>
  7. # Copyright (c) 2014-2015 Michal Nowikowski <godfryd@gmail.com>
  8. # Copyright (c) 2014 LCD 47 <lcd047@gmail.com>
  9. # Copyright (c) 2014 Brett Cannon <brett@python.org>
  10. # Copyright (c) 2014 Arun Persaud <arun@nubati.net>
  11. # Copyright (c) 2014 Damien Nozay <damien.nozay@gmail.com>
  12. # Copyright (c) 2015 Aru Sahni <arusahni@gmail.com>
  13. # Copyright (c) 2015 Florian Bruhin <me@the-compiler.org>
  14. # Copyright (c) 2015 Simu Toni <simutoni@gmail.com>
  15. # Copyright (c) 2015 Ionel Cristian Maries <contact@ionelmc.ro>
  16. # Copyright (c) 2016 Łukasz Rogalski <rogalski.91@gmail.com>
  17. # Copyright (c) 2016 Moises Lopez <moylop260@vauxoo.com>
  18. # Copyright (c) 2016 Glenn Matthews <glenn@e-dad.net>
  19. # Copyright (c) 2016 Glenn Matthews <glmatthe@cisco.com>
  20. # Copyright (c) 2016 Ashley Whetter <ashley@awhetter.co.uk>
  21. # Copyright (c) 2016 xmo-odoo <xmo-odoo@users.noreply.github.com>
  22. # Copyright (c) 2017 Chris Lamb <chris@chris-lamb.co.uk>
  23. # Copyright (c) 2017 hippo91 <guillaume.peillex@gmail.com>
  24. # Copyright (c) 2017 Anthony Sottile <asottile@umich.edu>
  25. # Copyright (c) 2017 Thomas Hisch <t.hisch@gmail.com>
  26. # Copyright (c) 2017 Mikhail Fesenko <proggga@gmail.com>
  27. # Copyright (c) 2017 Craig Citro <craigcitro@gmail.com>
  28. # Copyright (c) 2017 Ville Skyttä <ville.skytta@iki.fi>
  29. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  30. # For details: https://github.com/PyCQA/pylint/blob/master/COPYING
  31. """some various utilities and helper classes, most of them used in the
  32. main pylint class
  33. """
  34. from __future__ import print_function
  35. import codecs
  36. import collections
  37. from inspect import cleandoc
  38. import os
  39. from os.path import dirname, basename, splitext, exists, isdir, join, normpath
  40. import re
  41. import sys
  42. import tokenize
  43. import warnings
  44. import textwrap
  45. import six
  46. from six.moves import zip # pylint: disable=redefined-builtin
  47. from astroid import nodes, Module
  48. from astroid import modutils
  49. from pylint.interfaces import IRawChecker, ITokenChecker, UNDEFINED, implements
  50. from pylint.reporters.ureports.nodes import Section
  51. from pylint.exceptions import InvalidMessageError, UnknownMessageError, EmptyReportError
  52. MSG_TYPES = {
  53. 'I' : 'info',
  54. 'C' : 'convention',
  55. 'R' : 'refactor',
  56. 'W' : 'warning',
  57. 'E' : 'error',
  58. 'F' : 'fatal'
  59. }
  60. MSG_TYPES_LONG = {v: k for k, v in six.iteritems(MSG_TYPES)}
  61. MSG_TYPES_STATUS = {
  62. 'I' : 0,
  63. 'C' : 16,
  64. 'R' : 8,
  65. 'W' : 4,
  66. 'E' : 2,
  67. 'F' : 1
  68. }
  69. _MSG_ORDER = 'EWRCIF'
  70. MSG_STATE_SCOPE_CONFIG = 0
  71. MSG_STATE_SCOPE_MODULE = 1
  72. MSG_STATE_CONFIDENCE = 2
  73. # Allow stopping after the first semicolon encountered,
  74. # so that an option can be continued with the reasons
  75. # why it is active or disabled.
  76. OPTION_RGX = re.compile(r'\s*#.*\bpylint:\s*([^;]+);{0,1}')
  77. # The line/node distinction does not apply to fatal errors and reports.
  78. _SCOPE_EXEMPT = 'FR'
  79. class WarningScope(object):
  80. LINE = 'line-based-msg'
  81. NODE = 'node-based-msg'
  82. _MsgBase = collections.namedtuple(
  83. '_MsgBase',
  84. ['msg_id', 'symbol', 'msg', 'C', 'category', 'confidence',
  85. 'abspath', 'path', 'module', 'obj', 'line', 'column'])
  86. class Message(_MsgBase):
  87. """This class represent a message to be issued by the reporters"""
  88. def __new__(cls, msg_id, symbol, location, msg, confidence):
  89. return _MsgBase.__new__(
  90. cls, msg_id, symbol, msg, msg_id[0], MSG_TYPES[msg_id[0]],
  91. confidence, *location)
  92. def format(self, template):
  93. """Format the message according to the given template.
  94. The template format is the one of the format method :
  95. cf. http://docs.python.org/2/library/string.html#formatstrings
  96. """
  97. # For some reason, _asdict on derived namedtuples does not work with
  98. # Python 3.4. Needs some investigation.
  99. return template.format(**dict(zip(self._fields, self)))
  100. def get_module_and_frameid(node):
  101. """return the module name and the frame id in the module"""
  102. frame = node.frame()
  103. module, obj = '', []
  104. while frame:
  105. if isinstance(frame, Module):
  106. module = frame.name
  107. else:
  108. obj.append(getattr(frame, 'name', '<lambda>'))
  109. try:
  110. frame = frame.parent.frame()
  111. except AttributeError:
  112. frame = None
  113. obj.reverse()
  114. return module, '.'.join(obj)
  115. def category_id(cid):
  116. cid = cid.upper()
  117. if cid in MSG_TYPES:
  118. return cid
  119. return MSG_TYPES_LONG.get(cid)
  120. def safe_decode(line, encoding, *args, **kwargs):
  121. '''return decoded line from encoding or decode with default encoding'''
  122. try:
  123. return line.decode(encoding or sys.getdefaultencoding(), *args, **kwargs)
  124. except LookupError:
  125. return line.decode(sys.getdefaultencoding(), *args, **kwargs)
  126. def decoding_stream(stream, encoding, errors='strict'):
  127. try:
  128. reader_cls = codecs.getreader(encoding or sys.getdefaultencoding())
  129. except LookupError:
  130. reader_cls = codecs.getreader(sys.getdefaultencoding())
  131. return reader_cls(stream, errors)
  132. def _decoding_readline(stream, encoding):
  133. '''return lambda function for tokenize with safe decode'''
  134. return decoding_stream(stream, encoding, errors='replace').readline
  135. def tokenize_module(module):
  136. with module.stream() as stream:
  137. readline = stream.readline
  138. if sys.version_info < (3, 0):
  139. if module.file_encoding is not None:
  140. readline = _decoding_readline(stream, module.file_encoding)
  141. return list(tokenize.generate_tokens(readline))
  142. return list(tokenize.tokenize(readline))
  143. def build_message_def(checker, msgid, msg_tuple):
  144. if implements(checker, (IRawChecker, ITokenChecker)):
  145. default_scope = WarningScope.LINE
  146. else:
  147. default_scope = WarningScope.NODE
  148. options = {}
  149. if len(msg_tuple) > 3:
  150. (msg, symbol, descr, options) = msg_tuple
  151. elif len(msg_tuple) > 2:
  152. (msg, symbol, descr) = msg_tuple
  153. else:
  154. # messages should have a symbol, but for backward compatibility
  155. # they may not.
  156. (msg, descr) = msg_tuple
  157. warnings.warn("[pylint 0.26] description of message %s doesn't include "
  158. "a symbolic name" % msgid, DeprecationWarning)
  159. symbol = None
  160. options.setdefault('scope', default_scope)
  161. return MessageDefinition(checker, msgid, msg, descr, symbol, **options)
  162. class MessageDefinition(object):
  163. def __init__(self, checker, msgid, msg, descr, symbol, scope,
  164. minversion=None, maxversion=None, old_names=None):
  165. self.checker = checker
  166. if len(msgid) != 5:
  167. raise InvalidMessageError('Invalid message id %r' % msgid)
  168. if not msgid[0] in MSG_TYPES:
  169. raise InvalidMessageError(
  170. 'Bad message type %s in %r' % (msgid[0], msgid))
  171. self.msgid = msgid
  172. self.msg = msg
  173. self.descr = descr
  174. self.symbol = symbol
  175. self.scope = scope
  176. self.minversion = minversion
  177. self.maxversion = maxversion
  178. self.old_names = old_names or []
  179. def may_be_emitted(self):
  180. """return True if message may be emitted using the current interpreter"""
  181. if self.minversion is not None and self.minversion > sys.version_info:
  182. return False
  183. if self.maxversion is not None and self.maxversion <= sys.version_info:
  184. return False
  185. return True
  186. def format_help(self, checkerref=False):
  187. """return the help string for the given message id"""
  188. desc = self.descr
  189. if checkerref:
  190. desc += ' This message belongs to the %s checker.' % \
  191. self.checker.name
  192. title = self.msg
  193. if self.symbol:
  194. msgid = '%s (%s)' % (self.symbol, self.msgid)
  195. else:
  196. msgid = self.msgid
  197. if self.minversion or self.maxversion:
  198. restr = []
  199. if self.minversion:
  200. restr.append('< %s' % '.'.join([str(n) for n in self.minversion]))
  201. if self.maxversion:
  202. restr.append('>= %s' % '.'.join([str(n) for n in self.maxversion]))
  203. restr = ' or '.join(restr)
  204. if checkerref:
  205. desc += " It can't be emitted when using Python %s." % restr
  206. else:
  207. desc += " This message can't be emitted when using Python %s." % restr
  208. desc = _normalize_text(' '.join(desc.split()), indent=' ')
  209. if title != '%s':
  210. title = title.splitlines()[0]
  211. return ':%s: *%s*\n%s' % (msgid, title, desc)
  212. return ':%s:\n%s' % (msgid, desc)
  213. class MessagesHandlerMixIn(object):
  214. """a mix-in class containing all the messages related methods for the main
  215. lint class
  216. """
  217. def __init__(self):
  218. self._msgs_state = {}
  219. self.msg_status = 0
  220. def _checker_messages(self, checker):
  221. for known_checker in self._checkers[checker.lower()]:
  222. for msgid in known_checker.msgs:
  223. yield msgid
  224. def disable(self, msgid, scope='package', line=None, ignore_unknown=False):
  225. """don't output message of the given id"""
  226. self._set_msg_status(msgid, enable=False, scope=scope,
  227. line=line, ignore_unknown=ignore_unknown)
  228. def enable(self, msgid, scope='package', line=None, ignore_unknown=False):
  229. """reenable message of the given id"""
  230. self._set_msg_status(msgid, enable=True, scope=scope,
  231. line=line, ignore_unknown=ignore_unknown)
  232. def _set_msg_status(self, msgid, enable, scope='package', line=None, ignore_unknown=False):
  233. assert scope in ('package', 'module')
  234. if msgid == 'all':
  235. for _msgid in MSG_TYPES:
  236. self._set_msg_status(_msgid, enable, scope, line, ignore_unknown)
  237. if enable and not self._python3_porting_mode:
  238. # Don't activate the python 3 porting checker if it wasn't activated explicitly.
  239. self.disable('python3')
  240. return
  241. # msgid is a category?
  242. catid = category_id(msgid)
  243. if catid is not None:
  244. for _msgid in self.msgs_store._msgs_by_category.get(catid):
  245. self._set_msg_status(_msgid, enable, scope, line)
  246. return
  247. # msgid is a checker name?
  248. if msgid.lower() in self._checkers:
  249. msgs_store = self.msgs_store
  250. for checker in self._checkers[msgid.lower()]:
  251. for _msgid in checker.msgs:
  252. if _msgid in msgs_store._alternative_names:
  253. self._set_msg_status(_msgid, enable, scope, line)
  254. return
  255. # msgid is report id?
  256. if msgid.lower().startswith('rp'):
  257. if enable:
  258. self.enable_report(msgid)
  259. else:
  260. self.disable_report(msgid)
  261. return
  262. try:
  263. # msgid is a symbolic or numeric msgid.
  264. msg = self.msgs_store.check_message_id(msgid)
  265. except UnknownMessageError:
  266. if ignore_unknown:
  267. return
  268. raise
  269. if scope == 'module':
  270. self.file_state.set_msg_status(msg, line, enable)
  271. if enable:
  272. self.add_message('locally-enabled', line=line,
  273. args=(msg.symbol, msg.msgid))
  274. elif msg.symbol != 'locally-disabled':
  275. self.add_message('locally-disabled', line=line,
  276. args=(msg.symbol, msg.msgid))
  277. else:
  278. msgs = self._msgs_state
  279. msgs[msg.msgid] = enable
  280. # sync configuration object
  281. self.config.enable = [self._message_symbol(mid) for mid, val
  282. in sorted(six.iteritems(msgs)) if val]
  283. self.config.disable = [self._message_symbol(mid) for mid, val
  284. in sorted(six.iteritems(msgs)) if not val]
  285. def _message_symbol(self, msgid):
  286. """Get the message symbol of the given message id
  287. Return the original message id if the message does not
  288. exist.
  289. """
  290. try:
  291. return self.msgs_store.check_message_id(msgid).symbol
  292. except UnknownMessageError:
  293. return msgid
  294. def get_message_state_scope(self, msgid, line=None, confidence=UNDEFINED):
  295. """Returns the scope at which a message was enabled/disabled."""
  296. if self.config.confidence and confidence.name not in self.config.confidence:
  297. return MSG_STATE_CONFIDENCE
  298. try:
  299. if line in self.file_state._module_msgs_state[msgid]:
  300. return MSG_STATE_SCOPE_MODULE
  301. except (KeyError, TypeError):
  302. return MSG_STATE_SCOPE_CONFIG
  303. return None
  304. def is_message_enabled(self, msg_descr, line=None, confidence=None):
  305. """return true if the message associated to the given message id is
  306. enabled
  307. msgid may be either a numeric or symbolic message id.
  308. """
  309. if self.config.confidence and confidence:
  310. if confidence.name not in self.config.confidence:
  311. return False
  312. try:
  313. msgid = self.msgs_store.check_message_id(msg_descr).msgid
  314. except UnknownMessageError:
  315. # The linter checks for messages that are not registered
  316. # due to version mismatch, just treat them as message IDs
  317. # for now.
  318. msgid = msg_descr
  319. if line is None:
  320. return self._msgs_state.get(msgid, True)
  321. try:
  322. return self.file_state._module_msgs_state[msgid][line]
  323. except KeyError:
  324. return self._msgs_state.get(msgid, True)
  325. def add_message(self, msg_descr, line=None, node=None, args=None, confidence=UNDEFINED):
  326. """Adds a message given by ID or name.
  327. If provided, the message string is expanded using args
  328. AST checkers should must the node argument (but may optionally
  329. provide line if the line number is different), raw and token checkers
  330. must provide the line argument.
  331. """
  332. msg_info = self.msgs_store.check_message_id(msg_descr)
  333. msgid = msg_info.msgid
  334. # backward compatibility, message may not have a symbol
  335. symbol = msg_info.symbol or msgid
  336. # Fatal messages and reports are special, the node/scope distinction
  337. # does not apply to them.
  338. if msgid[0] not in _SCOPE_EXEMPT:
  339. if msg_info.scope == WarningScope.LINE:
  340. if line is None:
  341. raise InvalidMessageError(
  342. 'Message %s must provide line, got None' % msgid)
  343. if node is not None:
  344. raise InvalidMessageError(
  345. 'Message %s must only provide line, '
  346. 'got line=%s, node=%s' % (msgid, line, node))
  347. elif msg_info.scope == WarningScope.NODE:
  348. # Node-based warnings may provide an override line.
  349. if node is None:
  350. raise InvalidMessageError(
  351. 'Message %s must provide Node, got None' % msgid)
  352. if line is None and node is not None:
  353. line = node.fromlineno
  354. if hasattr(node, 'col_offset'):
  355. col_offset = node.col_offset # XXX measured in bytes for utf-8, divide by two for chars?
  356. else:
  357. col_offset = None
  358. # should this message be displayed
  359. if not self.is_message_enabled(msgid, line, confidence):
  360. self.file_state.handle_ignored_message(
  361. self.get_message_state_scope(msgid, line, confidence),
  362. msgid, line, node, args, confidence)
  363. return
  364. # update stats
  365. msg_cat = MSG_TYPES[msgid[0]]
  366. self.msg_status |= MSG_TYPES_STATUS[msgid[0]]
  367. self.stats[msg_cat] += 1
  368. self.stats['by_module'][self.current_name][msg_cat] += 1
  369. try:
  370. self.stats['by_msg'][symbol] += 1
  371. except KeyError:
  372. self.stats['by_msg'][symbol] = 1
  373. # expand message ?
  374. msg = msg_info.msg
  375. if args:
  376. msg %= args
  377. # get module and object
  378. if node is None:
  379. module, obj = self.current_name, ''
  380. abspath = self.current_file
  381. else:
  382. module, obj = get_module_and_frameid(node)
  383. abspath = node.root().file
  384. path = abspath.replace(self.reporter.path_strip_prefix, '')
  385. # add the message
  386. self.reporter.handle_message(
  387. Message(msgid, symbol,
  388. (abspath, path, module, obj, line or 1, col_offset or 0), msg, confidence))
  389. def print_full_documentation(self, stream=None):
  390. """output a full documentation in ReST format"""
  391. if not stream:
  392. stream = sys.stdout
  393. print("Pylint global options and switches", file=stream)
  394. print("----------------------------------", file=stream)
  395. print("", file=stream)
  396. print("Pylint provides global options and switches.", file=stream)
  397. print("", file=stream)
  398. by_checker = {}
  399. for checker in self.get_checkers():
  400. if checker.name == 'master':
  401. if checker.options:
  402. for section, options in checker.options_by_section():
  403. if section is None:
  404. title = 'General options'
  405. else:
  406. title = '%s options' % section.capitalize()
  407. print(title, file=stream)
  408. print('~' * len(title), file=stream)
  409. _rest_format_section(stream, None, options)
  410. print("", file=stream)
  411. else:
  412. name = checker.name
  413. try:
  414. by_checker[name]['options'] += checker.options_and_values()
  415. by_checker[name]['msgs'].update(checker.msgs)
  416. by_checker[name]['reports'] += checker.reports
  417. except KeyError:
  418. by_checker[name] = {
  419. 'options': list(checker.options_and_values()),
  420. 'msgs': dict(checker.msgs),
  421. 'reports': list(checker.reports),
  422. }
  423. print("Pylint checkers' options and switches", file=stream)
  424. print("-------------------------------------", file=stream)
  425. print("", file=stream)
  426. print("Pylint checkers can provide three set of features:", file=stream)
  427. print("", file=stream)
  428. print("* options that control their execution,", file=stream)
  429. print("* messages that they can raise,", file=stream)
  430. print("* reports that they can generate.", file=stream)
  431. print("", file=stream)
  432. print("Below is a list of all checkers and their features.", file=stream)
  433. print("", file=stream)
  434. for checker, info in sorted(six.iteritems(by_checker)):
  435. self._print_checker_doc(checker, info, stream=stream)
  436. @staticmethod
  437. def _print_checker_doc(checker_name, info, stream=None):
  438. """Helper method for print_full_documentation.
  439. Also used by doc/exts/pylint_extensions.py.
  440. """
  441. if not stream:
  442. stream = sys.stdout
  443. doc = info.get('doc')
  444. module = info.get('module')
  445. msgs = info.get('msgs')
  446. options = info.get('options')
  447. reports = info.get('reports')
  448. title = '%s checker' % (checker_name.replace("_", " ").title())
  449. if module:
  450. # Provide anchor to link against
  451. print(".. _%s:\n" % module, file=stream)
  452. print(title, file=stream)
  453. print('~' * len(title), file=stream)
  454. print("", file=stream)
  455. if module:
  456. print("This checker is provided by ``%s``." % module, file=stream)
  457. print("Verbatim name of the checker is ``%s``." % checker_name, file=stream)
  458. print("", file=stream)
  459. if doc:
  460. title = 'Documentation'
  461. print(title, file=stream)
  462. print('^' * len(title), file=stream)
  463. print(cleandoc(doc), file=stream)
  464. print("", file=stream)
  465. if options:
  466. title = 'Options'
  467. print(title, file=stream)
  468. print('^' * len(title), file=stream)
  469. _rest_format_section(stream, None, options)
  470. print("", file=stream)
  471. if msgs:
  472. title = 'Messages'
  473. print(title, file=stream)
  474. print('^' * len(title), file=stream)
  475. for msgid, msg in sorted(six.iteritems(msgs),
  476. key=lambda kv: (_MSG_ORDER.index(kv[0][0]), kv[1])):
  477. msg = build_message_def(checker_name, msgid, msg)
  478. print(msg.format_help(checkerref=False), file=stream)
  479. print("", file=stream)
  480. if reports:
  481. title = 'Reports'
  482. print(title, file=stream)
  483. print('^' * len(title), file=stream)
  484. for report in reports:
  485. print(':%s: %s' % report[:2], file=stream)
  486. print("", file=stream)
  487. print("", file=stream)
  488. class FileState(object):
  489. """Hold internal state specific to the currently analyzed file"""
  490. def __init__(self, modname=None):
  491. self.base_name = modname
  492. self._module_msgs_state = {}
  493. self._raw_module_msgs_state = {}
  494. self._ignored_msgs = collections.defaultdict(set)
  495. self._suppression_mapping = {}
  496. def collect_block_lines(self, msgs_store, module_node):
  497. """Walk the AST to collect block level options line numbers."""
  498. for msg, lines in six.iteritems(self._module_msgs_state):
  499. self._raw_module_msgs_state[msg] = lines.copy()
  500. orig_state = self._module_msgs_state.copy()
  501. self._module_msgs_state = {}
  502. self._suppression_mapping = {}
  503. self._collect_block_lines(msgs_store, module_node, orig_state)
  504. def _collect_block_lines(self, msgs_store, node, msg_state):
  505. """Recursively walk (depth first) AST to collect block level options
  506. line numbers.
  507. """
  508. for child in node.get_children():
  509. self._collect_block_lines(msgs_store, child, msg_state)
  510. first = node.fromlineno
  511. last = node.tolineno
  512. # first child line number used to distinguish between disable
  513. # which are the first child of scoped node with those defined later.
  514. # For instance in the code below:
  515. #
  516. # 1. def meth8(self):
  517. # 2. """test late disabling"""
  518. # 3. # pylint: disable=E1102
  519. # 4. print self.blip
  520. # 5. # pylint: disable=E1101
  521. # 6. print self.bla
  522. #
  523. # E1102 should be disabled from line 1 to 6 while E1101 from line 5 to 6
  524. #
  525. # this is necessary to disable locally messages applying to class /
  526. # function using their fromlineno
  527. if (isinstance(node, (nodes.Module, nodes.ClassDef, nodes.FunctionDef))
  528. and node.body):
  529. firstchildlineno = node.body[0].fromlineno
  530. else:
  531. firstchildlineno = last
  532. for msgid, lines in six.iteritems(msg_state):
  533. for lineno, state in list(lines.items()):
  534. original_lineno = lineno
  535. if first > lineno or last < lineno:
  536. continue
  537. # Set state for all lines for this block, if the
  538. # warning is applied to nodes.
  539. if msgs_store.check_message_id(msgid).scope == WarningScope.NODE:
  540. if lineno > firstchildlineno:
  541. state = True
  542. first_, last_ = node.block_range(lineno)
  543. else:
  544. first_ = lineno
  545. last_ = last
  546. for line in range(first_, last_+1):
  547. # do not override existing entries
  548. if line in self._module_msgs_state.get(msgid, ()):
  549. continue
  550. if line in lines: # state change in the same block
  551. state = lines[line]
  552. original_lineno = line
  553. if not state:
  554. self._suppression_mapping[(msgid, line)] = original_lineno
  555. try:
  556. self._module_msgs_state[msgid][line] = state
  557. except KeyError:
  558. self._module_msgs_state[msgid] = {line: state}
  559. del lines[lineno]
  560. def set_msg_status(self, msg, line, status):
  561. """Set status (enabled/disable) for a given message at a given line"""
  562. assert line > 0
  563. try:
  564. self._module_msgs_state[msg.msgid][line] = status
  565. except KeyError:
  566. self._module_msgs_state[msg.msgid] = {line: status}
  567. def handle_ignored_message(self, state_scope, msgid, line,
  568. node, args, confidence): # pylint: disable=unused-argument
  569. """Report an ignored message.
  570. state_scope is either MSG_STATE_SCOPE_MODULE or MSG_STATE_SCOPE_CONFIG,
  571. depending on whether the message was disabled locally in the module,
  572. or globally. The other arguments are the same as for add_message.
  573. """
  574. if state_scope == MSG_STATE_SCOPE_MODULE:
  575. try:
  576. orig_line = self._suppression_mapping[(msgid, line)]
  577. self._ignored_msgs[(msgid, orig_line)].add(line)
  578. except KeyError:
  579. pass
  580. def iter_spurious_suppression_messages(self, msgs_store):
  581. for warning, lines in six.iteritems(self._raw_module_msgs_state):
  582. for line, enable in six.iteritems(lines):
  583. if not enable and (warning, line) not in self._ignored_msgs:
  584. yield 'useless-suppression', line, \
  585. (msgs_store.get_msg_display_string(warning),)
  586. # don't use iteritems here, _ignored_msgs may be modified by add_message
  587. for (warning, from_), lines in list(self._ignored_msgs.items()):
  588. for line in lines:
  589. yield 'suppressed-message', line, \
  590. (msgs_store.get_msg_display_string(warning), from_)
  591. class MessagesStore(object):
  592. """The messages store knows information about every possible message but has
  593. no particular state during analysis.
  594. """
  595. def __init__(self):
  596. # Primary registry for all active messages (i.e. all messages
  597. # that can be emitted by pylint for the underlying Python
  598. # version). It contains the 1:1 mapping from symbolic names
  599. # to message definition objects.
  600. self._messages = {}
  601. # Maps alternative names (numeric IDs, deprecated names) to
  602. # message definitions. May contain several names for each definition
  603. # object.
  604. self._alternative_names = {}
  605. self._msgs_by_category = collections.defaultdict(list)
  606. @property
  607. def messages(self):
  608. """The list of all active messages."""
  609. return six.itervalues(self._messages)
  610. def add_renamed_message(self, old_id, old_symbol, new_symbol):
  611. """Register the old ID and symbol for a warning that was renamed.
  612. This allows users to keep using the old ID/symbol in suppressions.
  613. """
  614. msg = self.check_message_id(new_symbol)
  615. msg.old_names.append((old_id, old_symbol))
  616. self._register_alternative_name(msg, old_id)
  617. self._register_alternative_name(msg, old_symbol)
  618. def register_messages(self, checker):
  619. """register a dictionary of messages
  620. Keys are message ids, values are a 2-uple with the message type and the
  621. message itself
  622. message ids should be a string of len 4, where the two first characters
  623. are the checker id and the two last the message id in this checker
  624. """
  625. chkid = None
  626. for msgid, msg_tuple in sorted(six.iteritems(checker.msgs)):
  627. msg = build_message_def(checker, msgid, msg_tuple)
  628. # avoid duplicate / malformed ids
  629. if msg.symbol in self._messages or msg.symbol in self._alternative_names:
  630. raise InvalidMessageError(
  631. 'Message symbol %r is already defined' % msg.symbol)
  632. if chkid is not None and chkid != msg.msgid[1:3]:
  633. raise InvalidMessageError(
  634. "Inconsistent checker part in message id %r (expected 'x%sxx')"
  635. % (msgid, chkid))
  636. chkid = msg.msgid[1:3]
  637. self._messages[msg.symbol] = msg
  638. self._register_alternative_name(msg, msg.msgid)
  639. for old_id, old_symbol in msg.old_names:
  640. self._register_alternative_name(msg, old_id)
  641. self._register_alternative_name(msg, old_symbol)
  642. self._msgs_by_category[msg.msgid[0]].append(msg.msgid)
  643. def _register_alternative_name(self, msg, name):
  644. """helper for register_message()"""
  645. if name in self._messages and self._messages[name] != msg:
  646. raise InvalidMessageError(
  647. 'Message symbol %r is already defined' % name)
  648. if name in self._alternative_names and self._alternative_names[name] != msg:
  649. raise InvalidMessageError(
  650. 'Message %s %r is already defined' % (
  651. 'id' if len(name) == 5 and name[0] in MSG_TYPES else 'alternate name',
  652. name))
  653. self._alternative_names[name] = msg
  654. def check_message_id(self, msgid):
  655. """returns the Message object for this message.
  656. msgid may be either a numeric or symbolic id.
  657. Raises UnknownMessageError if the message id is not defined.
  658. """
  659. if msgid[1:].isdigit():
  660. msgid = msgid.upper()
  661. for source in (self._alternative_names, self._messages):
  662. try:
  663. return source[msgid]
  664. except KeyError:
  665. pass
  666. raise UnknownMessageError('No such message id %s' % msgid)
  667. def get_msg_display_string(self, msgid):
  668. """Generates a user-consumable representation of a message.
  669. Can be just the message ID or the ID and the symbol.
  670. """
  671. return repr(self.check_message_id(msgid).symbol)
  672. def help_message(self, msgids):
  673. """display help messages for the given message identifiers"""
  674. for msgid in msgids:
  675. try:
  676. print(self.check_message_id(msgid).format_help(checkerref=True))
  677. print("")
  678. except UnknownMessageError as ex:
  679. print(ex)
  680. print("")
  681. continue
  682. def list_messages(self):
  683. """output full messages list documentation in ReST format"""
  684. msgs = sorted(six.itervalues(self._messages), key=lambda msg: msg.msgid)
  685. for msg in msgs:
  686. if not msg.may_be_emitted():
  687. continue
  688. print(msg.format_help(checkerref=False))
  689. print("")
  690. class ReportsHandlerMixIn(object):
  691. """a mix-in class containing all the reports and stats manipulation
  692. related methods for the main lint class
  693. """
  694. def __init__(self):
  695. self._reports = collections.defaultdict(list)
  696. self._reports_state = {}
  697. def report_order(self):
  698. """ Return a list of reports, sorted in the order
  699. in which they must be called.
  700. """
  701. return list(self._reports)
  702. def register_report(self, reportid, r_title, r_cb, checker):
  703. """register a report
  704. reportid is the unique identifier for the report
  705. r_title the report's title
  706. r_cb the method to call to make the report
  707. checker is the checker defining the report
  708. """
  709. reportid = reportid.upper()
  710. self._reports[checker].append((reportid, r_title, r_cb))
  711. def enable_report(self, reportid):
  712. """disable the report of the given id"""
  713. reportid = reportid.upper()
  714. self._reports_state[reportid] = True
  715. def disable_report(self, reportid):
  716. """disable the report of the given id"""
  717. reportid = reportid.upper()
  718. self._reports_state[reportid] = False
  719. def report_is_enabled(self, reportid):
  720. """return true if the report associated to the given identifier is
  721. enabled
  722. """
  723. return self._reports_state.get(reportid, True)
  724. def make_reports(self, stats, old_stats):
  725. """render registered reports"""
  726. sect = Section('Report',
  727. '%s statements analysed.'% (self.stats['statement']))
  728. for checker in self.report_order():
  729. for reportid, r_title, r_cb in self._reports[checker]:
  730. if not self.report_is_enabled(reportid):
  731. continue
  732. report_sect = Section(r_title)
  733. try:
  734. r_cb(report_sect, stats, old_stats)
  735. except EmptyReportError:
  736. continue
  737. report_sect.report_id = reportid
  738. sect.append(report_sect)
  739. return sect
  740. def add_stats(self, **kwargs):
  741. """add some stats entries to the statistic dictionary
  742. raise an AssertionError if there is a key conflict
  743. """
  744. for key, value in six.iteritems(kwargs):
  745. if key[-1] == '_':
  746. key = key[:-1]
  747. assert key not in self.stats
  748. self.stats[key] = value
  749. return self.stats
  750. def _basename_in_blacklist_re(base_name, black_list_re):
  751. """Determines if the basename is matched in a regex blacklist
  752. :param str base_name: The basename of the file
  753. :param list black_list_re: A collection of regex patterns to match against.
  754. Successful matches are blacklisted.
  755. :returns: `True` if the basename is blacklisted, `False` otherwise.
  756. :rtype: bool
  757. """
  758. for file_pattern in black_list_re:
  759. if file_pattern.match(base_name):
  760. return True
  761. return False
  762. def _modpath_from_file(filename, is_namespace):
  763. def _is_package_cb(path, parts):
  764. return modutils.check_modpath_has_init(path, parts) or is_namespace
  765. return modutils.modpath_from_file_with_callback(filename, is_package_cb=_is_package_cb)
  766. def expand_modules(files_or_modules, black_list, black_list_re):
  767. """take a list of files/modules/packages and return the list of tuple
  768. (file, module name) which have to be actually checked
  769. """
  770. result = []
  771. errors = []
  772. for something in files_or_modules:
  773. if os.path.basename(something) in black_list:
  774. continue
  775. if _basename_in_blacklist_re(os.path.basename(something), black_list_re):
  776. continue
  777. if exists(something):
  778. # this is a file or a directory
  779. try:
  780. modname = '.'.join(modutils.modpath_from_file(something))
  781. except ImportError:
  782. modname = splitext(basename(something))[0]
  783. if isdir(something):
  784. filepath = join(something, '__init__.py')
  785. else:
  786. filepath = something
  787. else:
  788. # suppose it's a module or package
  789. modname = something
  790. try:
  791. filepath = modutils.file_from_modpath(modname.split('.'))
  792. if filepath is None:
  793. continue
  794. except (ImportError, SyntaxError) as ex:
  795. # FIXME p3k : the SyntaxError is a Python bug and should be
  796. # removed as soon as possible http://bugs.python.org/issue10588
  797. errors.append({'key': 'fatal', 'mod': modname, 'ex': ex})
  798. continue
  799. filepath = normpath(filepath)
  800. modparts = (modname or something).split('.')
  801. try:
  802. spec = modutils.file_info_from_modpath(modparts, path=sys.path)
  803. except ImportError:
  804. # Might not be acceptable, don't crash.
  805. is_namespace = False
  806. is_directory = isdir(something)
  807. else:
  808. is_namespace = modutils.is_namespace(spec)
  809. is_directory = modutils.is_directory(spec)
  810. if not is_namespace:
  811. result.append({'path': filepath, 'name': modname, 'isarg': True,
  812. 'basepath': filepath, 'basename': modname})
  813. has_init = (not (modname.endswith('.__init__') or modname == '__init__')
  814. and basename(filepath) == '__init__.py')
  815. if has_init or is_namespace or is_directory:
  816. for subfilepath in modutils.get_module_files(dirname(filepath), black_list,
  817. list_all=is_namespace):
  818. if filepath == subfilepath:
  819. continue
  820. if _basename_in_blacklist_re(basename(subfilepath), black_list_re):
  821. continue
  822. modpath = _modpath_from_file(subfilepath, is_namespace)
  823. submodname = '.'.join(modpath)
  824. result.append({'path': subfilepath, 'name': submodname,
  825. 'isarg': False,
  826. 'basepath': filepath, 'basename': modname})
  827. return result, errors
  828. class PyLintASTWalker(object):
  829. def __init__(self, linter):
  830. # callbacks per node types
  831. self.nbstatements = 0
  832. self.visit_events = collections.defaultdict(list)
  833. self.leave_events = collections.defaultdict(list)
  834. self.linter = linter
  835. def _is_method_enabled(self, method):
  836. if not hasattr(method, 'checks_msgs'):
  837. return True
  838. for msg_desc in method.checks_msgs:
  839. if self.linter.is_message_enabled(msg_desc):
  840. return True
  841. return False
  842. def add_checker(self, checker):
  843. """walk to the checker's dir and collect visit and leave methods"""
  844. # XXX : should be possible to merge needed_checkers and add_checker
  845. vcids = set()
  846. lcids = set()
  847. visits = self.visit_events
  848. leaves = self.leave_events
  849. for member in dir(checker):
  850. cid = member[6:]
  851. if cid == 'default':
  852. continue
  853. if member.startswith('visit_'):
  854. v_meth = getattr(checker, member)
  855. # don't use visit_methods with no activated message:
  856. if self._is_method_enabled(v_meth):
  857. visits[cid].append(v_meth)
  858. vcids.add(cid)
  859. elif member.startswith('leave_'):
  860. l_meth = getattr(checker, member)
  861. # don't use leave_methods with no activated message:
  862. if self._is_method_enabled(l_meth):
  863. leaves[cid].append(l_meth)
  864. lcids.add(cid)
  865. visit_default = getattr(checker, 'visit_default', None)
  866. if visit_default:
  867. for cls in nodes.ALL_NODE_CLASSES:
  868. cid = cls.__name__.lower()
  869. if cid not in vcids:
  870. visits[cid].append(visit_default)
  871. # for now we have no "leave_default" method in Pylint
  872. def walk(self, astroid):
  873. """call visit events of astroid checkers for the given node, recurse on
  874. its children, then leave events.
  875. """
  876. cid = astroid.__class__.__name__.lower()
  877. # Detect if the node is a new name for a deprecated alias.
  878. # In this case, favour the methods for the deprecated
  879. # alias if any, in order to maintain backwards
  880. # compatibility.
  881. visit_events = ()
  882. leave_events = ()
  883. visit_events = self.visit_events.get(cid, ())
  884. leave_events = self.leave_events.get(cid, ())
  885. if astroid.is_statement:
  886. self.nbstatements += 1
  887. # generate events for this node on each checker
  888. for cb in visit_events or ():
  889. cb(astroid)
  890. # recurse on children
  891. for child in astroid.get_children():
  892. self.walk(child)
  893. for cb in leave_events or ():
  894. cb(astroid)
  895. PY_EXTS = ('.py', '.pyc', '.pyo', '.pyw', '.so', '.dll')
  896. def register_plugins(linter, directory):
  897. """load all module and package in the given directory, looking for a
  898. 'register' function in each one, used to register pylint checkers
  899. """
  900. imported = {}
  901. for filename in os.listdir(directory):
  902. base, extension = splitext(filename)
  903. if base in imported or base == '__pycache__':
  904. continue
  905. if extension in PY_EXTS and base != '__init__' or (
  906. not extension and isdir(join(directory, base))):
  907. try:
  908. module = modutils.load_module_from_file(join(directory, filename))
  909. except ValueError:
  910. # empty module name (usually emacs auto-save files)
  911. continue
  912. except ImportError as exc:
  913. print("Problem importing module %s: %s" % (filename, exc),
  914. file=sys.stderr)
  915. else:
  916. if hasattr(module, 'register'):
  917. module.register(linter)
  918. imported[base] = 1
  919. def get_global_option(checker, option, default=None):
  920. """ Retrieve an option defined by the given *checker* or
  921. by all known option providers.
  922. It will look in the list of all options providers
  923. until the given *option* will be found.
  924. If the option wasn't found, the *default* value will be returned.
  925. """
  926. # First, try in the given checker's config.
  927. # After that, look in the options providers.
  928. try:
  929. return getattr(checker.config, option.replace("-", "_"))
  930. except AttributeError:
  931. pass
  932. for provider in checker.linter.options_providers:
  933. for options in provider.options:
  934. if options[0] == option:
  935. return getattr(provider.config, option.replace("-", "_"))
  936. return default
  937. def deprecated_option(shortname=None, opt_type=None, help_msg=None, deprecation_msg=None):
  938. def _warn_deprecated(option, optname, *args): # pylint: disable=unused-argument
  939. if deprecation_msg:
  940. sys.stderr.write(deprecation_msg % (optname,))
  941. option = {
  942. 'help': help_msg,
  943. 'hide': True,
  944. 'type': opt_type,
  945. 'action': 'callback',
  946. 'callback': _warn_deprecated,
  947. 'deprecated': True
  948. }
  949. if shortname:
  950. option['shortname'] = shortname
  951. return option
  952. def _splitstrip(string, sep=','):
  953. """return a list of stripped string by splitting the string given as
  954. argument on `sep` (',' by default). Empty string are discarded.
  955. >>> _splitstrip('a, b, c , 4,,')
  956. ['a', 'b', 'c', '4']
  957. >>> _splitstrip('a')
  958. ['a']
  959. >>> _splitstrip('a,\nb,\nc,')
  960. ['a', 'b', 'c']
  961. :type string: str or unicode
  962. :param string: a csv line
  963. :type sep: str or unicode
  964. :param sep: field separator, default to the comma (',')
  965. :rtype: str or unicode
  966. :return: the unquoted string (or the input string if it wasn't quoted)
  967. """
  968. return [word.strip() for word in string.split(sep) if word.strip()]
  969. def _unquote(string):
  970. """remove optional quotes (simple or double) from the string
  971. :type string: str or unicode
  972. :param string: an optionally quoted string
  973. :rtype: str or unicode
  974. :return: the unquoted string (or the input string if it wasn't quoted)
  975. """
  976. if not string:
  977. return string
  978. if string[0] in '"\'':
  979. string = string[1:]
  980. if string[-1] in '"\'':
  981. string = string[:-1]
  982. return string
  983. def _normalize_text(text, line_len=80, indent=''):
  984. """Wrap the text on the given line length."""
  985. return '\n'.join(textwrap.wrap(text, width=line_len, initial_indent=indent,
  986. subsequent_indent=indent))
  987. def _check_csv(value):
  988. if isinstance(value, (list, tuple)):
  989. return value
  990. return _splitstrip(value)
  991. if six.PY2:
  992. def _encode(string, encoding):
  993. # pylint: disable=undefined-variable
  994. if isinstance(string, unicode):
  995. return string.encode(encoding)
  996. return str(string)
  997. else:
  998. def _encode(string, _):
  999. return str(string)
  1000. def _get_encoding(encoding, stream):
  1001. encoding = encoding or getattr(stream, 'encoding', None)
  1002. if not encoding:
  1003. import locale
  1004. encoding = locale.getpreferredencoding()
  1005. return encoding
  1006. def _comment(string):
  1007. """return string as a comment"""
  1008. lines = [line.strip() for line in string.splitlines()]
  1009. return '# ' + ('%s# ' % os.linesep).join(lines)
  1010. def _format_option_value(optdict, value):
  1011. """return the user input's value from a 'compiled' value"""
  1012. if isinstance(value, (list, tuple)):
  1013. value = ','.join(_format_option_value(optdict, item) for item in value)
  1014. elif isinstance(value, dict):
  1015. value = ','.join('%s:%s' % (k, v) for k, v in value.items())
  1016. elif hasattr(value, 'match'): # optdict.get('type') == 'regexp'
  1017. # compiled regexp
  1018. value = value.pattern
  1019. elif optdict.get('type') == 'yn':
  1020. value = 'yes' if value else 'no'
  1021. elif isinstance(value, six.string_types) and value.isspace():
  1022. value = "'%s'" % value
  1023. return value
  1024. def _ini_format_section(stream, section, options, encoding=None, doc=None):
  1025. """format an options section using the INI format"""
  1026. encoding = _get_encoding(encoding, stream)
  1027. if doc:
  1028. print(_encode(_comment(doc), encoding), file=stream)
  1029. print('[%s]' % section, file=stream)
  1030. _ini_format(stream, options, encoding)
  1031. def _ini_format(stream, options, encoding):
  1032. """format options using the INI format"""
  1033. for optname, optdict, value in options:
  1034. value = _format_option_value(optdict, value)
  1035. help = optdict.get('help')
  1036. if help:
  1037. help = _normalize_text(help, line_len=79, indent='# ')
  1038. print(file=stream)
  1039. print(_encode(help, encoding), file=stream)
  1040. else:
  1041. print(file=stream)
  1042. if value is None:
  1043. print('#%s=' % optname, file=stream)
  1044. else:
  1045. value = _encode(value, encoding).strip()
  1046. if re.match(r'^([\w-]+,)+[\w-]+$', str(value)):
  1047. separator = '\n ' + ' ' * len(optname)
  1048. value = separator.join(
  1049. x + ',' for x in str(value).split(','))
  1050. # remove trailing ',' from last element of the list
  1051. value = value[:-1]
  1052. print('%s=%s' % (optname, value), file=stream)
  1053. format_section = _ini_format_section
  1054. def _rest_format_section(stream, section, options, encoding=None, doc=None):
  1055. """format an options section using as ReST formatted output"""
  1056. encoding = _get_encoding(encoding, stream)
  1057. if section:
  1058. print('%s\n%s' % (section, "'"*len(section)), file=stream)
  1059. if doc:
  1060. print(_encode(_normalize_text(doc, line_len=79, indent=''), encoding), file=stream)
  1061. print(file=stream)
  1062. for optname, optdict, value in options:
  1063. help = optdict.get('help')
  1064. print(':%s:' % optname, file=stream)
  1065. if help:
  1066. help = _normalize_text(help, line_len=79, indent=' ')
  1067. print(_encode(help, encoding), file=stream)
  1068. if value:
  1069. value = _encode(_format_option_value(optdict, value), encoding)
  1070. print(file=stream)
  1071. print(' Default: ``%s``' % value.replace("`` ", "```` ``"), file=stream)