lint.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. # Copyright (c) 2003-2010 Sylvain Thenault (thenault@gmail.com).
  2. # Copyright (c) 2003-2012 LOGILAB S.A. (Paris, FRANCE).
  3. # http://www.logilab.fr/ -- mailto:contact@logilab.fr
  4. #
  5. # This program is free software; you can redistribute it and/or modify it under
  6. # the terms of the GNU General Public License as published by the Free Software
  7. # Foundation; either version 2 of the License, or (at your option) any later
  8. # version.
  9. #
  10. # This program is distributed in the hope that it will be useful, but WITHOUT
  11. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  12. # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details
  13. #
  14. # You should have received a copy of the GNU General Public License along with
  15. # this program; if not, write to the Free Software Foundation, Inc.,
  16. # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  17. """ %prog [options] module_or_package
  18. Check that a module satisfy a coding standard (and more !).
  19. %prog --help
  20. Display this help message and exit.
  21. %prog --help-msg <msg-id>[,<msg-id>]
  22. Display help messages about given message identifiers and exit.
  23. """
  24. # import this first to avoid builtin namespace pollution
  25. from pylint.checkers import utils
  26. import sys
  27. import os
  28. import re
  29. import tokenize
  30. from warnings import warn
  31. from logilab.common.configuration import UnsupportedAction, OptionsManagerMixIn
  32. from logilab.common.optik_ext import check_csv
  33. from logilab.common.modutils import load_module_from_name
  34. from logilab.common.interface import implements
  35. from logilab.common.textutils import splitstrip
  36. from logilab.common.ureports import Table, Text, Section
  37. from logilab.common.__pkginfo__ import version as common_version
  38. from logilab.astng import MANAGER, nodes, ASTNGBuildingException
  39. from logilab.astng.__pkginfo__ import version as astng_version
  40. from pylint.utils import PyLintASTWalker, UnknownMessage, MessagesHandlerMixIn,\
  41. ReportsHandlerMixIn, MSG_TYPES, expand_modules
  42. from pylint.interfaces import ILinter, IRawChecker, IASTNGChecker
  43. from pylint.checkers import BaseRawChecker, EmptyReport, \
  44. table_lines_from_stats
  45. from pylint.reporters.text import TextReporter, ParseableTextReporter, \
  46. VSTextReporter, ColorizedTextReporter
  47. from pylint.reporters.html import HTMLReporter
  48. from pylint import config
  49. from pylint.__pkginfo__ import version
  50. OPTION_RGX = re.compile('\s*#*\s*pylint:(.*)')
  51. REPORTER_OPT_MAP = {'text': TextReporter,
  52. 'parseable': ParseableTextReporter,
  53. 'msvs': VSTextReporter,
  54. 'colorized': ColorizedTextReporter,
  55. 'html': HTMLReporter,}
  56. def _get_python_path(filepath):
  57. dirname = os.path.dirname(os.path.realpath(
  58. os.path.expanduser(filepath)))
  59. while True:
  60. if not os.path.exists(os.path.join(dirname, "__init__.py")):
  61. return dirname
  62. old_dirname = dirname
  63. dirname = os.path.dirname(dirname)
  64. if old_dirname == dirname:
  65. return os.getcwd()
  66. # Python Linter class #########################################################
  67. MSGS = {
  68. 'F0001': ('%s',
  69. 'Used when an error occurred preventing the analysis of a \
  70. module (unable to find it for instance).'),
  71. 'F0002': ('%s: %s',
  72. 'Used when an unexpected error occurred while building the ASTNG \
  73. representation. This is usually accompanied by a traceback. \
  74. Please report such errors !'),
  75. 'F0003': ('ignored builtin module %s',
  76. 'Used to indicate that the user asked to analyze a builtin module\
  77. which has been skipped.'),
  78. 'F0004': ('unexpected inferred value %s',
  79. 'Used to indicate that some value of an unexpected type has been \
  80. inferred.'),
  81. 'F0010': ('error while code parsing: %s',
  82. 'Used when an exception occured while building the ASTNG \
  83. representation which could be handled by astng.'),
  84. 'I0001': ('Unable to run raw checkers on built-in module %s',
  85. 'Used to inform that a built-in module has not been checked \
  86. using the raw checkers.'),
  87. 'I0010': ('Unable to consider inline option %r',
  88. 'Used when an inline option is either badly formatted or can\'t \
  89. be used inside modules.'),
  90. 'I0011': ('Locally disabling %s',
  91. 'Used when an inline option disables a message or a messages \
  92. category.'),
  93. 'I0012': ('Locally enabling %s',
  94. 'Used when an inline option enables a message or a messages \
  95. category.'),
  96. 'I0013': ('Ignoring entire file',
  97. 'Used to inform that the file will not be checked'),
  98. 'E0001': ('%s',
  99. 'Used when a syntax error is raised for a module.'),
  100. 'E0011': ('Unrecognized file option %r',
  101. 'Used when an unknown inline option is encountered.'),
  102. 'E0012': ('Bad option value %r',
  103. 'Used when a bad value for an inline option is encountered.'),
  104. }
  105. class PyLinter(OptionsManagerMixIn, MessagesHandlerMixIn, ReportsHandlerMixIn,
  106. BaseRawChecker):
  107. """lint Python modules using external checkers.
  108. This is the main checker controlling the other ones and the reports
  109. generation. It is itself both a raw checker and an astng checker in order
  110. to:
  111. * handle message activation / deactivation at the module level
  112. * handle some basic but necessary stats'data (number of classes, methods...)
  113. IDE plugins developpers: you may have to call
  114. `logilab.astng.builder.MANAGER.astng_cache.clear()` accross run if you want
  115. to ensure the latest code version is actually checked.
  116. """
  117. __implements__ = (ILinter, IRawChecker)
  118. name = 'master'
  119. priority = 0
  120. level = 0
  121. msgs = MSGS
  122. may_be_disabled = False
  123. @staticmethod
  124. def make_options():
  125. return (('ignore',
  126. {'type' : 'csv', 'metavar' : '<file>[,<file>...]',
  127. 'dest' : 'black_list', 'default' : ('CVS',),
  128. 'help' : 'Add files or directories to the blacklist. \
  129. They should be base names, not paths.'}),
  130. ('persistent',
  131. {'default': True, 'type' : 'yn', 'metavar' : '<y_or_n>',
  132. 'level': 1,
  133. 'help' : 'Pickle collected data for later comparisons.'}),
  134. ('load-plugins',
  135. {'type' : 'csv', 'metavar' : '<modules>', 'default' : (),
  136. 'level': 1,
  137. 'help' : 'List of plugins (as comma separated values of \
  138. python modules names) to load, usually to register additional checkers.'}),
  139. ('output-format',
  140. {'default': 'text', 'type': 'choice', 'metavar' : '<format>',
  141. 'choices': REPORTER_OPT_MAP.keys(),
  142. 'short': 'f',
  143. 'group': 'Reports',
  144. 'help' : 'Set the output format. Available formats are text,\
  145. parseable, colorized, msvs (visual studio) and html'}),
  146. ('include-ids',
  147. {'type' : 'yn', 'metavar' : '<y_or_n>', 'default' : 0,
  148. 'short': 'i',
  149. 'group': 'Reports',
  150. 'help' : 'Include message\'s id in output'}),
  151. ('files-output',
  152. {'default': 0, 'type' : 'yn', 'metavar' : '<y_or_n>',
  153. 'group': 'Reports', 'level': 1,
  154. 'help' : 'Put messages in a separate file for each module / \
  155. package specified on the command line instead of printing them on stdout. \
  156. Reports (if any) will be written in a file name "pylint_global.[txt|html]".'}),
  157. ('reports',
  158. {'default': 1, 'type' : 'yn', 'metavar' : '<y_or_n>',
  159. 'short': 'r',
  160. 'group': 'Reports',
  161. 'help' : 'Tells whether to display a full report or only the\
  162. messages'}),
  163. ('evaluation',
  164. {'type' : 'string', 'metavar' : '<python_expression>',
  165. 'group': 'Reports', 'level': 1,
  166. 'default': '10.0 - ((float(5 * error + warning + refactor + \
  167. convention) / statement) * 10)',
  168. 'help' : 'Python expression which should return a note less \
  169. than 10 (10 is the highest note). You have access to the variables errors \
  170. warning, statement which respectively contain the number of errors / warnings\
  171. messages and the total number of statements analyzed. This is used by the \
  172. global evaluation report (RP0004).'}),
  173. ('comment',
  174. {'default': 0, 'type' : 'yn', 'metavar' : '<y_or_n>',
  175. 'group': 'Reports', 'level': 1,
  176. 'help' : 'Add a comment according to your evaluation note. \
  177. This is used by the global evaluation report (RP0004).'}),
  178. ('enable',
  179. {'type' : 'csv', 'metavar': '<msg ids>',
  180. 'short': 'e',
  181. 'group': 'Messages control',
  182. 'help' : 'Enable the message, report, category or checker with the '
  183. 'given id(s). You can either give multiple identifier '
  184. 'separated by comma (,) or put this option multiple time.'}),
  185. ('disable',
  186. {'type' : 'csv', 'metavar': '<msg ids>',
  187. 'short': 'd',
  188. 'group': 'Messages control',
  189. 'help' : 'Disable the message, report, category or checker '
  190. 'with the given id(s). You can either give multiple identifier'
  191. ' separated by comma (,) or put this option multiple time '
  192. '(only on the command line, not in the configuration file '
  193. 'where it should appear only once).'}),
  194. )
  195. option_groups = (
  196. ('Messages control', 'Options controling analysis messages'),
  197. ('Reports', 'Options related to output formating and reporting'),
  198. )
  199. def __init__(self, options=(), reporter=None, option_groups=(),
  200. pylintrc=None):
  201. # some stuff has to be done before ancestors initialization...
  202. #
  203. # checkers / reporter / astng manager
  204. self.reporter = None
  205. self._checkers = {}
  206. self._ignore_file = False
  207. # visit variables
  208. self.base_name = None
  209. self.base_file = None
  210. self.current_name = None
  211. self.current_file = None
  212. self.stats = None
  213. # init options
  214. self.options = options + PyLinter.make_options()
  215. self.option_groups = option_groups + PyLinter.option_groups
  216. self._options_methods = {
  217. 'enable': self.enable,
  218. 'disable': self.disable}
  219. self._bw_options_methods = {'disable-msg': self.disable,
  220. 'enable-msg': self.enable}
  221. full_version = '%%prog %s, \nastng %s, common %s\nPython %s' % (
  222. version, astng_version, common_version, sys.version)
  223. OptionsManagerMixIn.__init__(self, usage=__doc__,
  224. version=full_version,
  225. config_file=pylintrc or config.PYLINTRC)
  226. MessagesHandlerMixIn.__init__(self)
  227. ReportsHandlerMixIn.__init__(self)
  228. BaseRawChecker.__init__(self)
  229. # provided reports
  230. self.reports = (('RP0001', 'Messages by category',
  231. report_total_messages_stats),
  232. ('RP0002', '% errors / warnings by module',
  233. report_messages_by_module_stats),
  234. ('RP0003', 'Messages',
  235. report_messages_stats),
  236. ('RP0004', 'Global evaluation',
  237. self.report_evaluation),
  238. )
  239. self.register_checker(self)
  240. self._dynamic_plugins = []
  241. self.load_provider_defaults()
  242. self.set_reporter(reporter or TextReporter(sys.stdout))
  243. def load_default_plugins(self):
  244. from pylint import checkers
  245. checkers.initialize(self)
  246. def load_plugin_modules(self, modnames):
  247. """take a list of module names which are pylint plugins and load
  248. and register them
  249. """
  250. for modname in modnames:
  251. if modname in self._dynamic_plugins:
  252. continue
  253. self._dynamic_plugins.append(modname)
  254. module = load_module_from_name(modname)
  255. module.register(self)
  256. def set_reporter(self, reporter):
  257. """set the reporter used to display messages and reports"""
  258. self.reporter = reporter
  259. reporter.linter = self
  260. def set_option(self, optname, value, action=None, optdict=None):
  261. """overridden from configuration.OptionsProviderMixin to handle some
  262. special options
  263. """
  264. if optname in self._options_methods or optname in self._bw_options_methods:
  265. if value:
  266. try:
  267. meth = self._options_methods[optname]
  268. except KeyError:
  269. meth = self._bw_options_methods[optname]
  270. warn('%s is deprecated, replace it by %s' % (
  271. optname, optname.split('-')[0]), DeprecationWarning)
  272. value = check_csv(None, optname, value)
  273. if isinstance(value, (list, tuple)):
  274. for _id in value :
  275. meth(_id)
  276. else :
  277. meth(value)
  278. elif optname == 'output-format':
  279. self.set_reporter(REPORTER_OPT_MAP[value.lower()]())
  280. try:
  281. BaseRawChecker.set_option(self, optname, value, action, optdict)
  282. except UnsupportedAction:
  283. print >> sys.stderr, 'option %s can\'t be read from config file' % \
  284. optname
  285. # checkers manipulation methods ############################################
  286. def register_checker(self, checker):
  287. """register a new checker
  288. checker is an object implementing IRawChecker or / and IASTNGChecker
  289. """
  290. assert checker.priority <= 0, 'checker priority can\'t be >= 0'
  291. self._checkers.setdefault(checker.name, []).append(checker)
  292. for r_id, r_title, r_cb in checker.reports:
  293. self.register_report(r_id, r_title, r_cb, checker)
  294. self.register_options_provider(checker)
  295. if hasattr(checker, 'msgs'):
  296. self.register_messages(checker)
  297. checker.load_defaults()
  298. def disable_noerror_messages(self):
  299. for msgcat, msgids in self._msgs_by_category.iteritems():
  300. if msgcat == 'E':
  301. for msgid in msgids:
  302. self.enable(msgid)
  303. else:
  304. for msgid in msgids:
  305. self.disable(msgid)
  306. def disable_reporters(self):
  307. """disable all reporters"""
  308. for reporters in self._reports.values():
  309. for report_id, _title, _cb in reporters:
  310. self.disable_report(report_id)
  311. def error_mode(self):
  312. """error mode: enable only errors; no reports, no persistent"""
  313. self.disable_noerror_messages()
  314. self.disable('miscellaneous')
  315. self.set_option('reports', False)
  316. self.set_option('persistent', False)
  317. # block level option handling #############################################
  318. #
  319. # see func_block_disable_msg.py test case for expected behaviour
  320. def process_tokens(self, tokens):
  321. """process tokens from the current module to search for module/block
  322. level options
  323. """
  324. comment = tokenize.COMMENT
  325. newline = tokenize.NEWLINE
  326. for (tok_type, _, start, _, line) in tokens:
  327. if tok_type not in (comment, newline):
  328. continue
  329. match = OPTION_RGX.search(line)
  330. if match is None:
  331. continue
  332. if match.group(1).strip() == "disable-all":
  333. self.add_message('I0013', line=start[0])
  334. self._ignore_file = True
  335. return
  336. try:
  337. opt, value = match.group(1).split('=', 1)
  338. except ValueError:
  339. self.add_message('I0010', args=match.group(1).strip(),
  340. line=start[0])
  341. continue
  342. opt = opt.strip()
  343. if opt in self._options_methods or opt in self._bw_options_methods:
  344. try:
  345. meth = self._options_methods[opt]
  346. except KeyError:
  347. meth = self._bw_options_methods[opt]
  348. warn('%s is deprecated, replace it by %s (%s, line %s)' % (
  349. opt, opt.split('-')[0], self.current_file, line),
  350. DeprecationWarning)
  351. for msgid in splitstrip(value):
  352. try:
  353. meth(msgid, 'module', start[0])
  354. except UnknownMessage:
  355. self.add_message('E0012', args=msgid, line=start[0])
  356. else:
  357. self.add_message('E0011', args=opt, line=start[0])
  358. def collect_block_lines(self, node, msg_state):
  359. """walk ast to collect block level options line numbers"""
  360. # recurse on children (depth first)
  361. for child in node.get_children():
  362. self.collect_block_lines(child, msg_state)
  363. first = node.fromlineno
  364. last = node.tolineno
  365. # first child line number used to distinguish between disable
  366. # which are the first child of scoped node with those defined later.
  367. # For instance in the code below:
  368. #
  369. # 1. def meth8(self):
  370. # 2. """test late disabling"""
  371. # 3. # pylint: disable=E1102
  372. # 4. print self.blip
  373. # 5. # pylint: disable=E1101
  374. # 6. print self.bla
  375. #
  376. # E1102 should be disabled from line 1 to 6 while E1101 from line 5 to 6
  377. #
  378. # this is necessary to disable locally messages applying to class /
  379. # function using their fromlineno
  380. if isinstance(node, (nodes.Module, nodes.Class, nodes.Function)) and node.body:
  381. firstchildlineno = node.body[0].fromlineno
  382. else:
  383. firstchildlineno = last
  384. for msgid, lines in msg_state.iteritems():
  385. for lineno, state in lines.items():
  386. if first <= lineno <= last:
  387. if lineno > firstchildlineno:
  388. state = True
  389. # set state for all lines for this block
  390. first, last = node.block_range(lineno)
  391. for line in xrange(first, last+1):
  392. # do not override existing entries
  393. if not line in self._module_msgs_state.get(msgid, ()):
  394. if line in lines: # state change in the same block
  395. state = lines[line]
  396. try:
  397. self._module_msgs_state[msgid][line] = state
  398. except KeyError:
  399. self._module_msgs_state[msgid] = {line: state}
  400. del lines[lineno]
  401. # code checking methods ###################################################
  402. def get_checkers(self):
  403. """return all available checkers as a list"""
  404. return [self] + [c for checkers in self._checkers.values()
  405. for c in checkers if c is not self]
  406. def prepare_checkers(self):
  407. """return checkers needed for activated messages and reports"""
  408. if not self.config.reports:
  409. self.disable_reporters()
  410. # get needed checkers
  411. neededcheckers = [self]
  412. for checker in self.get_checkers()[1:]:
  413. messages = set(msg for msg in checker.msgs
  414. if self.is_message_enabled(msg))
  415. if (messages or
  416. any(self.report_is_enabled(r[0]) for r in checker.reports)):
  417. neededcheckers.append(checker)
  418. checker.active_msgs = messages
  419. return neededcheckers
  420. def check(self, files_or_modules):
  421. """main checking entry: check a list of files or modules from their
  422. name.
  423. """
  424. self.reporter.include_ids = self.config.include_ids
  425. if not isinstance(files_or_modules, (list, tuple)):
  426. files_or_modules = (files_or_modules,)
  427. walker = PyLintASTWalker(self)
  428. checkers = self.prepare_checkers()
  429. rawcheckers = [c for c in checkers if implements(c, IRawChecker)
  430. and c is not self]
  431. # notify global begin
  432. for checker in checkers:
  433. checker.open()
  434. if implements(checker, IASTNGChecker):
  435. walker.add_checker(checker)
  436. # build ast and check modules or packages
  437. for descr in self.expand_files(files_or_modules):
  438. modname, filepath = descr['name'], descr['path']
  439. self.set_current_module(modname, filepath)
  440. # get the module representation
  441. astng = self.get_astng(filepath, modname)
  442. if astng is None:
  443. continue
  444. self.base_name = descr['basename']
  445. self.base_file = descr['basepath']
  446. if self.config.files_output:
  447. reportfile = 'pylint_%s.%s' % (modname, self.reporter.extension)
  448. self.reporter.set_output(open(reportfile, 'w'))
  449. self._ignore_file = False
  450. # fix the current file (if the source file was not available or
  451. # if it's actually a c extension)
  452. self.current_file = astng.file
  453. self.check_astng_module(astng, walker, rawcheckers)
  454. # notify global end
  455. self.set_current_module('')
  456. self.stats['statement'] = walker.nbstatements
  457. checkers.reverse()
  458. for checker in checkers:
  459. checker.close()
  460. def expand_files(self, modules):
  461. """get modules and errors from a list of modules and handle errors
  462. """
  463. result, errors = expand_modules(modules, self.config.black_list)
  464. for error in errors:
  465. message = modname = error["mod"]
  466. key = error["key"]
  467. self.set_current_module(modname)
  468. if key == "F0001":
  469. message = str(error["ex"]).replace(os.getcwd() + os.sep, '')
  470. self.add_message(key, args=message)
  471. return result
  472. def set_current_module(self, modname, filepath=None):
  473. """set the name of the currently analyzed module and
  474. init statistics for it
  475. """
  476. if not modname and filepath is None:
  477. return
  478. self.reporter.on_set_current_module(modname, filepath)
  479. self.current_name = modname
  480. self.current_file = filepath or modname
  481. self.stats['by_module'][modname] = {}
  482. self.stats['by_module'][modname]['statement'] = 0
  483. for msg_cat in MSG_TYPES.values():
  484. self.stats['by_module'][modname][msg_cat] = 0
  485. # XXX hack, to be correct we need to keep module_msgs_state
  486. # for every analyzed module (the problem stands with localized
  487. # messages which are only detected in the .close step)
  488. if modname:
  489. self._module_msgs_state = {}
  490. self._module_msg_cats_state = {}
  491. def get_astng(self, filepath, modname):
  492. """return a astng representation for a module"""
  493. try:
  494. return MANAGER.astng_from_file(filepath, modname, source=True)
  495. except SyntaxError, ex:
  496. self.add_message('E0001', line=ex.lineno, args=ex.msg)
  497. except ASTNGBuildingException, ex:
  498. self.add_message('F0010', args=ex)
  499. except Exception, ex:
  500. import traceback
  501. traceback.print_exc()
  502. self.add_message('F0002', args=(ex.__class__, ex))
  503. def check_astng_module(self, astng, walker, rawcheckers):
  504. """check a module from its astng representation, real work"""
  505. # call raw checkers if possible
  506. if not astng.pure_python:
  507. self.add_message('I0001', args=astng.name)
  508. else:
  509. #assert astng.file.endswith('.py')
  510. # invoke IRawChecker interface on self to fetch module/block
  511. # level options
  512. self.process_module(astng)
  513. if self._ignore_file:
  514. return False
  515. # walk ast to collect line numbers
  516. orig_state = self._module_msgs_state.copy()
  517. self._module_msgs_state = {}
  518. self.collect_block_lines(astng, orig_state)
  519. for checker in rawcheckers:
  520. checker.process_module(astng)
  521. # generate events to astng checkers
  522. walker.walk(astng)
  523. return True
  524. # IASTNGChecker interface #################################################
  525. def open(self):
  526. """initialize counters"""
  527. self.stats = { 'by_module' : {},
  528. 'by_msg' : {},
  529. }
  530. for msg_cat in MSG_TYPES.values():
  531. self.stats[msg_cat] = 0
  532. def close(self):
  533. """close the whole package /module, it's time to make reports !
  534. if persistent run, pickle results for later comparison
  535. """
  536. if self.base_name is not None:
  537. # load previous results if any
  538. previous_stats = config.load_results(self.base_name)
  539. # XXX code below needs refactoring to be more reporter agnostic
  540. self.reporter.on_close(self.stats, previous_stats)
  541. if self.config.reports:
  542. sect = self.make_reports(self.stats, previous_stats)
  543. if self.config.files_output:
  544. filename = 'pylint_global.' + self.reporter.extension
  545. self.reporter.set_output(open(filename, 'w'))
  546. else:
  547. sect = Section()
  548. if self.config.reports or self.config.output_format == 'html':
  549. self.reporter.display_results(sect)
  550. # save results if persistent run
  551. if self.config.persistent:
  552. config.save_results(self.stats, self.base_name)
  553. # specific reports ########################################################
  554. def report_evaluation(self, sect, stats, previous_stats):
  555. """make the global evaluation report"""
  556. # check with at least check 1 statements (usually 0 when there is a
  557. # syntax error preventing pylint from further processing)
  558. if stats['statement'] == 0:
  559. raise EmptyReport()
  560. # get a global note for the code
  561. evaluation = self.config.evaluation
  562. try:
  563. note = eval(evaluation, {}, self.stats)
  564. except Exception, ex:
  565. msg = 'An exception occurred while rating: %s' % ex
  566. else:
  567. stats['global_note'] = note
  568. msg = 'Your code has been rated at %.2f/10' % note
  569. if 'global_note' in previous_stats:
  570. msg += ' (previous run: %.2f/10)' % previous_stats['global_note']
  571. if self.config.comment:
  572. msg = '%s\n%s' % (msg, config.get_note_message(note))
  573. sect.append(Text(msg))
  574. # some reporting functions ####################################################
  575. def report_total_messages_stats(sect, stats, previous_stats):
  576. """make total errors / warnings report"""
  577. lines = ['type', 'number', 'previous', 'difference']
  578. lines += table_lines_from_stats(stats, previous_stats,
  579. ('convention', 'refactor',
  580. 'warning', 'error'))
  581. sect.append(Table(children=lines, cols=4, rheaders=1))
  582. def report_messages_stats(sect, stats, _):
  583. """make messages type report"""
  584. if not stats['by_msg']:
  585. # don't print this report when we didn't detected any errors
  586. raise EmptyReport()
  587. in_order = sorted([(value, msg_id)
  588. for msg_id, value in stats['by_msg'].items()
  589. if not msg_id.startswith('I')])
  590. in_order.reverse()
  591. lines = ('message id', 'occurrences')
  592. for value, msg_id in in_order:
  593. lines += (msg_id, str(value))
  594. sect.append(Table(children=lines, cols=2, rheaders=1))
  595. def report_messages_by_module_stats(sect, stats, _):
  596. """make errors / warnings by modules report"""
  597. if len(stats['by_module']) == 1:
  598. # don't print this report when we are analysing a single module
  599. raise EmptyReport()
  600. by_mod = {}
  601. for m_type in ('fatal', 'error', 'warning', 'refactor', 'convention'):
  602. total = stats[m_type]
  603. for module in stats['by_module'].keys():
  604. mod_total = stats['by_module'][module][m_type]
  605. if total == 0:
  606. percent = 0
  607. else:
  608. percent = float((mod_total)*100) / total
  609. by_mod.setdefault(module, {})[m_type] = percent
  610. sorted_result = []
  611. for module, mod_info in by_mod.items():
  612. sorted_result.append((mod_info['error'],
  613. mod_info['warning'],
  614. mod_info['refactor'],
  615. mod_info['convention'],
  616. module))
  617. sorted_result.sort()
  618. sorted_result.reverse()
  619. lines = ['module', 'error', 'warning', 'refactor', 'convention']
  620. for line in sorted_result:
  621. if line[0] == 0 and line[1] == 0:
  622. break
  623. lines.append(line[-1])
  624. for val in line[:-1]:
  625. lines.append('%.2f' % val)
  626. if len(lines) == 5:
  627. raise EmptyReport()
  628. sect.append(Table(children=lines, cols=5, rheaders=1))
  629. # utilities ###################################################################
  630. # this may help to import modules using gettext
  631. try:
  632. __builtins__._ = str
  633. except AttributeError:
  634. __builtins__['_'] = str
  635. class ArgumentPreprocessingError(Exception):
  636. """Raised if an error occurs during argument preprocessing."""
  637. def preprocess_options(args, search_for):
  638. """look for some options (keys of <search_for>) which have to be processed
  639. before others
  640. values of <search_for> are callback functions to call when the option is
  641. found
  642. """
  643. i = 0
  644. while i < len(args):
  645. arg = args[i]
  646. if arg.startswith('--'):
  647. try:
  648. option, val = arg[2:].split('=', 1)
  649. except ValueError:
  650. option, val = arg[2:], None
  651. try:
  652. cb, takearg = search_for[option]
  653. del args[i]
  654. if takearg and val is None:
  655. if i >= len(args) or args[i].startswith('-'):
  656. raise ArgumentPreprocessingError(arg)
  657. val = args[i]
  658. del args[i]
  659. cb(option, val)
  660. except KeyError:
  661. i += 1
  662. else:
  663. i += 1
  664. class Run:
  665. """helper class to use as main for pylint :
  666. run(*sys.argv[1:])
  667. """
  668. LinterClass = PyLinter
  669. option_groups = (
  670. ('Commands', 'Options which are actually commands. Options in this \
  671. group are mutually exclusive.'),
  672. )
  673. def __init__(self, args, reporter=None, exit=True):
  674. self._rcfile = None
  675. self._plugins = []
  676. try:
  677. preprocess_options(args, {
  678. # option: (callback, takearg)
  679. 'rcfile': (self.cb_set_rcfile, True),
  680. 'load-plugins': (self.cb_add_plugins, True),
  681. })
  682. except ArgumentPreprocessingError, e:
  683. print >> sys.stderr, 'Argument %s expects a value.' % (e.args[0],)
  684. sys.exit(32)
  685. self.linter = linter = self.LinterClass((
  686. ('rcfile',
  687. {'action' : 'callback', 'callback' : lambda *args: 1,
  688. 'type': 'string', 'metavar': '<file>',
  689. 'help' : 'Specify a configuration file.'}),
  690. ('init-hook',
  691. {'action' : 'callback', 'type' : 'string', 'metavar': '<code>',
  692. 'callback' : cb_init_hook, 'level': 1,
  693. 'help' : 'Python code to execute, usually for sys.path \
  694. manipulation such as pygtk.require().'}),
  695. ('help-msg',
  696. {'action' : 'callback', 'type' : 'string', 'metavar': '<msg-id>',
  697. 'callback' : self.cb_help_message,
  698. 'group': 'Commands',
  699. 'help' : '''Display a help message for the given message id and \
  700. exit. The value may be a comma separated list of message ids.'''}),
  701. ('list-msgs',
  702. {'action' : 'callback', 'metavar': '<msg-id>',
  703. 'callback' : self.cb_list_messages,
  704. 'group': 'Commands', 'level': 1,
  705. 'help' : "Generate pylint's messages."}),
  706. ('full-documentation',
  707. {'action' : 'callback', 'metavar': '<msg-id>',
  708. 'callback' : self.cb_full_documentation,
  709. 'group': 'Commands', 'level': 1,
  710. 'help' : "Generate pylint's full documentation."}),
  711. ('generate-rcfile',
  712. {'action' : 'callback', 'callback' : self.cb_generate_config,
  713. 'group': 'Commands',
  714. 'help' : '''Generate a sample configuration file according to \
  715. the current configuration. You can put other options before this one to get \
  716. them in the generated configuration.'''}),
  717. ('generate-man',
  718. {'action' : 'callback', 'callback' : self.cb_generate_manpage,
  719. 'group': 'Commands',
  720. 'help' : "Generate pylint's man page.",'hide': True}),
  721. ('errors-only',
  722. {'action' : 'callback', 'callback' : self.cb_error_mode,
  723. 'short': 'E',
  724. 'help' : '''In error mode, checkers without error messages are \
  725. disabled and for others, only the ERROR messages are displayed, and no reports \
  726. are done by default'''}),
  727. ('profile',
  728. {'type' : 'yn', 'metavar' : '<y_or_n>',
  729. 'default': False, 'hide': True,
  730. 'help' : 'Profiled execution.'}),
  731. ), option_groups=self.option_groups,
  732. reporter=reporter, pylintrc=self._rcfile)
  733. # register standard checkers
  734. linter.load_default_plugins()
  735. # load command line plugins
  736. linter.load_plugin_modules(self._plugins)
  737. # add some help section
  738. linter.add_help_section('Environment variables', config.ENV_HELP, level=1)
  739. linter.add_help_section('Output', '''
  740. Using the default text output, the message format is :
  741. MESSAGE_TYPE: LINE_NUM:[OBJECT:] MESSAGE
  742. There are 5 kind of message types :
  743. * (C) convention, for programming standard violation
  744. * (R) refactor, for bad code smell
  745. * (W) warning, for python specific problems
  746. * (E) error, for probable bugs in the code
  747. * (F) fatal, if an error occurred which prevented pylint from doing further
  748. processing.
  749. ''', level=1)
  750. linter.add_help_section('Output status code', '''
  751. Pylint should leave with following status code:
  752. * 0 if everything went fine
  753. * 1 if a fatal message was issued
  754. * 2 if an error message was issued
  755. * 4 if a warning message was issued
  756. * 8 if a refactor message was issued
  757. * 16 if a convention message was issued
  758. * 32 on usage error
  759. status 1 to 16 will be bit-ORed so you can know which different categories has
  760. been issued by analysing pylint output status code
  761. ''', level=1)
  762. # read configuration
  763. linter.disable('W0704')
  764. linter.read_config_file()
  765. # is there some additional plugins in the file configuration, in
  766. config_parser = linter.cfgfile_parser
  767. if config_parser.has_option('MASTER', 'load-plugins'):
  768. plugins = splitstrip(config_parser.get('MASTER', 'load-plugins'))
  769. linter.load_plugin_modules(plugins)
  770. # now we can load file config and command line, plugins (which can
  771. # provide options) have been registered
  772. linter.load_config_file()
  773. if reporter:
  774. # if a custom reporter is provided as argument, it may be overridden
  775. # by file parameters, so re-set it here, but before command line
  776. # parsing so it's still overrideable by command line option
  777. linter.set_reporter(reporter)
  778. try:
  779. args = linter.load_command_line_configuration(args)
  780. except SystemExit, exc:
  781. if exc.code == 2: # bad options
  782. exc.code = 32
  783. raise
  784. if not args:
  785. print linter.help()
  786. sys.exit(32)
  787. # insert current working directory to the python path to have a correct
  788. # behaviour
  789. if len(args) == 1:
  790. sys.path.insert(0, _get_python_path(args[0]))
  791. else:
  792. sys.path.insert(0, os.getcwd())
  793. if self.linter.config.profile:
  794. print >> sys.stderr, '** profiled run'
  795. import cProfile, pstats
  796. cProfile.runctx('linter.check(%r)' % args, globals(), locals(), 'stones.prof' )
  797. data = pstats.Stats('stones.prof')
  798. data.strip_dirs()
  799. data.sort_stats('time', 'calls')
  800. data.print_stats(30)
  801. else:
  802. linter.check(args)
  803. sys.path.pop(0)
  804. if exit:
  805. sys.exit(self.linter.msg_status)
  806. def cb_set_rcfile(self, name, value):
  807. """callback for option preprocessing (i.e. before optik parsing)"""
  808. self._rcfile = value
  809. def cb_add_plugins(self, name, value):
  810. """callback for option preprocessing (i.e. before optik parsing)"""
  811. self._plugins.extend(splitstrip(value))
  812. def cb_error_mode(self, *args, **kwargs):
  813. """error mode:
  814. * disable all but error messages
  815. * disable the 'miscellaneous' checker which can be safely deactivated in
  816. debug
  817. * disable reports
  818. * do not save execution information
  819. """
  820. self.linter.error_mode()
  821. def cb_generate_config(self, *args, **kwargs):
  822. """optik callback for sample config file generation"""
  823. self.linter.generate_config(skipsections=('COMMANDS',))
  824. sys.exit(0)
  825. def cb_generate_manpage(self, *args, **kwargs):
  826. """optik callback for sample config file generation"""
  827. from pylint import __pkginfo__
  828. self.linter.generate_manpage(__pkginfo__)
  829. sys.exit(0)
  830. def cb_help_message(self, option, optname, value, parser):
  831. """optik callback for printing some help about a particular message"""
  832. self.linter.help_message(splitstrip(value))
  833. sys.exit(0)
  834. def cb_full_documentation(self, option, optname, value, parser):
  835. """optik callback for printing full documentation"""
  836. self.linter.print_full_documentation()
  837. sys.exit(0)
  838. def cb_list_messages(self, option, optname, value, parser): # FIXME
  839. """optik callback for printing available messages"""
  840. self.linter.list_messages()
  841. sys.exit(0)
  842. def cb_init_hook(option, optname, value, parser):
  843. """exec arbitrary code to set sys.path for instance"""
  844. exec value
  845. if __name__ == '__main__':
  846. Run(sys.argv[1:])