summaryrefslogtreecommitdiff
path: root/src/flake8/style_guide.py
blob: c35c73949fe6da4e10a409f8e6e846c27e4c8b7d (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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
"""Implementation of the StyleGuide used by Flake8."""
import argparse
import collections
import contextlib
import copy
import enum
import functools
import itertools
import linecache
import logging
from typing import Dict
from typing import Generator
from typing import List
from typing import Match
from typing import Optional
from typing import Sequence
from typing import Set
from typing import Tuple
from typing import Union

from flake8 import defaults
from flake8 import statistics
from flake8 import utils
from flake8.formatting import base as base_formatter

__all__ = ("StyleGuide",)

LOG = logging.getLogger(__name__)


class Selected(enum.Enum):
    """Enum representing an explicitly or implicitly selected code."""

    Explicitly = "explicitly selected"
    Implicitly = "implicitly selected"


class Ignored(enum.Enum):
    """Enum representing an explicitly or implicitly ignored code."""

    Explicitly = "explicitly ignored"
    Implicitly = "implicitly ignored"


class Decision(enum.Enum):
    """Enum representing whether a code should be ignored or selected."""

    Ignored = "ignored error"
    Selected = "selected error"


@functools.lru_cache(maxsize=512)
def find_noqa(physical_line: str) -> Optional[Match[str]]:
    return defaults.NOQA_INLINE_REGEXP.search(physical_line)


_Violation = collections.namedtuple(
    "Violation",
    [
        "code",
        "filename",
        "line_number",
        "column_number",
        "text",
        "physical_line",
    ],
)


class Violation(_Violation):
    """Class representing a violation reported by Flake8."""

    def is_inline_ignored(self, disable_noqa: bool) -> bool:
        """Determine if a comment has been added to ignore this line.

        :param bool disable_noqa:
            Whether or not users have provided ``--disable-noqa``.
        :returns:
            True if error is ignored in-line, False otherwise.
        :rtype:
            bool
        """
        physical_line = self.physical_line
        # TODO(sigmavirus24): Determine how to handle stdin with linecache
        if disable_noqa:
            return False

        if physical_line is None:
            physical_line = linecache.getline(self.filename, self.line_number)
        noqa_match = find_noqa(physical_line)
        if noqa_match is None:
            LOG.debug("%r is not inline ignored", self)
            return False

        codes_str = noqa_match.groupdict()["codes"]
        if codes_str is None:
            LOG.debug("%r is ignored by a blanket ``# noqa``", self)
            return True

        codes = set(utils.parse_comma_separated_list(codes_str))
        if self.code in codes or self.code.startswith(tuple(codes)):
            LOG.debug(
                "%r is ignored specifically inline with ``# noqa: %s``",
                self,
                codes_str,
            )
            return True

        LOG.debug(
            "%r is not ignored inline with ``# noqa: %s``", self, codes_str
        )
        return False

    def is_in(self, diff: Dict[str, Set[int]]) -> bool:
        """Determine if the violation is included in a diff's line ranges.

        This function relies on the parsed data added via
        :meth:`~StyleGuide.add_diff_ranges`. If that has not been called and
        we are not evaluating files in a diff, then this will always return
        True. If there are diff ranges, then this will return True if the
        line number in the error falls inside one of the ranges for the file
        (and assuming the file is part of the diff data). If there are diff
        ranges, this will return False if the file is not part of the diff
        data or the line number of the error is not in any of the ranges of
        the diff.

        :returns:
            True if there is no diff or if the error is in the diff's line
            number ranges. False if the error's line number falls outside
            the diff's line number ranges.
        :rtype:
            bool
        """
        if not diff:
            return True

        # NOTE(sigmavirus24): The parsed diff will be a defaultdict with
        # a set as the default value (if we have received it from
        # flake8.utils.parse_unified_diff). In that case ranges below
        # could be an empty set (which is False-y) or if someone else
        # is using this API, it could be None. If we could guarantee one
        # or the other, we would check for it more explicitly.
        line_numbers = diff.get(self.filename)
        if not line_numbers:
            return False

        return self.line_number in line_numbers


class DecisionEngine:
    """A class for managing the decision process around violations.

    This contains the logic for whether a violation should be reported or
    ignored.
    """

    def __init__(self, options: argparse.Namespace) -> None:
        """Initialize the engine."""
        self.cache: Dict[str, Decision] = {}
        self.selected = tuple(options.select)
        self.extended_selected = tuple(
            sorted(options.extended_default_select, reverse=True)
        )
        self.enabled_extensions = tuple(options.enable_extensions)
        self.all_selected = tuple(
            sorted(self.selected + self.enabled_extensions, reverse=True)
        )
        self.ignored = tuple(
            sorted(
                itertools.chain(options.ignore, options.extend_ignore),
                reverse=True,
            )
        )
        self.using_default_ignore = set(self.ignored) == set(defaults.IGNORE)
        self.using_default_select = set(self.selected) == set(defaults.SELECT)

    def _in_all_selected(self, code: str) -> bool:
        return bool(self.all_selected) and code.startswith(self.all_selected)

    def _in_extended_selected(self, code: str) -> bool:
        return bool(self.extended_selected) and code.startswith(
            self.extended_selected
        )

    def was_selected(self, code: str) -> Union[Selected, Ignored]:
        """Determine if the code has been selected by the user.

        :param str code:
            The code for the check that has been run.
        :returns:
            Selected.Implicitly if the selected list is empty,
            Selected.Explicitly if the selected list is not empty and a match
            was found,
            Ignored.Implicitly if the selected list is not empty but no match
            was found.
        """
        if self._in_all_selected(code):
            return Selected.Explicitly

        if not self.all_selected and self._in_extended_selected(code):
            # If it was not explicitly selected, it may have been implicitly
            # selected because the check comes from a plugin that is enabled by
            # default
            return Selected.Implicitly

        return Ignored.Implicitly

    def was_ignored(self, code: str) -> Union[Selected, Ignored]:
        """Determine if the code has been ignored by the user.

        :param str code:
            The code for the check that has been run.
        :returns:
            Selected.Implicitly if the ignored list is empty,
            Ignored.Explicitly if the ignored list is not empty and a match was
            found,
            Selected.Implicitly if the ignored list is not empty but no match
            was found.
        """
        if self.ignored and code.startswith(self.ignored):
            return Ignored.Explicitly

        return Selected.Implicitly

    def more_specific_decision_for(self, code: str) -> Decision:
        select = find_first_match(code, self.all_selected)
        extra_select = find_first_match(code, self.extended_selected)
        ignore = find_first_match(code, self.ignored)

        if select and ignore:
            # If the violation code appears in both the select and ignore
            # lists (in some fashion) then if we're using the default ignore
            # list and a custom select list we should select the code. An
            # example usage looks like this:
            #   A user has a code that would generate an E126 violation which
            #   is in our default ignore list and they specify select=E.
            # We should be reporting that violation. This logic changes,
            # however, if they specify select and ignore such that both match.
            # In that case we fall through to our find_more_specific call.
            # If, however, the user hasn't specified a custom select, and
            # we're using the defaults for both select and ignore then the
            # more specific rule must win. In most cases, that will be to
            # ignore the violation since our default select list is very
            # high-level and our ignore list is highly specific.
            if self.using_default_ignore and not self.using_default_select:
                return Decision.Selected
            return find_more_specific(select, ignore)
        if extra_select and ignore:
            # At this point, select is false-y. Now we need to check if the
            # code is in our extended select list and our ignore list. This is
            # a *rare* case as we see little usage of the extended select list
            # that plugins can use, so I suspect this section may change to
            # look a little like the block above in which we check if we're
            # using our default ignore list.
            return find_more_specific(extra_select, ignore)
        if select or (extra_select and self.using_default_select):
            # Here, ignore was false-y and the user has either selected
            # explicitly the violation or the violation is covered by
            # something in the extended select list and we're using the
            # default select list. In either case, we want the violation to be
            # selected.
            return Decision.Selected
        if select is None and (
            extra_select is None or not self.using_default_ignore
        ):
            return Decision.Ignored
        if (select is None and not self.using_default_select) and (
            ignore is None and self.using_default_ignore
        ):
            return Decision.Ignored
        return Decision.Selected

    def make_decision(self, code: str) -> Decision:
        """Decide if code should be ignored or selected."""
        LOG.debug('Deciding if "%s" should be reported', code)
        selected = self.was_selected(code)
        ignored = self.was_ignored(code)
        LOG.debug(
            'The user configured "%s" to be "%s", "%s"',
            code,
            selected,
            ignored,
        )

        if (
            selected is Selected.Explicitly or selected is Selected.Implicitly
        ) and ignored is Selected.Implicitly:
            decision = Decision.Selected
        elif (
            selected is Selected.Explicitly and ignored is Ignored.Explicitly
        ) or (
            selected is Ignored.Implicitly and ignored is Selected.Implicitly
        ):
            decision = self.more_specific_decision_for(code)
        elif selected is Ignored.Implicitly or ignored is Ignored.Explicitly:
            decision = Decision.Ignored  # pylint: disable=R0204
        return decision

    def decision_for(self, code: str) -> Decision:
        """Return the decision for a specific code.

        This method caches the decisions for codes to avoid retracing the same
        logic over and over again. We only care about the select and ignore
        rules as specified by the user in their configuration files and
        command-line flags.

        This method does not look at whether the specific line is being
        ignored in the file itself.

        :param str code:
            The code for the check that has been run.
        """
        decision = self.cache.get(code)
        if decision is None:
            decision = self.make_decision(code)
            self.cache[code] = decision
            LOG.debug('"%s" will be "%s"', code, decision)
        return decision


class StyleGuideManager:
    """Manage multiple style guides for a single run."""

    def __init__(
        self,
        options: argparse.Namespace,
        formatter: base_formatter.BaseFormatter,
        decider: Optional[DecisionEngine] = None,
    ) -> None:
        """Initialize our StyleGuide.

        .. todo:: Add parameter documentation.
        """
        self.options = options
        self.formatter = formatter
        self.stats = statistics.Statistics()
        self.decider = decider or DecisionEngine(options)
        self.style_guides: List[StyleGuide] = []
        self.default_style_guide = StyleGuide(
            options, formatter, self.stats, decider=decider
        )
        self.style_guides = list(
            itertools.chain(
                [self.default_style_guide],
                self.populate_style_guides_with(options),
            )
        )

    def populate_style_guides_with(
        self, options: argparse.Namespace
    ) -> Generator["StyleGuide", None, None]:
        """Generate style guides from the per-file-ignores option.

        :param options:
            The original options parsed from the CLI and config file.
        :type options:
            :class:`~argparse.Namespace`
        :returns:
            A copy of the default style guide with overridden values.
        :rtype:
            :class:`~flake8.style_guide.StyleGuide`
        """
        per_file = utils.parse_files_to_codes_mapping(
            options.per_file_ignores
        )
        for filename, violations in per_file:
            yield self.default_style_guide.copy(
                filename=filename, extend_ignore_with=violations
            )

    @functools.lru_cache(maxsize=None)
    def style_guide_for(self, filename: str) -> "StyleGuide":
        """Find the StyleGuide for the filename in particular."""
        guides = sorted(
            (g for g in self.style_guides if g.applies_to(filename)),
            key=lambda g: len(g.filename or ""),
        )
        if len(guides) > 1:
            return guides[-1]
        return guides[0]

    @contextlib.contextmanager
    def processing_file(
        self, filename: str
    ) -> Generator["StyleGuide", None, None]:
        """Record the fact that we're processing the file's results."""
        guide = self.style_guide_for(filename)
        with guide.processing_file(filename):
            yield guide

    def handle_error(
        self,
        code: str,
        filename: str,
        line_number: int,
        column_number: Optional[int],
        text: str,
        physical_line: Optional[str] = None,
    ) -> int:
        """Handle an error reported by a check.

        :param str code:
            The error code found, e.g., E123.
        :param str filename:
            The file in which the error was found.
        :param int line_number:
            The line number (where counting starts at 1) at which the error
            occurs.
        :param int column_number:
            The column number (where counting starts at 1) at which the error
            occurs.
        :param str text:
            The text of the error message.
        :param str physical_line:
            The actual physical line causing the error.
        :returns:
            1 if the error was reported. 0 if it was ignored. This is to allow
            for counting of the number of errors found that were not ignored.
        :rtype:
            int
        """
        guide = self.style_guide_for(filename)
        return guide.handle_error(
            code, filename, line_number, column_number, text, physical_line
        )

    def add_diff_ranges(self, diffinfo: Dict[str, Set[int]]) -> None:
        """Update the StyleGuides to filter out information not in the diff.

        This provides information to the underlying StyleGuides so that only
        the errors in the line number ranges are reported.

        :param dict diffinfo:
            Dictionary mapping filenames to sets of line number ranges.
        """
        for guide in self.style_guides:
            guide.add_diff_ranges(diffinfo)


class StyleGuide:
    """Manage a Flake8 user's style guide."""

    def __init__(
        self,
        options: argparse.Namespace,
        formatter: base_formatter.BaseFormatter,
        stats: statistics.Statistics,
        filename: Optional[str] = None,
        decider: Optional[DecisionEngine] = None,
    ):
        """Initialize our StyleGuide.

        .. todo:: Add parameter documentation.
        """
        self.options = options
        self.formatter = formatter
        self.stats = stats
        self.decider = decider or DecisionEngine(options)
        self.filename = filename
        if self.filename:
            self.filename = utils.normalize_path(self.filename)
        self._parsed_diff: Dict[str, Set[int]] = {}

    def __repr__(self) -> str:
        """Make it easier to debug which StyleGuide we're using."""
        return f"<StyleGuide [{self.filename}]>"

    def copy(
        self,
        filename: Optional[str] = None,
        extend_ignore_with: Optional[Sequence[str]] = None,
    ) -> "StyleGuide":
        """Create a copy of this style guide with different values."""
        filename = filename or self.filename
        options = copy.deepcopy(self.options)
        options.ignore.extend(extend_ignore_with or [])
        return StyleGuide(
            options, self.formatter, self.stats, filename=filename
        )

    @contextlib.contextmanager
    def processing_file(
        self, filename: str
    ) -> Generator["StyleGuide", None, None]:
        """Record the fact that we're processing the file's results."""
        self.formatter.beginning(filename)
        yield self
        self.formatter.finished(filename)

    def applies_to(self, filename: str) -> bool:
        """Check if this StyleGuide applies to the file.

        :param str filename:
            The name of the file with violations that we're potentially
            applying this StyleGuide to.
        :returns:
            True if this applies, False otherwise
        :rtype:
            bool
        """
        if self.filename is None:
            return True
        return utils.matches_filename(
            filename,
            patterns=[self.filename],
            log_message=f'{self!r} does %(whether)smatch "%(path)s"',
            logger=LOG,
        )

    def should_report_error(self, code: str) -> Decision:
        """Determine if the error code should be reported or ignored.

        This method only cares about the select and ignore rules as specified
        by the user in their configuration files and command-line flags.

        This method does not look at whether the specific line is being
        ignored in the file itself.

        :param str code:
            The code for the check that has been run.
        """
        return self.decider.decision_for(code)

    def handle_error(
        self,
        code: str,
        filename: str,
        line_number: int,
        column_number: Optional[int],
        text: str,
        physical_line: Optional[str] = None,
    ) -> int:
        """Handle an error reported by a check.

        :param str code:
            The error code found, e.g., E123.
        :param str filename:
            The file in which the error was found.
        :param int line_number:
            The line number (where counting starts at 1) at which the error
            occurs.
        :param int column_number:
            The column number (where counting starts at 1) at which the error
            occurs.
        :param str text:
            The text of the error message.
        :param str physical_line:
            The actual physical line causing the error.
        :returns:
            1 if the error was reported. 0 if it was ignored. This is to allow
            for counting of the number of errors found that were not ignored.
        :rtype:
            int
        """
        disable_noqa = self.options.disable_noqa
        # NOTE(sigmavirus24): Apparently we're provided with 0-indexed column
        # numbers so we have to offset that here. Also, if a SyntaxError is
        # caught, column_number may be None.
        if not column_number:
            column_number = 0
        error = Violation(
            code,
            filename,
            line_number,
            column_number + 1,
            text,
            physical_line,
        )
        error_is_selected = (
            self.should_report_error(error.code) is Decision.Selected
        )
        is_not_inline_ignored = error.is_inline_ignored(disable_noqa) is False
        is_included_in_diff = error.is_in(self._parsed_diff)
        if (
            error_is_selected
            and is_not_inline_ignored
            and is_included_in_diff
        ):
            self.formatter.handle(error)
            self.stats.record(error)
            return 1
        return 0

    def add_diff_ranges(self, diffinfo: Dict[str, Set[int]]) -> None:
        """Update the StyleGuide to filter out information not in the diff.

        This provides information to the StyleGuide so that only the errors
        in the line number ranges are reported.

        :param dict diffinfo:
            Dictionary mapping filenames to sets of line number ranges.
        """
        self._parsed_diff = diffinfo


def find_more_specific(selected: str, ignored: str) -> Decision:
    if selected.startswith(ignored) and selected != ignored:
        return Decision.Selected
    return Decision.Ignored


def find_first_match(
    error_code: str, code_list: Tuple[str, ...]
) -> Optional[str]:
    startswith = error_code.startswith
    for code in code_list:
        if startswith(code):
            break
    else:
        return None
    return code