def store():
    store = MessagesStore()

    class Checker(object):
        name = "achecker"
        msgs = {
            "W1234": (
                "message",
                "msg-symbol",
                "msg description.",
                {
                    "old_names": [("W0001", "old-symbol")]
                },
            ),
            "E1234": (
                "Duplicate keyword argument %r in %s call",
                "duplicate-keyword-arg",
                "Used when a function call passes the same keyword argument multiple times.",
                {
                    "maxversion": (2, 6)
                },
            ),
        }

    store.register_messages(Checker())
    return store
Exemple #2
0
def store():
    store = MessagesStore()

    class Checker(object):
        name = 'achecker'
        msgs = {
            'W1234': ('message', 'msg-symbol', 'msg description.',
                      {'old_names': [('W0001', 'old-symbol')]}),
            'E1234': ('Duplicate keyword argument %r in %s call',
                      'duplicate-keyword-arg',
                      'Used when a function call passes the same keyword argument multiple times.',
                      {'maxversion': (2, 6)}),
            }
    store.register_messages(Checker())
    return store
Exemple #3
0
def store():
    store = MessagesStore()

    class Checker(object):
        name = 'achecker'
        msgs = {
            'W1234': ('message', 'msg-symbol', 'msg description.',
                      {'old_names': [('W0001', 'old-symbol')]}),
            'E1234': ('Duplicate keyword argument %r in %s call',
                      'duplicate-keyword-arg',
                      'Used when a function call passes the same keyword argument multiple times.',
                      {'maxversion': (2, 6)}),
            }
    store.register_messages(Checker())
    return store
Exemple #4
0
class PyLinter(OptionsManagerMixIn, MessagesHandlerMixIn, ReportsHandlerMixIn,
               BaseTokenChecker):
    """lint Python modules using external checkers.

    This is the main checker controlling the other ones and the reports
    generation. It is itself both a raw checker and an astroid checker in order
    to:
    * handle message activation / deactivation at the module level
    * handle some basic but necessary stats'data (number of classes, methods...)

    IDE plugins developpers: you may have to call
    `astroid.builder.MANAGER.astroid_cache.clear()` accross run if you want
    to ensure the latest code version is actually checked.
    """

    __implements__ = (ITokenChecker,)

    name = 'master'
    priority = 0
    level = 0
    msgs = MSGS
    may_be_disabled = False

    @staticmethod
    def make_options():
        return (('ignore',
                 {'type' : 'csv', 'metavar' : '<file>[,<file>...]',
                  'dest' : 'black_list', 'default' : ('CVS',),
                  'help' : 'Add files or directories to the blacklist. '
                           'They should be base names, not paths.'}),
                ('persistent',
                 {'default': True, 'type' : 'yn', 'metavar' : '<y_or_n>',
                  'level': 1,
                  'help' : 'Pickle collected data for later comparisons.'}),

                ('load-plugins',
                 {'type' : 'csv', 'metavar' : '<modules>', 'default' : (),
                  'level': 1,
                  'help' : 'List of plugins (as comma separated values of '
                           'python modules names) to load, usually to register '
                           'additional checkers.'}),

                ('output-format',
                 {'default': 'text', 'type': 'string', 'metavar' : '<format>',
                  'short': 'f',
                  'group': 'Reports',
                  'help' : 'Set the output format. Available formats are text,'
                           ' parseable, colorized, msvs (visual studio) and html. You '
                           'can also give a reporter class, eg mypackage.mymodule.'
                           'MyReporterClass.'}),

                ('files-output',
                 {'default': 0, 'type' : 'yn', 'metavar' : '<y_or_n>',
                  'group': 'Reports', 'level': 1,
                  'help' : 'Put messages in a separate file for each module / '
                           'package specified on the command line instead of printing '
                           'them on stdout. Reports (if any) will be written in a file '
                           'name "pylint_global.[txt|html]".'}),

                ('reports',
                 {'default': 1, 'type' : 'yn', 'metavar' : '<y_or_n>',
                  'short': 'r',
                  'group': 'Reports',
                  'help' : 'Tells whether to display a full report or only the '
                           'messages'}),

                ('evaluation',
                 {'type' : 'string', 'metavar' : '<python_expression>',
                  'group': 'Reports', 'level': 1,
                  'default': '10.0 - ((float(5 * error + warning + refactor + '
                             'convention) / statement) * 10)',
                  'help' : 'Python expression which should return a note less '
                           'than 10 (10 is the highest note). You have access '
                           'to the variables errors warning, statement which '
                           'respectively contain the number of errors / '
                           'warnings messages and the total number of '
                           'statements analyzed. This is used by the global '
                           'evaluation report (RP0004).'}),

                ('comment',
                 {'default': 0, 'type' : 'yn', 'metavar' : '<y_or_n>',
                  'group': 'Reports', 'level': 1,
                  'help' : 'Add a comment according to your evaluation note. '
                           'This is used by the global evaluation report (RP0004).'}),

                ('enable',
                 {'type' : 'csv', 'metavar': '<msg ids>',
                  'short': 'e',
                  'group': 'Messages control',
                  'help' : 'Enable the message, report, category or checker with the '
                           'given id(s). You can either give multiple identifier '
                           'separated by comma (,) or put this option multiple time. '
                           'See also the "--disable" option for examples. '}),

                ('disable',
                 {'type' : 'csv', 'metavar': '<msg ids>',
                  'short': 'd',
                  'group': 'Messages control',
                  'help' : 'Disable the message, report, category or checker '
                           'with the given id(s). You can either give multiple identifiers'
                           ' separated by comma (,) or put this option multiple times '
                           '(only on the command line, not in the configuration file '
                           'where it should appear only once).'
                           'You can also use "--disable=all" to disable everything first '
                           'and then reenable specific checks. For example, if you want '
                           'to run only the similarities checker, you can use '
                           '"--disable=all --enable=similarities". '
                           'If you want to run only the classes checker, but have no '
                           'Warning level messages displayed, use'
                           '"--disable=all --enable=classes --disable=W"'}),

                ('msg-template',
                 {'type' : 'string', 'metavar': '<template>',
                  'group': 'Reports',
                  'help' : ('Template used to display messages. '
                            'This is a python new-style format string '
                            'used to format the message information. '
                            'See doc for all details')
                 }),

                ('include-ids', _deprecated_option('i', 'yn')),
                ('symbols', _deprecated_option('s', 'yn')),
               )

    option_groups = (
        ('Messages control', 'Options controling analysis messages'),
        ('Reports', 'Options related to output formating and reporting'),
        )

    def __init__(self, options=(), reporter=None, option_groups=(),
                 pylintrc=None):
        # some stuff has to be done before ancestors initialization...
        #
        # messages store / checkers / reporter / astroid manager
        self.msgs_store = MessagesStore()
        self.reporter = None
        self._reporter_name = None
        self._reporters = {}
        self._checkers = {}
        self._ignore_file = False
        # visit variables
        self.file_state = FileState()
        self.current_name = None
        self.current_file = None
        self.stats = None
        # init options
        self.options = options + PyLinter.make_options()
        self.option_groups = option_groups + PyLinter.option_groups
        self._options_methods = {
            'enable': self.enable,
            'disable': self.disable}
        self._bw_options_methods = {'disable-msg': self.disable,
                                    'enable-msg': self.enable}
        full_version = '%%prog %s, \nastroid %s, common %s\nPython %s' % (
            version, astroid_version, common_version, sys.version)
        OptionsManagerMixIn.__init__(self, usage=__doc__,
                                     version=full_version,
                                     config_file=pylintrc or config.PYLINTRC)
        MessagesHandlerMixIn.__init__(self)
        ReportsHandlerMixIn.__init__(self)
        BaseTokenChecker.__init__(self)
        # provided reports
        self.reports = (('RP0001', 'Messages by category',
                         report_total_messages_stats),
                        ('RP0002', '% errors / warnings by module',
                         report_messages_by_module_stats),
                        ('RP0003', 'Messages',
                         report_messages_stats),
                        ('RP0004', 'Global evaluation',
                         self.report_evaluation),
                       )
        self.register_checker(self)
        self._dynamic_plugins = set()
        self.load_provider_defaults()
        if reporter:
            self.set_reporter(reporter)

    def load_default_plugins(self):
        checkers_initialize(self)
        reporters_initialize(self)
        # Make sure to load the default reporter, because
        # the option has been set before the plugins had been loaded.
        if not self.reporter:
            self._load_reporter()

    def prepare_import_path(self, args):
        """Prepare sys.path for running the linter checks."""
        if len(args) == 1:
            sys.path.insert(0, _get_python_path(args[0]))
        else:
            sys.path.insert(0, os.getcwd())

    def cleanup_import_path(self):
        """Revert any changes made to sys.path in prepare_import_path."""
        sys.path.pop(0)

    def load_plugin_modules(self, modnames):
        """take a list of module names which are pylint plugins and load
        and register them
        """
        for modname in modnames:
            if modname in self._dynamic_plugins:
                continue
            self._dynamic_plugins.add(modname)
            module = load_module_from_name(modname)
            module.register(self)

    def _load_reporter(self):
        name = self._reporter_name.lower()
        if name in self._reporters:
            self.set_reporter(self._reporters[name]())
        else:
            qname = self._reporter_name
            module = load_module_from_name(get_module_part(qname))
            class_name = qname.split('.')[-1]
            reporter_class = getattr(module, class_name)
            self.set_reporter(reporter_class())

    def set_reporter(self, reporter):
        """set the reporter used to display messages and reports"""
        self.reporter = reporter
        reporter.linter = self

    def set_option(self, optname, value, action=None, optdict=None):
        """overridden from configuration.OptionsProviderMixin to handle some
        special options
        """
        if optname in self._options_methods or \
                optname in self._bw_options_methods:
            if value:
                try:
                    meth = self._options_methods[optname]
                except KeyError:
                    meth = self._bw_options_methods[optname]
                    warn('%s is deprecated, replace it by %s' % (
                        optname, optname.split('-')[0]), DeprecationWarning)
                value = check_csv(None, optname, value)
                if isinstance(value, (list, tuple)):
                    for _id in value:
                        meth(_id, ignore_unknown=True)
                else:
                    meth(value)
        elif optname == 'output-format':
            self._reporter_name = value
            # If the reporters are already available, load
            # the reporter class.
            if self._reporters:
                self._load_reporter()
        try:
            BaseTokenChecker.set_option(self, optname, value, action, optdict)
        except UnsupportedAction:
            print >> sys.stderr, 'option %s can\'t be read from config file' % \
                  optname

    def register_reporter(self, reporter_class):
        self._reporters[reporter_class.name] = reporter_class

    # checkers manipulation methods ############################################

    def register_checker(self, checker):
        """register a new checker

        checker is an object implementing IRawChecker or / and IAstroidChecker
        """
        assert checker.priority <= 0, 'checker priority can\'t be >= 0'
        self._checkers.setdefault(checker.name, []).append(checker)
        for r_id, r_title, r_cb in checker.reports:
            self.register_report(r_id, r_title, r_cb, checker)
        self.register_options_provider(checker)
        if hasattr(checker, 'msgs'):
            self.msgs_store.register_messages(checker)
        checker.load_defaults()

    def disable_noerror_messages(self):
        for msgcat, msgids in self.msgs_store._msgs_by_category.iteritems():
            if msgcat == 'E':
                for msgid in msgids:
                    self.enable(msgid)
            else:
                for msgid in msgids:
                    self.disable(msgid)

    def disable_reporters(self):
        """disable all reporters"""
        for reporters in self._reports.itervalues():
            for report_id, _title, _cb in reporters:
                self.disable_report(report_id)

    def error_mode(self):
        """error mode: enable only errors; no reports, no persistent"""
        self.disable_noerror_messages()
        self.disable('miscellaneous')
        self.set_option('reports', False)
        self.set_option('persistent', False)

    # block level option handling #############################################
    #
    # see func_block_disable_msg.py test case for expected behaviour

    def process_tokens(self, tokens):
        """process tokens from the current module to search for module/block
        level options
        """
        for (tok_type, content, start, _, _) in tokens:
            if tok_type != tokenize.COMMENT:
                continue
            match = OPTION_RGX.search(content)
            if match is None:
                continue
            if match.group(1).strip() == "disable-all" or \
                    match.group(1).strip() == 'skip-file':
                if match.group(1).strip() == "disable-all":
                    self.add_message('deprecated-pragma', line=start[0],
                                     args=('disable-all', 'skip-file'))
                self.add_message('file-ignored', line=start[0])
                self._ignore_file = True
                return
            try:
                opt, value = match.group(1).split('=', 1)
            except ValueError:
                self.add_message('bad-inline-option', args=match.group(1).strip(),
                                 line=start[0])
                continue
            opt = opt.strip()
            if opt in self._options_methods or opt in self._bw_options_methods:
                try:
                    meth = self._options_methods[opt]
                except KeyError:
                    meth = self._bw_options_methods[opt]
                    # found a "(dis|en)able-msg" pragma deprecated suppresssion
                    self.add_message('deprecated-pragma', line=start[0], args=(opt, opt.replace('-msg', '')))
                for msgid in splitstrip(value):
                    try:
                        if (opt, msgid) == ('disable', 'all'):
                            self.add_message('deprecated-pragma', line=start[0], args=('disable=all', 'skip-file'))
                            self.add_message('file-ignored', line=start[0])
                            self._ignore_file = True
                            return
                        meth(msgid, 'module', start[0])
                    except UnknownMessage:
                        self.add_message('bad-option-value', args=msgid, line=start[0])
            else:
                self.add_message('unrecognized-inline-option', args=opt, line=start[0])


    # code checking methods ###################################################

    def get_checkers(self):
        """return all available checkers as a list"""
        return [self] + [c for checkers in self._checkers.itervalues()
                         for c in checkers if c is not self]

    def prepare_checkers(self):
        """return checkers needed for activated messages and reports"""
        if not self.config.reports:
            self.disable_reporters()
        # get needed checkers
        neededcheckers = [self]
        for checker in self.get_checkers()[1:]:
            # fatal errors should not trigger enable / disabling a checker
            messages = set(msg for msg in checker.msgs
                           if msg[0] != 'F' and self.is_message_enabled(msg))
            if (messages or
                    any(self.report_is_enabled(r[0]) for r in checker.reports)):
                neededcheckers.append(checker)
        # Sort checkers by priority
        neededcheckers = sorted(neededcheckers, key=attrgetter('priority'),
                                reverse=True)
        return neededcheckers

    def should_analyze_file(self, modname, path): # pylint: disable=unused-argument
        """Returns whether or not a module should be checked.

        This implementation returns True for all python source file, indicating
        that all files should be linted.

        Subclasses may override this method to indicate that modules satisfying
        certain conditions should not be linted.

        :param str modname: The name of the module to be checked.
        :param str path: The full path to the source code of the module.
        :returns: True if the module should be checked.
        :rtype: bool
        """
        return path.endswith('.py')

    def check(self, files_or_modules):
        """main checking entry: check a list of files or modules from their
        name.
        """
        # initialize msgs_state now that all messages have been registered into
        # the store
        for msg in self.msgs_store.messages:
            if not msg.may_be_emitted():
                self._msgs_state[msg.msgid] = False

        if not isinstance(files_or_modules, (list, tuple)):
            files_or_modules = (files_or_modules,)
        walker = PyLintASTWalker(self)
        checkers = self.prepare_checkers()
        tokencheckers = [c for c in checkers if implements(c, ITokenChecker)
                         and c is not self]
        rawcheckers = [c for c in checkers if implements(c, IRawChecker)]
        # notify global begin
        for checker in checkers:
            checker.open()
            if implements(checker, IAstroidChecker):
                walker.add_checker(checker)
        # build ast and check modules or packages
        for descr in self.expand_files(files_or_modules):
            modname, filepath = descr['name'], descr['path']
            if not descr['isarg'] and not self.should_analyze_file(modname, filepath):
                continue
            if self.config.files_output:
                reportfile = 'pylint_%s.%s' % (modname, self.reporter.extension)
                self.reporter.set_output(open(reportfile, 'w'))
            self.set_current_module(modname, filepath)
            # get the module representation
            astroid = self.get_ast(filepath, modname)
            if astroid is None:
                continue
            # XXX to be correct we need to keep module_msgs_state for every
            # analyzed module (the problem stands with localized messages which
            # are only detected in the .close step)
            self.file_state = FileState(descr['basename'])
            self._ignore_file = False
            # fix the current file (if the source file was not available or
            # if it's actually a c extension)
            self.current_file = astroid.file # pylint: disable=maybe-no-member
            self.check_astroid_module(astroid, walker, rawcheckers, tokencheckers)
            # warn about spurious inline messages handling
            for msgid, line, args in self.file_state.iter_spurious_suppression_messages(self.msgs_store):
                self.add_message(msgid, line, None, args)
        # notify global end
        self.set_current_module('')
        self.stats['statement'] = walker.nbstatements
        checkers.reverse()
        for checker in checkers:
            checker.close()

    def expand_files(self, modules):
        """get modules and errors from a list of modules and handle errors
        """
        result, errors = expand_modules(modules, self.config.black_list)
        for error in errors:
            message = modname = error["mod"]
            key = error["key"]
            self.set_current_module(modname)
            if key == "fatal":
                message = str(error["ex"]).replace(os.getcwd() + os.sep, '')
            self.add_message(key, args=message)
        return result

    def set_current_module(self, modname, filepath=None):
        """set the name of the currently analyzed module and
        init statistics for it
        """
        if not modname and filepath is None:
            return
        self.reporter.on_set_current_module(modname, filepath)
        self.current_name = modname
        self.current_file = filepath or modname
        self.stats['by_module'][modname] = {}
        self.stats['by_module'][modname]['statement'] = 0
        for msg_cat in MSG_TYPES.itervalues():
            self.stats['by_module'][modname][msg_cat] = 0

    def get_ast(self, filepath, modname):
        """return a ast(roid) representation for a module"""
        try:
            return MANAGER.ast_from_file(filepath, modname, source=True)
        except SyntaxError, ex:
            self.add_message('syntax-error', line=ex.lineno, args=ex.msg)
        except AstroidBuildingException, ex:
            self.add_message('parse-error', args=ex)
Exemple #5
0
class PyLinter(OptionsManagerMixIn, MessagesHandlerMixIn, ReportsHandlerMixIn,
               BaseTokenChecker):
    """lint Python modules using external checkers.

    This is the main checker controlling the other ones and the reports
    generation. It is itself both a raw checker and an astroid checker in order
    to:
    * handle message activation / deactivation at the module level
    * handle some basic but necessary stats'data (number of classes, methods...)

    IDE plugins developpers: you may have to call
    `astroid.builder.MANAGER.astroid_cache.clear()` accross run if you want
    to ensure the latest code version is actually checked.
    """

    __implements__ = (ITokenChecker, )

    name = 'master'
    priority = 0
    level = 0
    msgs = MSGS
    may_be_disabled = False

    @staticmethod
    def make_options():
        return (
            ('ignore', {
                'type':
                'csv',
                'metavar':
                '<file>[,<file>...]',
                'dest':
                'black_list',
                'default': ('CVS', ),
                'help':
                'Add files or directories to the blacklist. '
                'They should be base names, not paths.'
            }),
            ('persistent', {
                'default': True,
                'type': 'yn',
                'metavar': '<y_or_n>',
                'level': 1,
                'help': 'Pickle collected data for later comparisons.'
            }),
            ('load-plugins', {
                'type':
                'csv',
                'metavar':
                '<modules>',
                'default': (),
                'level':
                1,
                'help':
                'List of plugins (as comma separated values of '
                'python modules names) to load, usually to register '
                'additional checkers.'
            }),
            ('output-format', {
                'default':
                'text',
                'type':
                'string',
                'metavar':
                '<format>',
                'short':
                'f',
                'group':
                'Reports',
                'help':
                'Set the output format. Available formats are text,'
                ' parseable, colorized, msvs (visual studio) and html. You '
                'can also give a reporter class, eg mypackage.mymodule.'
                'MyReporterClass.'
            }),
            ('files-output', {
                'default':
                0,
                'type':
                'yn',
                'metavar':
                '<y_or_n>',
                'group':
                'Reports',
                'level':
                1,
                'help':
                'Put messages in a separate file for each module / '
                'package specified on the command line instead of printing '
                'them on stdout. Reports (if any) will be written in a file '
                'name "pylint_global.[txt|html]".'
            }),
            ('reports', {
                'default':
                1,
                'type':
                'yn',
                'metavar':
                '<y_or_n>',
                'short':
                'r',
                'group':
                'Reports',
                'help':
                'Tells whether to display a full report or only the '
                'messages'
            }),
            ('evaluation', {
                'type':
                'string',
                'metavar':
                '<python_expression>',
                'group':
                'Reports',
                'level':
                1,
                'default':
                '10.0 - ((float(5 * error + warning + refactor + '
                'convention) / statement) * 10)',
                'help':
                'Python expression which should return a note less '
                'than 10 (10 is the highest note). You have access '
                'to the variables errors warning, statement which '
                'respectively contain the number of errors / '
                'warnings messages and the total number of '
                'statements analyzed. This is used by the global '
                'evaluation report (RP0004).'
            }),
            ('comment', {
                'default':
                0,
                'type':
                'yn',
                'metavar':
                '<y_or_n>',
                'group':
                'Reports',
                'level':
                1,
                'help':
                'Add a comment according to your evaluation note. '
                'This is used by the global evaluation report (RP0004).'
            }),
            ('enable', {
                'type':
                'csv',
                'metavar':
                '<msg ids>',
                'short':
                'e',
                'group':
                'Messages control',
                'help':
                'Enable the message, report, category or checker with the '
                'given id(s). You can either give multiple identifier '
                'separated by comma (,) or put this option multiple time. '
                'See also the "--disable" option for examples. '
            }),
            ('disable', {
                'type':
                'csv',
                'metavar':
                '<msg ids>',
                'short':
                'd',
                'group':
                'Messages control',
                'help':
                'Disable the message, report, category or checker '
                'with the given id(s). You can either give multiple identifiers'
                ' separated by comma (,) or put this option multiple times '
                '(only on the command line, not in the configuration file '
                'where it should appear only once).'
                'You can also use "--disable=all" to disable everything first '
                'and then reenable specific checks. For example, if you want '
                'to run only the similarities checker, you can use '
                '"--disable=all --enable=similarities". '
                'If you want to run only the classes checker, but have no '
                'Warning level messages displayed, use'
                '"--disable=all --enable=classes --disable=W"'
            }),
            ('msg-template', {
                'type':
                'string',
                'metavar':
                '<template>',
                'group':
                'Reports',
                'help': ('Template used to display messages. '
                         'This is a python new-style format string '
                         'used to format the message information. '
                         'See doc for all details')
            }),
            ('include-ids', _deprecated_option('i', 'yn')),
            ('symbols', _deprecated_option('s', 'yn')),
        )

    option_groups = (
        ('Messages control', 'Options controling analysis messages'),
        ('Reports', 'Options related to output formating and reporting'),
    )

    def __init__(self,
                 options=(),
                 reporter=None,
                 option_groups=(),
                 pylintrc=None):
        # some stuff has to be done before ancestors initialization...
        #
        # messages store / checkers / reporter / astroid manager
        self.msgs_store = MessagesStore()
        self.reporter = None
        self._reporter_name = None
        self._reporters = {}
        self._checkers = {}
        self._ignore_file = False
        # visit variables
        self.file_state = FileState()
        self.current_name = None
        self.current_file = None
        self.stats = None
        # init options
        self.options = options + PyLinter.make_options()
        self.option_groups = option_groups + PyLinter.option_groups
        self._options_methods = {
            'enable': self.enable,
            'disable': self.disable
        }
        self._bw_options_methods = {
            'disable-msg': self.disable,
            'enable-msg': self.enable
        }
        full_version = '%%prog %s, \nastroid %s, common %s\nPython %s' % (
            version, astroid_version, common_version, sys.version)
        OptionsManagerMixIn.__init__(self,
                                     usage=__doc__,
                                     version=full_version,
                                     config_file=pylintrc or config.PYLINTRC)
        MessagesHandlerMixIn.__init__(self)
        ReportsHandlerMixIn.__init__(self)
        BaseTokenChecker.__init__(self)
        # provided reports
        self.reports = (
            ('RP0001', 'Messages by category', report_total_messages_stats),
            ('RP0002', '% errors / warnings by module',
             report_messages_by_module_stats),
            ('RP0003', 'Messages', report_messages_stats),
            ('RP0004', 'Global evaluation', self.report_evaluation),
        )
        self.register_checker(self)
        self._dynamic_plugins = set()
        self.load_provider_defaults()
        if reporter:
            self.set_reporter(reporter)

    def load_default_plugins(self):
        checkers_initialize(self)
        reporters_initialize(self)
        # Make sure to load the default reporter, because
        # the option has been set before the plugins had been loaded.
        if not self.reporter:
            self._load_reporter()

    def prepare_import_path(self, args):
        """Prepare sys.path for running the linter checks."""
        if len(args) == 1:
            sys.path.insert(0, _get_python_path(args[0]))
        else:
            sys.path.insert(0, os.getcwd())

    def cleanup_import_path(self):
        """Revert any changes made to sys.path in prepare_import_path."""
        sys.path.pop(0)

    def load_plugin_modules(self, modnames):
        """take a list of module names which are pylint plugins and load
        and register them
        """
        for modname in modnames:
            if modname in self._dynamic_plugins:
                continue
            self._dynamic_plugins.add(modname)
            module = load_module_from_name(modname)
            module.register(self)

    def _load_reporter(self):
        name = self._reporter_name.lower()
        if name in self._reporters:
            self.set_reporter(self._reporters[name]())
        else:
            qname = self._reporter_name
            module = load_module_from_name(get_module_part(qname))
            class_name = qname.split('.')[-1]
            reporter_class = getattr(module, class_name)
            self.set_reporter(reporter_class())

    def set_reporter(self, reporter):
        """set the reporter used to display messages and reports"""
        self.reporter = reporter
        reporter.linter = self

    def set_option(self, optname, value, action=None, optdict=None):
        """overridden from configuration.OptionsProviderMixin to handle some
        special options
        """
        if optname in self._options_methods or \
                optname in self._bw_options_methods:
            if value:
                try:
                    meth = self._options_methods[optname]
                except KeyError:
                    meth = self._bw_options_methods[optname]
                    warn(
                        '%s is deprecated, replace it by %s' %
                        (optname, optname.split('-')[0]), DeprecationWarning)
                value = check_csv(None, optname, value)
                if isinstance(value, (list, tuple)):
                    for _id in value:
                        meth(_id, ignore_unknown=True)
                else:
                    meth(value)
        elif optname == 'output-format':
            self._reporter_name = value
            # If the reporters are already available, load
            # the reporter class.
            if self._reporters:
                self._load_reporter()
        try:
            BaseTokenChecker.set_option(self, optname, value, action, optdict)
        except UnsupportedAction:
            print >> sys.stderr, 'option %s can\'t be read from config file' % \
                  optname

    def register_reporter(self, reporter_class):
        self._reporters[reporter_class.name] = reporter_class

    # checkers manipulation methods ############################################

    def register_checker(self, checker):
        """register a new checker

        checker is an object implementing IRawChecker or / and IAstroidChecker
        """
        assert checker.priority <= 0, 'checker priority can\'t be >= 0'
        self._checkers.setdefault(checker.name, []).append(checker)
        for r_id, r_title, r_cb in checker.reports:
            self.register_report(r_id, r_title, r_cb, checker)
        self.register_options_provider(checker)
        if hasattr(checker, 'msgs'):
            self.msgs_store.register_messages(checker)
        checker.load_defaults()

    def disable_noerror_messages(self):
        for msgcat, msgids in self.msgs_store._msgs_by_category.iteritems():
            if msgcat == 'E':
                for msgid in msgids:
                    self.enable(msgid)
            else:
                for msgid in msgids:
                    self.disable(msgid)

    def disable_reporters(self):
        """disable all reporters"""
        for reporters in self._reports.itervalues():
            for report_id, _title, _cb in reporters:
                self.disable_report(report_id)

    def error_mode(self):
        """error mode: enable only errors; no reports, no persistent"""
        self.disable_noerror_messages()
        self.disable('miscellaneous')
        self.set_option('reports', False)
        self.set_option('persistent', False)

    # block level option handling #############################################
    #
    # see func_block_disable_msg.py test case for expected behaviour

    def process_tokens(self, tokens):
        """process tokens from the current module to search for module/block
        level options
        """
        for (tok_type, content, start, _, _) in tokens:
            if tok_type != tokenize.COMMENT:
                continue
            match = OPTION_RGX.search(content)
            if match is None:
                continue
            if match.group(1).strip() == "disable-all" or \
                    match.group(1).strip() == 'skip-file':
                if match.group(1).strip() == "disable-all":
                    self.add_message('deprecated-pragma',
                                     line=start[0],
                                     args=('disable-all', 'skip-file'))
                self.add_message('file-ignored', line=start[0])
                self._ignore_file = True
                return
            try:
                opt, value = match.group(1).split('=', 1)
            except ValueError:
                self.add_message('bad-inline-option',
                                 args=match.group(1).strip(),
                                 line=start[0])
                continue
            opt = opt.strip()
            if opt in self._options_methods or opt in self._bw_options_methods:
                try:
                    meth = self._options_methods[opt]
                except KeyError:
                    meth = self._bw_options_methods[opt]
                    # found a "(dis|en)able-msg" pragma deprecated suppresssion
                    self.add_message('deprecated-pragma',
                                     line=start[0],
                                     args=(opt, opt.replace('-msg', '')))
                for msgid in splitstrip(value):
                    try:
                        if (opt, msgid) == ('disable', 'all'):
                            self.add_message('deprecated-pragma',
                                             line=start[0],
                                             args=('disable=all', 'skip-file'))
                            self.add_message('file-ignored', line=start[0])
                            self._ignore_file = True
                            return
                        meth(msgid, 'module', start[0])
                    except UnknownMessage:
                        self.add_message('bad-option-value',
                                         args=msgid,
                                         line=start[0])
            else:
                self.add_message('unrecognized-inline-option',
                                 args=opt,
                                 line=start[0])

    # code checking methods ###################################################

    def get_checkers(self):
        """return all available checkers as a list"""
        return [self] + [
            c for checkers in self._checkers.itervalues()
            for c in checkers if c is not self
        ]

    def prepare_checkers(self):
        """return checkers needed for activated messages and reports"""
        if not self.config.reports:
            self.disable_reporters()
        # get needed checkers
        neededcheckers = [self]
        for checker in self.get_checkers()[1:]:
            # fatal errors should not trigger enable / disabling a checker
            messages = set(msg for msg in checker.msgs
                           if msg[0] != 'F' and self.is_message_enabled(msg))
            if (messages or any(
                    self.report_is_enabled(r[0]) for r in checker.reports)):
                neededcheckers.append(checker)
        # Sort checkers by priority
        neededcheckers = sorted(neededcheckers,
                                key=attrgetter('priority'),
                                reverse=True)
        return neededcheckers

    def should_analyze_file(self, modname, path):  # pylint: disable=unused-argument
        """Returns whether or not a module should be checked.

        This implementation returns True for all python source file, indicating
        that all files should be linted.

        Subclasses may override this method to indicate that modules satisfying
        certain conditions should not be linted.

        :param str modname: The name of the module to be checked.
        :param str path: The full path to the source code of the module.
        :returns: True if the module should be checked.
        :rtype: bool
        """
        return path.endswith('.py')

    def check(self, files_or_modules):
        """main checking entry: check a list of files or modules from their
        name.
        """
        # initialize msgs_state now that all messages have been registered into
        # the store
        for msg in self.msgs_store.messages:
            if not msg.may_be_emitted():
                self._msgs_state[msg.msgid] = False

        if not isinstance(files_or_modules, (list, tuple)):
            files_or_modules = (files_or_modules, )
        walker = PyLintASTWalker(self)
        checkers = self.prepare_checkers()
        tokencheckers = [
            c for c in checkers
            if implements(c, ITokenChecker) and c is not self
        ]
        rawcheckers = [c for c in checkers if implements(c, IRawChecker)]
        # notify global begin
        for checker in checkers:
            checker.open()
            if implements(checker, IAstroidChecker):
                walker.add_checker(checker)
        # build ast and check modules or packages
        for descr in self.expand_files(files_or_modules):
            modname, filepath = descr['name'], descr['path']
            if not descr['isarg'] and not self.should_analyze_file(
                    modname, filepath):
                continue
            if self.config.files_output:
                reportfile = 'pylint_%s.%s' % (modname,
                                               self.reporter.extension)
                self.reporter.set_output(open(reportfile, 'w'))
            self.set_current_module(modname, filepath)
            # get the module representation
            astroid = self.get_ast(filepath, modname)
            if astroid is None:
                continue
            # XXX to be correct we need to keep module_msgs_state for every
            # analyzed module (the problem stands with localized messages which
            # are only detected in the .close step)
            self.file_state = FileState(descr['basename'])
            self._ignore_file = False
            # fix the current file (if the source file was not available or
            # if it's actually a c extension)
            self.current_file = astroid.file  # pylint: disable=maybe-no-member
            self.check_astroid_module(astroid, walker, rawcheckers,
                                      tokencheckers)
            # warn about spurious inline messages handling
            for msgid, line, args in self.file_state.iter_spurious_suppression_messages(
                    self.msgs_store):
                self.add_message(msgid, line, None, args)
        # notify global end
        self.set_current_module('')
        self.stats['statement'] = walker.nbstatements
        checkers.reverse()
        for checker in checkers:
            checker.close()

    def expand_files(self, modules):
        """get modules and errors from a list of modules and handle errors
        """
        result, errors = expand_modules(modules, self.config.black_list)
        for error in errors:
            message = modname = error["mod"]
            key = error["key"]
            self.set_current_module(modname)
            if key == "fatal":
                message = str(error["ex"]).replace(os.getcwd() + os.sep, '')
            self.add_message(key, args=message)
        return result

    def set_current_module(self, modname, filepath=None):
        """set the name of the currently analyzed module and
        init statistics for it
        """
        if not modname and filepath is None:
            return
        self.reporter.on_set_current_module(modname, filepath)
        self.current_name = modname
        self.current_file = filepath or modname
        self.stats['by_module'][modname] = {}
        self.stats['by_module'][modname]['statement'] = 0
        for msg_cat in MSG_TYPES.itervalues():
            self.stats['by_module'][modname][msg_cat] = 0

    def get_ast(self, filepath, modname):
        """return a ast(roid) representation for a module"""
        try:
            return MANAGER.ast_from_file(filepath, modname, source=True)
        except SyntaxError, ex:
            self.add_message('syntax-error', line=ex.lineno, args=ex.msg)
        except AstroidBuildingException, ex:
            self.add_message('parse-error', args=ex)
Exemple #6
0
class MessagesStoreTC(unittest.TestCase):
    def setUp(self):
        self.store = MessagesStore()
        class Checker(object):
            name = 'achecker'
            msgs = {
                'W1234': ('message', 'msg-symbol', 'msg description.',
                          {'old_names': [('W0001', 'old-symbol')]}),
                'E1234': ('Duplicate keyword argument %r in %s call',
                          'duplicate-keyword-arg',
                          'Used when a function call passes the same keyword argument multiple times.',
                          {'maxversion': (2, 6)}),
                }
        self.store.register_messages(Checker())

    def _compare_messages(self, desc, msg, checkerref=False):
        self.assertMultiLineEqual(desc, msg.format_help(checkerref=checkerref))

    def test_check_message_id(self):
        self.assertIsInstance(self.store.check_message_id('W1234'),
                              MessageDefinition)
        self.assertRaises(UnknownMessage,
                          self.store.check_message_id, 'YB12')

    def test_message_help(self):
        msg = self.store.check_message_id('W1234')
        self._compare_messages(
            ''':msg-symbol (W1234): *message*
  msg description. This message belongs to the achecker checker.''',
            msg, checkerref=True)
        self._compare_messages(
            ''':msg-symbol (W1234): *message*
  msg description.''',
            msg, checkerref=False)

    def test_message_help_minmax(self):
        # build the message manually to be python version independant
        msg = self.store.check_message_id('E1234')
        self._compare_messages(
            ''':duplicate-keyword-arg (E1234): *Duplicate keyword argument %r in %s call*
  Used when a function call passes the same keyword argument multiple times.
  This message belongs to the achecker checker. It can't be emitted when using
  Python >= 2.6.''',
            msg, checkerref=True)
        self._compare_messages(
            ''':duplicate-keyword-arg (E1234): *Duplicate keyword argument %r in %s call*
  Used when a function call passes the same keyword argument multiple times.
  This message can't be emitted when using Python >= 2.6.''',
            msg, checkerref=False)

    def test_list_messages(self):
        sys.stdout = six.StringIO()
        try:
            self.store.list_messages()
            output = sys.stdout.getvalue()
        finally:
            sys.stdout = sys.__stdout__
        # cursory examination of the output: we're mostly testing it completes
        self.assertIn(':msg-symbol (W1234): *message*', output)

    def test_add_renamed_message(self):
        self.store.add_renamed_message('W1234', 'old-bad-name', 'msg-symbol')
        self.assertEqual('msg-symbol',
                         self.store.check_message_id('W1234').symbol)
        self.assertEqual('msg-symbol',
                         self.store.check_message_id('old-bad-name').symbol)

    def test_renamed_message_register(self):
        self.assertEqual('msg-symbol',
                         self.store.check_message_id('W0001').symbol)
        self.assertEqual('msg-symbol',
                         self.store.check_message_id('old-symbol').symbol)
Exemple #7
0
class MessagesStoreTC(unittest.TestCase):
    def setUp(self):
        self.store = MessagesStore()

        class Checker(object):
            name = "achecker"
            msgs = {
                "W1234": ("message", "msg-symbol", "msg description.", {"old_names": [("W0001", "old-symbol")]}),
                "E1234": (
                    "Duplicate keyword argument %r in %s call",
                    "duplicate-keyword-arg",
                    "Used when a function call passes the same keyword argument multiple times.",
                    {"maxversion": (2, 6)},
                ),
            }

        self.store.register_messages(Checker())

    def _compare_messages(self, desc, msg, checkerref=False):
        # replace \r\n with \n, because
        # logilab.common.textutils.normalize_text
        # uses os.linesep, which will
        # not properly compare with triple
        # quoted multilines used in these tests
        self.assertMultiLineEqual(desc, msg.format_help(checkerref=checkerref).replace("\r\n", "\n"))

    def test_check_message_id(self):
        self.assertIsInstance(self.store.check_message_id("W1234"), MessageDefinition)
        self.assertRaises(UnknownMessage, self.store.check_message_id, "YB12")

    def test_message_help(self):
        msg = self.store.check_message_id("W1234")
        self._compare_messages(
            """:msg-symbol (W1234): *message*
  msg description. This message belongs to the achecker checker.""",
            msg,
            checkerref=True,
        )
        self._compare_messages(
            """:msg-symbol (W1234): *message*
  msg description.""",
            msg,
            checkerref=False,
        )

    def test_message_help_minmax(self):
        # build the message manually to be python version independant
        msg = self.store.check_message_id("E1234")
        self._compare_messages(
            """:duplicate-keyword-arg (E1234): *Duplicate keyword argument %r in %s call*
  Used when a function call passes the same keyword argument multiple times.
  This message belongs to the achecker checker. It can't be emitted when using
  Python >= 2.6.""",
            msg,
            checkerref=True,
        )
        self._compare_messages(
            """:duplicate-keyword-arg (E1234): *Duplicate keyword argument %r in %s call*
  Used when a function call passes the same keyword argument multiple times.
  This message can't be emitted when using Python >= 2.6.""",
            msg,
            checkerref=False,
        )

    def test_list_messages(self):
        sys.stdout = six.StringIO()
        try:
            self.store.list_messages()
            output = sys.stdout.getvalue()
        finally:
            sys.stdout = sys.__stdout__
        # cursory examination of the output: we're mostly testing it completes
        self.assertIn(":msg-symbol (W1234): *message*", output)

    def test_add_renamed_message(self):
        self.store.add_renamed_message("W1234", "old-bad-name", "msg-symbol")
        self.assertEqual("msg-symbol", self.store.check_message_id("W1234").symbol)
        self.assertEqual("msg-symbol", self.store.check_message_id("old-bad-name").symbol)

    def test_renamed_message_register(self):
        self.assertEqual("msg-symbol", self.store.check_message_id("W0001").symbol)
        self.assertEqual("msg-symbol", self.store.check_message_id("old-symbol").symbol)