3 """Module used to manage the results of flake8 :
5 > 1. get them instead of print them ;
8 This module works with Python2 and Python3
10 :author: Sébastien CHAZALLET <s.chazallet@gmail.com>
11 :organization: InsPyration EURL
12 :copyright: Copyright © InsPyration EURL <www.inspyration.org>
13 :license: GPL 3 <http://www.gnu.org/licenses/gpl.html>
20 if sys.version_info.major == 2:
21 from io import BytesIO as IO
23 from io import StringIO as IO
25 from flake8.main import check_code
28 def _intercept_printed(action, *args, **kwargs):
29 """Function used to redirect printed to returned value
31 :type action: function
32 :param action: Called function that we intercept prints
35 :return: all that was printed by the call of action
38 ... print('Hello World')
40 >>> result = _intercept_printed(do)
46 out, sys.stdout = sys.stdout, buff
47 action(*args, **kwargs)
53 def _format_flake8_results(warnings):
54 """Function used to extract useful informations from flake8 results
57 :param warnings: Warnings generated by flake8
60 :return: list of (code:str, line:int, col:int, description:str)
62 >>> result = _format_flake8_results(
63 ... '''stdin:1:10: E901 SyntaxError: unexpected EOF while parsing
64 ... stdin:2:1: E901 TokenError: EOF in multi-line statement''')
68 (' e901', 1, 10, 'SyntaxError: unexpected EOF while parsing')
69 (' e901', 2, 1, 'TokenError: EOF in multi-line statement')
72 for warning in warnings.splitlines():
73 cols = warning.split(':')
74 result.append((cols[3][:5].lower(),
77 cols[3][6:] + ':' + ':'.join(cols[4:])))
81 def check_code_and_get_formated_result(code, ignore=(), complexity=-1):
82 """Function used to return the printed result of flake8 check_code function
84 >>> result = check_code_with_flake8("a = 42")
87 >>> result = check_code_with_flake8("a = f(42")
89 stdin:1:10: E901 SyntaxError: unexpected EOF while parsing
90 stdin:2:1: E901 TokenError: EOF in multi-line statement
93 return _format_flake8_results(
96 **{"code": code, "ignore": ignore, "complexity": complexity}))
99 if __name__ == '__main__':