summaryrefslogtreecommitdiff
path: root/src/flake8/api/legacy.py
blob: 35c71018eb0e4d3e79f0b582901c4a19c7d06c5b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
"""Module containing shims around Flake8 2.0 behaviour."""
import logging
import os.path

from flake8.formatting import base as formatter
from flake8.main import application as app

LOG = logging.getLogger(__name__)


def get_style_guide(**kwargs):
    """Stub out the only function I'm aware of people using."""
    application = app.Application()
    application.initialize([])
    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)
    return StyleGuide(application)


class StyleGuide(object):
    """Public facing object that mimic's Flake8 2.0's StyleGuide.

    .. note::

        There are important changes in how this object behaves compared to
        the StyleGuide object provided in Flake8 2.x.

    .. warning::

        This object should not be instantiated directly by users.

    .. versionchanged:: 3.0.0
    """

    def __init__(self, application):
        """Initialize our StyleGuide."""
        self._application = application
        self._file_checker_manager = application.file_checker_manager

    @property
    def options(self):
        """The parsed options.

        An instance of :class:`optparse.Values` containing parsed options.
        """
        return self._application.options

    @property
    def paths(self):
        """The extra arguments passed as paths."""
        return self._application.paths

    def check_files(self, paths=None):
        """Run collected checks on the files provided.

        This will check the files passed in and return a :class:`Report`
        instance.

        :param list paths:
            List of filenames (or paths) to check.
        :returns:
            Object that mimic's Flake8 2.0's Reporter class.
        :rtype:
            flake8.api.legacy.Report
        """
        self._application.run_checks(paths)
        self._application.report_errors()
        return Report(self._application)

    def excluded(self, filename, parent=None):
        """Determine if a file is excluded.

        :param str filename:
            Path to the file to check if it is excluded.
        :param str parent:
            Name of the parent directory containing the file.
        :returns:
            True if the filename is excluded, False otherwise.
        :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 init_report(self, reporter=None):
        """Set up a formatter for this run of Flake8."""
        if (reporter is not None and
                not issubclass(reporter, formatter.BaseFormatter)):
            raise ValueError("Report should be subclass of "
                             "flake8.formatter.BaseFormatter.")
        self._application.make_formatter(reporter)
        self._application.guide = None
        # NOTE(sigmavirus24): This isn't the intended use of
        # Application#make_guide but it works pretty well.
        # Stop cringing... I know it's gross.
        self._application.make_guide()

    def input_file(self, filename, lines=None, expected=None, line_offset=0):
        """Run collected checks on a single file.

        This will check the file passed in and return a :class:`Report`
        instance.

        :param str filename:
            The path to the file to check.
        :param list lines:
            Ignored since Flake8 3.0.
        :param expected:
            Ignored since Flake8 3.0.
        :param int line_offset:
            Ignored since Flake8 3.0.
        :returns:
            Object that mimic's Flake8 2.0's Reporter class.
        :rtype:
            flake8.api.legacy.Report
        """
        return self.check_files([filename])


class Report(object):
    """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.

    .. versionchanged:: 3.0.0
    """

    def __init__(self, application):
        """Initialize the Report for the user.

        .. warning:: This should not be instantiated by users.
        """
        self._application = application

    @property
    def total_errors(self):
        """The total number of errors found by Flake8."""
        return self._application.result_count

    def get_statistics(self, violation):
        """Get the number of occurences of a violation."""
        raise NotImplementedError('Statistics capturing needs to happen first')