summaryrefslogtreecommitdiff
path: root/src/flake8/formatting/default.py
blob: f8e3a66680ddc48ff27a01f298f812ad6d60b3da (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
"""Default formatting class for Flake8."""
from flake8.formatting import base


class SimpleFormatter(base.BaseFormatter):
    """Simple abstraction for Default and Pylint formatter commonality.

    Sub-classes of this need to define an ``error_format`` attribute in order
    to succeed. The ``format`` method relies on that attribute and expects the
    ``error_format`` string to use the old-style formatting strings with named
    parameters:

    * code
    * text
    * path
    * row
    * col

    """

    error_format = None

    def format(self, error):
        """Format and write error out.

        If an output filename is specified, write formatted errors to that
        file. Otherwise, print the formatted error to standard out.
        """
        return self.error_format % {
            "code": error.code,
            "text": error.text,
            "path": error.filename,
            "row": error.line_number,
            "col": error.column_number,
        }


class Default(SimpleFormatter):
    """Default formatter for Flake8.

    This also handles backwards compatibility for people specifying a custom
    format string.
    """

    error_format = '%(path)s:%(row)d:%(col)d: %(code)s %(text)s'

    def after_init(self):
        """Check for a custom format string."""
        if self.options.format.lower() != 'default':
            self.error_format = self.options.format


class Pylint(SimpleFormatter):
    """Pylint formatter for Flake8."""

    error_format = '%(path)s:%(row)d: [%(code)s] %(text)s'


class FilenameOnly(SimpleFormatter):
    """Only print filenames, e.g., flake8 -q."""

    error_format = '%(path)s'

    def after_init(self):
        """Initialize our set of filenames."""
        self.filenames_already_printed = set()

    def format(self, error):
        """Ensure we only print each error once."""
        if error.filename not in self.filenames_already_printed:
            self.filenames_already_printed.add(error.filename)
            return super(FilenameOnly, self).format(error)


class Nothing(base.BaseFormatter):
    """Print absolutely nothing."""

    def format(self, error):
        """Do nothing."""
        pass