We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Add `wemake-plain` output formatter
It should be the same as `wemake`, but without colors. Why?

When I try to save the output to file, I get this:

```
  106:29   WPS220 Found too deep nesting: 28 > 20
  [34mtry[39;49;00m:
  ^
```

And I want to have this:

```
  106:29   WPS220 Found too deep nesting: 28 > 20
  try:
  ^
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `wemake_python_styleguide/formatter.py`
Content:
```
1 """
2 Our very own ``flake8`` formatter for better error messages.
3 
4 That's how all ``flake8`` formatters work:
5 
6 .. mermaid::
7    :caption: ``flake8`` formatting API calls order.
8 
9     graph LR
10         F2[start]  --> F3[after_init]
11         F3         --> F4[start]
12         F4         --> F5[beginning]
13         F5         --> F6[handle]
14         F6         --> F7[format]
15         F6	       --> F8[show_source]
16         F6	       --> F9[show_statistic]
17         F7         --> F10[finished]
18         F8         --> F10[finished]
19         F9         --> F10[finished]
20         F10       -.-> F5
21         F10        --> F11[stop]
22 
23 .. autoclass:: WemakeFormatter
24    :no-undoc-members:
25 
26 """
27 
28 from collections import defaultdict
29 from typing import ClassVar, DefaultDict, List
30 
31 from flake8.formatting.base import BaseFormatter
32 from flake8.statistics import Statistics
33 from flake8.style_guide import Violation
34 from pygments import highlight
35 from pygments.formatters import TerminalFormatter
36 from pygments.lexers import PythonLexer
37 from typing_extensions import Final
38 
39 from wemake_python_styleguide.version import pkg_version
40 
41 #: That url is generated and hosted by Sphinx.
42 DOCS_URL_TEMPLATE: Final = (
43     'https://wemake-python-styleguide.rtfd.io/en/{0}/pages/usage/violations/'
44 )
45 
46 #: This url points to the specific violation page.
47 SHORTLINK_TEMPLATE: Final = (
48     'https://pyflak.es/{0}'
49 )
50 
51 
52 class WemakeFormatter(BaseFormatter):  # noqa: WPS214
53     """
54     We need to format our style :term:`violations <violation>` beatifully.
55 
56     The default formatter does not allow us to do that.
57     What things do we miss?
58 
59     1. Spacing, everything is just mixed up and glued together
60     2. Colors and decoration, some information is easier
61        to gather just with colors or underlined text
62     3. Grouping, we need explicit grouping by filename
63     4. Incomplete and non-informative statistics
64 
65     """
66 
67     _doc_url: ClassVar[str] = DOCS_URL_TEMPLATE.format(pkg_version)
68 
69     # API:
70 
71     def after_init(self):
72         """Called after the original ``init`` is used to set extra fields."""
73         self._lexer = PythonLexer()
74         self._formatter = TerminalFormatter()
75 
76         # Logic:
77         self._processed_filenames: List[str] = []
78         self._error_count = 0
79 
80     def handle(self, error: Violation) -> None:  # noqa: WPS110
81         """Processes each :term:`violation` to print it and all related."""
82         if error.filename not in self._processed_filenames:
83             self._print_header(error.filename)
84             self._processed_filenames.append(error.filename)
85 
86         line = self.format(error)
87         source = self.show_source(error)
88         link = self._show_link(error)
89 
90         self._write(line)
91         if link:
92             self._write(link)
93         if source:
94             self._write(source)
95 
96         self._error_count += 1
97 
98     def format(self, error: Violation) -> str:  # noqa: WPS125
99         """Called to format each individual :term:`violation`."""
100         return '{newline}  {row_col:<8} {code:<5} {text}'.format(
101             newline=self.newline if self._should_show_source(error) else '',
102             code=error.code,
103             text=error.text,
104             row_col='{0}:{1}'.format(error.line_number, error.column_number),
105         )
106 
107     def show_source(self, error: Violation) -> str:
108         """Called when ``--show-source`` option is provided."""
109         if not self._should_show_source(error):
110             return ''
111 
112         formatted_line = error.physical_line.lstrip()
113         adjust = len(error.physical_line) - len(formatted_line)
114 
115         code = _highlight(
116             formatted_line,
117             self._lexer,
118             self._formatter,
119         )
120 
121         return '  {code}  {spacing}^'.format(
122             code=code,
123             spacing=' ' * (error.column_number - 1 - adjust),
124         )
125 
126     def show_statistics(self, statistics: Statistics) -> None:  # noqa: WPS210
127         """Called when ``--statistic`` option is passed."""
128         all_errors = 0
129         for error_code in statistics.error_codes():
130             stats_for_error_code = statistics.statistics_for(error_code)
131             statistic = next(stats_for_error_code)
132 
133             count = statistic.count
134             count += sum(stat.count for stat in stats_for_error_code)
135             all_errors += count
136             error_by_file = _count_per_filename(statistics, error_code)
137 
138             self._print_violation_per_file(
139                 statistic,
140                 error_code,
141                 count,
142                 error_by_file,
143             )
144 
145         self._write(self.newline)
146         self._write(_underline(_bold('All errors: {0}'.format(all_errors))))
147 
148     def stop(self) -> None:
149         """Runs once per app when the formatting ends."""
150         if self._error_count:
151             message = '{0}Full list of violations and explanations:{0}{1}'
152             self._write(message.format(self.newline, self._doc_url))
153 
154     # Our own methods:
155 
156     def _show_link(self, error: Violation) -> str:
157         """Called when ``--show-violation-links`` option is provided."""
158         if not self.options.show_violation_links:
159             return ''
160 
161         return '  {spacing}-> {link}'.format(
162             spacing=' ' * 9,
163             link=SHORTLINK_TEMPLATE.format(error.code),
164         )
165 
166     def _print_header(self, filename: str) -> None:
167         self._write(
168             '{newline}{filename}'.format(
169                 filename=_underline(_bold(filename)),
170                 newline=self.newline,
171             ),
172         )
173 
174     def _print_violation_per_file(
175         self,
176         statistic: Statistics,
177         error_code: str,
178         count: int,
179         error_by_file: DefaultDict[str, int],
180     ):
181         self._write(
182             '{newline}{error_code}: {message}'.format(
183                 newline=self.newline,
184                 error_code=_bold(error_code),
185                 message=statistic.message,
186             ),
187         )
188         for filename, error_count in error_by_file.items():
189             self._write(
190                 '  {error_count:<5} {filename}'.format(
191                     error_count=error_count,
192                     filename=filename,
193                 ),
194             )
195         self._write(_underline('Total: {0}'.format(count)))
196 
197     def _should_show_source(self, error: Violation) -> bool:
198         return self.options.show_source and error.physical_line is not None
199 
200 
201 # Formatting text:
202 
203 def _bold(text: str) -> str:
204     r"""
205     Returns bold formatted text.
206 
207     >>> _bold('Hello!')
208     '\x1b[1mHello!\x1b[0m'
209 
210     """
211     return '\033[1m{0}\033[0m'.format(text)
212 
213 
214 def _underline(text: str) -> str:
215     r"""
216     Returns underlined formatted text.
217 
218     >>> _underline('Hello!')
219     '\x1b[4mHello!\x1b[0m'
220 
221     """
222     return '\033[4m{0}\033[0m'.format(text)
223 
224 
225 def _highlight(source: str, lexer, formatter) -> str:
226     """
227     Highlights source code. Might fail.
228 
229     See also:
230         https://github.com/wemake-services/wemake-python-styleguide/issues/794
231 
232     """
233     try:
234         return highlight(source, lexer, formatter)
235     except Exception:  # pragma: no cover
236         # Might fail on some systems, when colors are set incorrectly,
237         # or not available at all. In this case code will be just text.
238         return source
239 
240 
241 # Helpers:
242 
243 def _count_per_filename(
244     statistics: Statistics,
245     error_code: str,
246 ) -> DefaultDict[str, int]:
247     filenames: DefaultDict[str, int] = defaultdict(int)
248     stats_for_error_code = statistics.statistics_for(error_code)
249 
250     for stat in stats_for_error_code:
251         filenames[stat.filename] += stat.count
252 
253     return filenames
254
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/wemake_python_styleguide/formatter.py b/wemake_python_styleguide/formatter.py
--- a/wemake_python_styleguide/formatter.py
+++ b/wemake_python_styleguide/formatter.py
@@ -26,7 +26,8 @@
 """
 
 from collections import defaultdict
-from typing import ClassVar, DefaultDict, List
+from os import environ
+from typing import ClassVar, DefaultDict, Final, List
 
 from flake8.formatting.base import BaseFormatter
 from flake8.statistics import Statistics
@@ -34,19 +35,20 @@
 from pygments import highlight
 from pygments.formatters import TerminalFormatter
 from pygments.lexers import PythonLexer
-from typing_extensions import Final
 
 from wemake_python_styleguide.version import pkg_version
 
 #: That url is generated and hosted by Sphinx.
-DOCS_URL_TEMPLATE: Final = (
+_DOCS_URL_TEMPLATE: Final = (
     'https://wemake-python-styleguide.rtfd.io/en/{0}/pages/usage/violations/'
 )
 
 #: This url points to the specific violation page.
-SHORTLINK_TEMPLATE: Final = (
-    'https://pyflak.es/{0}'
-)
+_SHORTLINK_TEMPLATE: Final = 'https://pyflak.es/{0}'
+
+#: Option to disable any code highlight and text output format.
+#: See https://no-color.org
+_NO_COLOR: Final = environ.get('NO_COLOR', '0') == '1'
 
 
 class WemakeFormatter(BaseFormatter):  # noqa: WPS214
@@ -64,7 +66,7 @@
 
     """
 
-    _doc_url: ClassVar[str] = DOCS_URL_TEMPLATE.format(pkg_version)
+    _doc_url: ClassVar[str] = _DOCS_URL_TEMPLATE.format(pkg_version)
 
     # API:
 
@@ -160,7 +162,7 @@
 
         return '  {spacing}-> {link}'.format(
             spacing=' ' * 9,
-            link=SHORTLINK_TEMPLATE.format(error.code),
+            link=_SHORTLINK_TEMPLATE.format(error.code),
         )
 
     def _print_header(self, filename: str) -> None:
@@ -200,36 +202,61 @@
 
 # Formatting text:
 
-def _bold(text: str) -> str:
+def _bold(text: str, *, no_color: bool = _NO_COLOR) -> str:
     r"""
     Returns bold formatted text.
 
     >>> _bold('Hello!')
     '\x1b[1mHello!\x1b[0m'
 
+    Returns non-formatted text if environment variable ``NO_COLOR=1``.
+
+    >>> _bold('Hello!', no_color=True)
+    'Hello!'
+
     """
+    if no_color:
+        return text
     return '\033[1m{0}\033[0m'.format(text)
 
 
-def _underline(text: str) -> str:
+def _underline(text: str, *, no_color: bool = _NO_COLOR) -> str:
     r"""
     Returns underlined formatted text.
 
     >>> _underline('Hello!')
     '\x1b[4mHello!\x1b[0m'
 
+    Returns non-formatted text if environment variable ``NO_COLOR=1``.
+
+    >>> _underline('Hello!', no_color=True)
+    'Hello!'
+
     """
+    if no_color:
+        return text
     return '\033[4m{0}\033[0m'.format(text)
 
 
-def _highlight(source: str, lexer, formatter) -> str:
+def _highlight(
+    source: str,
+    lexer: PythonLexer,
+    formatter: TerminalFormatter,
+    *,
+    no_color: bool = _NO_COLOR,
+) -> str:
     """
     Highlights source code. Might fail.
 
+    Returns non-formatted text if environment variable ``NO_COLOR=1``.
+
     See also:
         https://github.com/wemake-services/wemake-python-styleguide/issues/794
+        https://no-color.org
 
     """
+    if no_color:
+        return source
     try:
         return highlight(source, lexer, formatter)
     except Exception:  # pragma: no cover

{"golden_diff": "diff --git a/wemake_python_styleguide/formatter.py b/wemake_python_styleguide/formatter.py\n--- a/wemake_python_styleguide/formatter.py\n+++ b/wemake_python_styleguide/formatter.py\n@@ -26,7 +26,8 @@\n \"\"\"\n \n from collections import defaultdict\n-from typing import ClassVar, DefaultDict, List\n+from os import environ\n+from typing import ClassVar, DefaultDict, Final, List\n \n from flake8.formatting.base import BaseFormatter\n from flake8.statistics import Statistics\n@@ -34,19 +35,20 @@\n from pygments import highlight\n from pygments.formatters import TerminalFormatter\n from pygments.lexers import PythonLexer\n-from typing_extensions import Final\n \n from wemake_python_styleguide.version import pkg_version\n \n #: That url is generated and hosted by Sphinx.\n-DOCS_URL_TEMPLATE: Final = (\n+_DOCS_URL_TEMPLATE: Final = (\n     'https://wemake-python-styleguide.rtfd.io/en/{0}/pages/usage/violations/'\n )\n \n #: This url points to the specific violation page.\n-SHORTLINK_TEMPLATE: Final = (\n-    'https://pyflak.es/{0}'\n-)\n+_SHORTLINK_TEMPLATE: Final = 'https://pyflak.es/{0}'\n+\n+#: Option to disable any code highlight and text output format.\n+#: See https://no-color.org\n+_NO_COLOR: Final = environ.get('NO_COLOR', '0') == '1'\n \n \n class WemakeFormatter(BaseFormatter):  # noqa: WPS214\n@@ -64,7 +66,7 @@\n \n     \"\"\"\n \n-    _doc_url: ClassVar[str] = DOCS_URL_TEMPLATE.format(pkg_version)\n+    _doc_url: ClassVar[str] = _DOCS_URL_TEMPLATE.format(pkg_version)\n \n     # API:\n \n@@ -160,7 +162,7 @@\n \n         return '  {spacing}-> {link}'.format(\n             spacing=' ' * 9,\n-            link=SHORTLINK_TEMPLATE.format(error.code),\n+            link=_SHORTLINK_TEMPLATE.format(error.code),\n         )\n \n     def _print_header(self, filename: str) -> None:\n@@ -200,36 +202,61 @@\n \n # Formatting text:\n \n-def _bold(text: str) -> str:\n+def _bold(text: str, *, no_color: bool = _NO_COLOR) -> str:\n     r\"\"\"\n     Returns bold formatted text.\n \n     >>> _bold('Hello!')\n     '\\x1b[1mHello!\\x1b[0m'\n \n+    Returns non-formatted text if environment variable ``NO_COLOR=1``.\n+\n+    >>> _bold('Hello!', no_color=True)\n+    'Hello!'\n+\n     \"\"\"\n+    if no_color:\n+        return text\n     return '\\033[1m{0}\\033[0m'.format(text)\n \n \n-def _underline(text: str) -> str:\n+def _underline(text: str, *, no_color: bool = _NO_COLOR) -> str:\n     r\"\"\"\n     Returns underlined formatted text.\n \n     >>> _underline('Hello!')\n     '\\x1b[4mHello!\\x1b[0m'\n \n+    Returns non-formatted text if environment variable ``NO_COLOR=1``.\n+\n+    >>> _underline('Hello!', no_color=True)\n+    'Hello!'\n+\n     \"\"\"\n+    if no_color:\n+        return text\n     return '\\033[4m{0}\\033[0m'.format(text)\n \n \n-def _highlight(source: str, lexer, formatter) -> str:\n+def _highlight(\n+    source: str,\n+    lexer: PythonLexer,\n+    formatter: TerminalFormatter,\n+    *,\n+    no_color: bool = _NO_COLOR,\n+) -> str:\n     \"\"\"\n     Highlights source code. Might fail.\n \n+    Returns non-formatted text if environment variable ``NO_COLOR=1``.\n+\n     See also:\n         https://github.com/wemake-services/wemake-python-styleguide/issues/794\n+        https://no-color.org\n \n     \"\"\"\n+    if no_color:\n+        return source\n     try:\n         return highlight(source, lexer, formatter)\n     except Exception:  # pragma: no cover\n", "issue": "Add `wemake-plain` output formatter\nIt should be the same as `wemake`, but without colors. Why?\r\n\r\nWhen I try to save the output to file, I get this:\r\n\r\n```\r\n  106:29   WPS220 Found too deep nesting: 28 > 20\r\n  \u001b[34mtry\u001b[39;49;00m:\r\n  ^\r\n```\r\n\r\nAnd I want to have this:\r\n\r\n```\r\n  106:29   WPS220 Found too deep nesting: 28 > 20\r\n  try:\r\n  ^\r\n```\n", "before_files": [{"content": "\"\"\"\nOur very own ``flake8`` formatter for better error messages.\n\nThat's how all ``flake8`` formatters work:\n\n.. mermaid::\n   :caption: ``flake8`` formatting API calls order.\n\n    graph LR\n        F2[start]  --> F3[after_init]\n        F3         --> F4[start]\n        F4         --> F5[beginning]\n        F5         --> F6[handle]\n        F6         --> F7[format]\n        F6\t       --> F8[show_source]\n        F6\t       --> F9[show_statistic]\n        F7         --> F10[finished]\n        F8         --> F10[finished]\n        F9         --> F10[finished]\n        F10       -.-> F5\n        F10        --> F11[stop]\n\n.. autoclass:: WemakeFormatter\n   :no-undoc-members:\n\n\"\"\"\n\nfrom collections import defaultdict\nfrom typing import ClassVar, DefaultDict, List\n\nfrom flake8.formatting.base import BaseFormatter\nfrom flake8.statistics import Statistics\nfrom flake8.style_guide import Violation\nfrom pygments import highlight\nfrom pygments.formatters import TerminalFormatter\nfrom pygments.lexers import PythonLexer\nfrom typing_extensions import Final\n\nfrom wemake_python_styleguide.version import pkg_version\n\n#: That url is generated and hosted by Sphinx.\nDOCS_URL_TEMPLATE: Final = (\n    'https://wemake-python-styleguide.rtfd.io/en/{0}/pages/usage/violations/'\n)\n\n#: This url points to the specific violation page.\nSHORTLINK_TEMPLATE: Final = (\n    'https://pyflak.es/{0}'\n)\n\n\nclass WemakeFormatter(BaseFormatter):  # noqa: WPS214\n    \"\"\"\n    We need to format our style :term:`violations <violation>` beatifully.\n\n    The default formatter does not allow us to do that.\n    What things do we miss?\n\n    1. Spacing, everything is just mixed up and glued together\n    2. Colors and decoration, some information is easier\n       to gather just with colors or underlined text\n    3. Grouping, we need explicit grouping by filename\n    4. Incomplete and non-informative statistics\n\n    \"\"\"\n\n    _doc_url: ClassVar[str] = DOCS_URL_TEMPLATE.format(pkg_version)\n\n    # API:\n\n    def after_init(self):\n        \"\"\"Called after the original ``init`` is used to set extra fields.\"\"\"\n        self._lexer = PythonLexer()\n        self._formatter = TerminalFormatter()\n\n        # Logic:\n        self._processed_filenames: List[str] = []\n        self._error_count = 0\n\n    def handle(self, error: Violation) -> None:  # noqa: WPS110\n        \"\"\"Processes each :term:`violation` to print it and all related.\"\"\"\n        if error.filename not in self._processed_filenames:\n            self._print_header(error.filename)\n            self._processed_filenames.append(error.filename)\n\n        line = self.format(error)\n        source = self.show_source(error)\n        link = self._show_link(error)\n\n        self._write(line)\n        if link:\n            self._write(link)\n        if source:\n            self._write(source)\n\n        self._error_count += 1\n\n    def format(self, error: Violation) -> str:  # noqa: WPS125\n        \"\"\"Called to format each individual :term:`violation`.\"\"\"\n        return '{newline}  {row_col:<8} {code:<5} {text}'.format(\n            newline=self.newline if self._should_show_source(error) else '',\n            code=error.code,\n            text=error.text,\n            row_col='{0}:{1}'.format(error.line_number, error.column_number),\n        )\n\n    def show_source(self, error: Violation) -> str:\n        \"\"\"Called when ``--show-source`` option is provided.\"\"\"\n        if not self._should_show_source(error):\n            return ''\n\n        formatted_line = error.physical_line.lstrip()\n        adjust = len(error.physical_line) - len(formatted_line)\n\n        code = _highlight(\n            formatted_line,\n            self._lexer,\n            self._formatter,\n        )\n\n        return '  {code}  {spacing}^'.format(\n            code=code,\n            spacing=' ' * (error.column_number - 1 - adjust),\n        )\n\n    def show_statistics(self, statistics: Statistics) -> None:  # noqa: WPS210\n        \"\"\"Called when ``--statistic`` option is passed.\"\"\"\n        all_errors = 0\n        for error_code in statistics.error_codes():\n            stats_for_error_code = statistics.statistics_for(error_code)\n            statistic = next(stats_for_error_code)\n\n            count = statistic.count\n            count += sum(stat.count for stat in stats_for_error_code)\n            all_errors += count\n            error_by_file = _count_per_filename(statistics, error_code)\n\n            self._print_violation_per_file(\n                statistic,\n                error_code,\n                count,\n                error_by_file,\n            )\n\n        self._write(self.newline)\n        self._write(_underline(_bold('All errors: {0}'.format(all_errors))))\n\n    def stop(self) -> None:\n        \"\"\"Runs once per app when the formatting ends.\"\"\"\n        if self._error_count:\n            message = '{0}Full list of violations and explanations:{0}{1}'\n            self._write(message.format(self.newline, self._doc_url))\n\n    # Our own methods:\n\n    def _show_link(self, error: Violation) -> str:\n        \"\"\"Called when ``--show-violation-links`` option is provided.\"\"\"\n        if not self.options.show_violation_links:\n            return ''\n\n        return '  {spacing}-> {link}'.format(\n            spacing=' ' * 9,\n            link=SHORTLINK_TEMPLATE.format(error.code),\n        )\n\n    def _print_header(self, filename: str) -> None:\n        self._write(\n            '{newline}{filename}'.format(\n                filename=_underline(_bold(filename)),\n                newline=self.newline,\n            ),\n        )\n\n    def _print_violation_per_file(\n        self,\n        statistic: Statistics,\n        error_code: str,\n        count: int,\n        error_by_file: DefaultDict[str, int],\n    ):\n        self._write(\n            '{newline}{error_code}: {message}'.format(\n                newline=self.newline,\n                error_code=_bold(error_code),\n                message=statistic.message,\n            ),\n        )\n        for filename, error_count in error_by_file.items():\n            self._write(\n                '  {error_count:<5} {filename}'.format(\n                    error_count=error_count,\n                    filename=filename,\n                ),\n            )\n        self._write(_underline('Total: {0}'.format(count)))\n\n    def _should_show_source(self, error: Violation) -> bool:\n        return self.options.show_source and error.physical_line is not None\n\n\n# Formatting text:\n\ndef _bold(text: str) -> str:\n    r\"\"\"\n    Returns bold formatted text.\n\n    >>> _bold('Hello!')\n    '\\x1b[1mHello!\\x1b[0m'\n\n    \"\"\"\n    return '\\033[1m{0}\\033[0m'.format(text)\n\n\ndef _underline(text: str) -> str:\n    r\"\"\"\n    Returns underlined formatted text.\n\n    >>> _underline('Hello!')\n    '\\x1b[4mHello!\\x1b[0m'\n\n    \"\"\"\n    return '\\033[4m{0}\\033[0m'.format(text)\n\n\ndef _highlight(source: str, lexer, formatter) -> str:\n    \"\"\"\n    Highlights source code. Might fail.\n\n    See also:\n        https://github.com/wemake-services/wemake-python-styleguide/issues/794\n\n    \"\"\"\n    try:\n        return highlight(source, lexer, formatter)\n    except Exception:  # pragma: no cover\n        # Might fail on some systems, when colors are set incorrectly,\n        # or not available at all. In this case code will be just text.\n        return source\n\n\n# Helpers:\n\ndef _count_per_filename(\n    statistics: Statistics,\n    error_code: str,\n) -> DefaultDict[str, int]:\n    filenames: DefaultDict[str, int] = defaultdict(int)\n    stats_for_error_code = statistics.statistics_for(error_code)\n\n    for stat in stats_for_error_code:\n        filenames[stat.filename] += stat.count\n\n    return filenames\n", "path": "wemake_python_styleguide/formatter.py"}], "after_files": [{"content": "\"\"\"\nOur very own ``flake8`` formatter for better error messages.\n\nThat's how all ``flake8`` formatters work:\n\n.. mermaid::\n   :caption: ``flake8`` formatting API calls order.\n\n    graph LR\n        F2[start]  --> F3[after_init]\n        F3         --> F4[start]\n        F4         --> F5[beginning]\n        F5         --> F6[handle]\n        F6         --> F7[format]\n        F6\t       --> F8[show_source]\n        F6\t       --> F9[show_statistic]\n        F7         --> F10[finished]\n        F8         --> F10[finished]\n        F9         --> F10[finished]\n        F10       -.-> F5\n        F10        --> F11[stop]\n\n.. autoclass:: WemakeFormatter\n   :no-undoc-members:\n\n\"\"\"\n\nfrom collections import defaultdict\nfrom os import environ\nfrom typing import ClassVar, DefaultDict, Final, List\n\nfrom flake8.formatting.base import BaseFormatter\nfrom flake8.statistics import Statistics\nfrom flake8.style_guide import Violation\nfrom pygments import highlight\nfrom pygments.formatters import TerminalFormatter\nfrom pygments.lexers import PythonLexer\n\nfrom wemake_python_styleguide.version import pkg_version\n\n#: That url is generated and hosted by Sphinx.\n_DOCS_URL_TEMPLATE: Final = (\n    'https://wemake-python-styleguide.rtfd.io/en/{0}/pages/usage/violations/'\n)\n\n#: This url points to the specific violation page.\n_SHORTLINK_TEMPLATE: Final = 'https://pyflak.es/{0}'\n\n#: Option to disable any code highlight and text output format.\n#: See https://no-color.org\n_NO_COLOR: Final = environ.get('NO_COLOR', '0') == '1'\n\n\nclass WemakeFormatter(BaseFormatter):  # noqa: WPS214\n    \"\"\"\n    We need to format our style :term:`violations <violation>` beatifully.\n\n    The default formatter does not allow us to do that.\n    What things do we miss?\n\n    1. Spacing, everything is just mixed up and glued together\n    2. Colors and decoration, some information is easier\n       to gather just with colors or underlined text\n    3. Grouping, we need explicit grouping by filename\n    4. Incomplete and non-informative statistics\n\n    \"\"\"\n\n    _doc_url: ClassVar[str] = _DOCS_URL_TEMPLATE.format(pkg_version)\n\n    # API:\n\n    def after_init(self):\n        \"\"\"Called after the original ``init`` is used to set extra fields.\"\"\"\n        self._lexer = PythonLexer()\n        self._formatter = TerminalFormatter()\n\n        # Logic:\n        self._processed_filenames: List[str] = []\n        self._error_count = 0\n\n    def handle(self, error: Violation) -> None:  # noqa: WPS110\n        \"\"\"Processes each :term:`violation` to print it and all related.\"\"\"\n        if error.filename not in self._processed_filenames:\n            self._print_header(error.filename)\n            self._processed_filenames.append(error.filename)\n\n        line = self.format(error)\n        source = self.show_source(error)\n        link = self._show_link(error)\n\n        self._write(line)\n        if link:\n            self._write(link)\n        if source:\n            self._write(source)\n\n        self._error_count += 1\n\n    def format(self, error: Violation) -> str:  # noqa: WPS125\n        \"\"\"Called to format each individual :term:`violation`.\"\"\"\n        return '{newline}  {row_col:<8} {code:<5} {text}'.format(\n            newline=self.newline if self._should_show_source(error) else '',\n            code=error.code,\n            text=error.text,\n            row_col='{0}:{1}'.format(error.line_number, error.column_number),\n        )\n\n    def show_source(self, error: Violation) -> str:\n        \"\"\"Called when ``--show-source`` option is provided.\"\"\"\n        if not self._should_show_source(error):\n            return ''\n\n        formatted_line = error.physical_line.lstrip()\n        adjust = len(error.physical_line) - len(formatted_line)\n\n        code = _highlight(\n            formatted_line,\n            self._lexer,\n            self._formatter,\n        )\n\n        return '  {code}  {spacing}^'.format(\n            code=code,\n            spacing=' ' * (error.column_number - 1 - adjust),\n        )\n\n    def show_statistics(self, statistics: Statistics) -> None:  # noqa: WPS210\n        \"\"\"Called when ``--statistic`` option is passed.\"\"\"\n        all_errors = 0\n        for error_code in statistics.error_codes():\n            stats_for_error_code = statistics.statistics_for(error_code)\n            statistic = next(stats_for_error_code)\n\n            count = statistic.count\n            count += sum(stat.count for stat in stats_for_error_code)\n            all_errors += count\n            error_by_file = _count_per_filename(statistics, error_code)\n\n            self._print_violation_per_file(\n                statistic,\n                error_code,\n                count,\n                error_by_file,\n            )\n\n        self._write(self.newline)\n        self._write(_underline(_bold('All errors: {0}'.format(all_errors))))\n\n    def stop(self) -> None:\n        \"\"\"Runs once per app when the formatting ends.\"\"\"\n        if self._error_count:\n            message = '{0}Full list of violations and explanations:{0}{1}'\n            self._write(message.format(self.newline, self._doc_url))\n\n    # Our own methods:\n\n    def _show_link(self, error: Violation) -> str:\n        \"\"\"Called when ``--show-violation-links`` option is provided.\"\"\"\n        if not self.options.show_violation_links:\n            return ''\n\n        return '  {spacing}-> {link}'.format(\n            spacing=' ' * 9,\n            link=_SHORTLINK_TEMPLATE.format(error.code),\n        )\n\n    def _print_header(self, filename: str) -> None:\n        self._write(\n            '{newline}{filename}'.format(\n                filename=_underline(_bold(filename)),\n                newline=self.newline,\n            ),\n        )\n\n    def _print_violation_per_file(\n        self,\n        statistic: Statistics,\n        error_code: str,\n        count: int,\n        error_by_file: DefaultDict[str, int],\n    ):\n        self._write(\n            '{newline}{error_code}: {message}'.format(\n                newline=self.newline,\n                error_code=_bold(error_code),\n                message=statistic.message,\n            ),\n        )\n        for filename, error_count in error_by_file.items():\n            self._write(\n                '  {error_count:<5} {filename}'.format(\n                    error_count=error_count,\n                    filename=filename,\n                ),\n            )\n        self._write(_underline('Total: {0}'.format(count)))\n\n    def _should_show_source(self, error: Violation) -> bool:\n        return self.options.show_source and error.physical_line is not None\n\n\n# Formatting text:\n\ndef _bold(text: str, *, no_color: bool = _NO_COLOR) -> str:\n    r\"\"\"\n    Returns bold formatted text.\n\n    >>> _bold('Hello!')\n    '\\x1b[1mHello!\\x1b[0m'\n\n    Returns non-formatted text if environment variable ``NO_COLOR=1``.\n\n    >>> _bold('Hello!', no_color=True)\n    'Hello!'\n\n    \"\"\"\n    if no_color:\n        return text\n    return '\\033[1m{0}\\033[0m'.format(text)\n\n\ndef _underline(text: str, *, no_color: bool = _NO_COLOR) -> str:\n    r\"\"\"\n    Returns underlined formatted text.\n\n    >>> _underline('Hello!')\n    '\\x1b[4mHello!\\x1b[0m'\n\n    Returns non-formatted text if environment variable ``NO_COLOR=1``.\n\n    >>> _underline('Hello!', no_color=True)\n    'Hello!'\n\n    \"\"\"\n    if no_color:\n        return text\n    return '\\033[4m{0}\\033[0m'.format(text)\n\n\ndef _highlight(\n    source: str,\n    lexer: PythonLexer,\n    formatter: TerminalFormatter,\n    *,\n    no_color: bool = _NO_COLOR,\n) -> str:\n    \"\"\"\n    Highlights source code. Might fail.\n\n    Returns non-formatted text if environment variable ``NO_COLOR=1``.\n\n    See also:\n        https://github.com/wemake-services/wemake-python-styleguide/issues/794\n        https://no-color.org\n\n    \"\"\"\n    if no_color:\n        return source\n    try:\n        return highlight(source, lexer, formatter)\n    except Exception:  # pragma: no cover\n        # Might fail on some systems, when colors are set incorrectly,\n        # or not available at all. In this case code will be just text.\n        return source\n\n\n# Helpers:\n\ndef _count_per_filename(\n    statistics: Statistics,\n    error_code: str,\n) -> DefaultDict[str, int]:\n    filenames: DefaultDict[str, int] = defaultdict(int)\n    stats_for_error_code = statistics.statistics_for(error_code)\n\n    for stat in stats_for_error_code:\n        filenames[stat.filename] += stat.count\n\n    return filenames\n", "path": "wemake_python_styleguide/formatter.py"}]}