diff options
author | Anthony Sottile <asottile@umich.edu> | 2022-01-05 12:37:53 -0500 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-01-05 12:37:53 -0500 |
commit | f0fb7868832486091e26072e53ead5e50bdf3e64 (patch) | |
tree | b05f69ef3cb72ee1ac5dbb0ff113dfb7f08200b7 /src | |
parent | 0d4128db48d364412c27dee9443ca4a429febd73 (diff) | |
parent | 78b2db4072cc1a81bf21391fcdd30638e8514792 (diff) | |
download | flake8-f0fb7868832486091e26072e53ead5e50bdf3e64.tar.gz |
Merge pull request #1510 from asottile/type_legacy_pt2
type the rest of the legacy api
Diffstat (limited to 'src')
-rw-r--r-- | src/flake8/api/legacy.py | 194 |
1 files changed, 110 insertions, 84 deletions
diff --git a/src/flake8/api/legacy.py b/src/flake8/api/legacy.py index b529553..ab20514 100644 --- a/src/flake8/api/legacy.py +++ b/src/flake8/api/legacy.py @@ -6,9 +6,13 @@ In 3.0 we no longer have an "engine" module but we maintain the API from it. import argparse import logging import os.path +from typing import Any from typing import List +from typing import Optional +from typing import Type import flake8 +from flake8.discover_files import expand_paths from flake8.formatting import base as formatter from flake8.main import application as app from flake8.options import config @@ -19,43 +23,50 @@ LOG = logging.getLogger(__name__) __all__ = ("get_style_guide",) -def get_style_guide(**kwargs): - r"""Provision a StyleGuide for use. +class Report: + """Public facing object that mimic's Flake8 2.0's API. - :param \*\*kwargs: - Keyword arguments that provide some options for the StyleGuide. - :returns: - An initialized StyleGuide - :rtype: - :class:`StyleGuide` + .. note:: + + There are important changes in how this object behaves compared to + the object provided in Flake8 2.x. + + .. warning:: + + This should not be instantiated by users. + + .. versionchanged:: 3.0.0 """ - application = app.Application() - prelim_opts, remaining_args = application.parse_preliminary_options([]) - flake8.configure_logging(prelim_opts.verbose, prelim_opts.output_file) - cfg, cfg_dir = config.load_config( - config=prelim_opts.config, - extra=prelim_opts.append_config, - isolated=prelim_opts.isolated, - ) + def __init__(self, application: app.Application) -> None: + """Initialize the Report for the user. - application.find_plugins(cfg, cfg_dir, prelim_opts.enable_extensions) - application.register_plugin_options() - application.parse_configuration_and_cli(cfg, cfg_dir, remaining_args) - # We basically want application.initialize to be called but with these - # options set instead before we make our formatter, notifier, internal - # style guide and file checker manager. - options = application.options - for key, value in kwargs.items(): - try: - getattr(options, key) - setattr(options, key, value) - except AttributeError: - LOG.error('Could not update option "%s"', key) - application.make_formatter() - application.make_guide() - application.make_file_checker_manager() - return StyleGuide(application) + .. warning:: This should not be instantiated by users. + """ + assert application.guide is not None + self._application = application + self._style_guide = application.guide + self._stats = self._style_guide.stats + + @property + def total_errors(self) -> int: + """Return the total number of errors.""" + return self._application.result_count + + def get_statistics(self, violation: str) -> List[str]: + """Get the list of occurrences of a violation. + + :returns: + List of occurrences of a violation formatted as: + {Count} {Error Code} {Message}, e.g., + ``8 E531 Some error message about the error`` + :rtype: + list + """ + return [ + f"{s.count} {s.error_code} {s.message}" + for s in self._stats.statistics_for(violation) + ] class StyleGuide: @@ -73,7 +84,7 @@ class StyleGuide: .. versionchanged:: 3.0.0 """ - def __init__(self, application): + def __init__(self, application: app.Application) -> None: """Initialize our StyleGuide.""" self._application = application self._file_checker_manager = application.file_checker_manager @@ -84,14 +95,16 @@ class StyleGuide: An instance of :class:`argparse.Namespace` containing parsed options. """ + assert self._application.options is not None return self._application.options @property - def paths(self): + def paths(self) -> List[str]: """Return the extra arguments passed as paths.""" - return self._application.paths + assert self._application.options is not None + return self._application.options.filenames - def check_files(self, paths=None): + def check_files(self, paths: Optional[List[str]] = None) -> Report: """Run collected checks on the files provided. This will check the files passed in and return a :class:`Report` @@ -104,12 +117,13 @@ class StyleGuide: :rtype: flake8.api.legacy.Report """ + assert self._application.options is not None self._application.options.filenames = paths self._application.run_checks() self._application.report_errors() return Report(self._application) - def excluded(self, filename, parent=None): + def excluded(self, filename: str, parent: Optional[str] = None) -> bool: """Determine if a file is excluded. :param str filename: @@ -121,14 +135,27 @@ class StyleGuide: :rtype: bool """ - return self._file_checker_manager.is_path_excluded(filename) or ( - parent - and self._file_checker_manager.is_path_excluded( - os.path.join(parent, filename) + + def excluded(path: str) -> bool: + paths = tuple( + expand_paths( + paths=[path], + stdin_display_name=self.options.stdin_display_name, + filename_patterns=self.options.filename, + exclude=self.options.exclude, + is_running_from_diff=self.options.diff, + ) ) + return not paths + + return excluded(filename) or ( + parent is not None and excluded(os.path.join(parent, filename)) ) - def init_report(self, reporter=None): + def init_report( + self, + reporter: Optional[Type[formatter.BaseFormatter]] = None, + ) -> None: """Set up a formatter for this run of Flake8.""" if reporter is None: return @@ -147,7 +174,13 @@ class StyleGuide: self._application.file_checker_manager = None self._application.make_file_checker_manager() - def input_file(self, filename, lines=None, expected=None, line_offset=0): + def input_file( + self, + filename: str, + lines: Optional[Any] = None, + expected: Optional[Any] = None, + line_offset: Optional[Any] = 0, + ) -> Report: """Run collected checks on a single file. This will check the file passed in and return a :class:`Report` @@ -169,47 +202,40 @@ class StyleGuide: return self.check_files([filename]) -class Report: - """Public facing object that mimic's Flake8 2.0's API. - - .. note:: - - There are important changes in how this object behaves compared to - the object provided in Flake8 2.x. - - .. warning:: - - This should not be instantiated by users. +def get_style_guide(**kwargs: Any) -> StyleGuide: + r"""Provision a StyleGuide for use. - .. versionchanged:: 3.0.0 + :param \*\*kwargs: + Keyword arguments that provide some options for the StyleGuide. + :returns: + An initialized StyleGuide + :rtype: + :class:`StyleGuide` """ + application = app.Application() + prelim_opts, remaining_args = application.parse_preliminary_options([]) + flake8.configure_logging(prelim_opts.verbose, prelim_opts.output_file) - def __init__(self, application: app.Application) -> None: - """Initialize the Report for the user. - - .. warning:: This should not be instantiated by users. - """ - assert application.guide is not None - self._application = application - self._style_guide = application.guide - self._stats = self._style_guide.stats - - @property - def total_errors(self) -> int: - """Return the total number of errors.""" - return self._application.result_count - - def get_statistics(self, violation: str) -> List[str]: - """Get the list of occurrences of a violation. + cfg, cfg_dir = config.load_config( + config=prelim_opts.config, + extra=prelim_opts.append_config, + isolated=prelim_opts.isolated, + ) - :returns: - List of occurrences of a violation formatted as: - {Count} {Error Code} {Message}, e.g., - ``8 E531 Some error message about the error`` - :rtype: - list - """ - return [ - f"{s.count} {s.error_code} {s.message}" - for s in self._stats.statistics_for(violation) - ] + application.find_plugins(cfg, cfg_dir, prelim_opts.enable_extensions) + application.register_plugin_options() + application.parse_configuration_and_cli(cfg, cfg_dir, remaining_args) + # We basically want application.initialize to be called but with these + # options set instead before we make our formatter, notifier, internal + # style guide and file checker manager. + options = application.options + for key, value in kwargs.items(): + try: + getattr(options, key) + setattr(options, key, value) + except AttributeError: + LOG.error('Could not update option "%s"', key) + application.make_formatter() + application.make_guide() + application.make_file_checker_manager() + return StyleGuide(application) |