#-*- coding: utf8 -*-
"""Module used to manage the results of flake8 :
> 1. get them instead of print them ;
> 2. format them ;
This module works with Python2 and Python3
:author: Sébastien CHAZALLET <s.chazallet@gmail.com>
:organization: InsPyration EURL
:copyright: Copyright © InsPyration EURL <www.inspyration.org>
:license: GPL 3 <http://www.gnu.org/licenses/gpl.html>
:version: 0.1
"""
import sys
if sys.version_info.major == 2:
from io import BytesIO as IO
else:
from io import StringIO as IO
from flake8.main import check_code
[docs]def _intercept_printed(action, *args, **kwargs):
"""Function used to redirect printed to returned value
:type action: function
:param action: Called function that we intercept prints
:rtype: str
:return: all that was printed by the call of action
>>> def do():
... print('Hello World')
...
>>> result = _intercept_printed(do)
>>> print(result)
Hello World
<BLANKLINE>
"""
with IO() as buff:
out, sys.stdout = sys.stdout, buff
action(*args, **kwargs)
sys.stdout = out
buff.seek(0)
return buff.read()
[docs]def _format_flake8_results(warnings):
"""Function used to extract useful informations from flake8 results
:type warnings: str
:param warnings: Warnings generated by flake8
:rtype: list
:return: list of (code:str, line:int, col:int, description:str)
>>> result = _format_flake8_results(
... '''stdin:1:10: E901 SyntaxError: unexpected EOF while parsing
... stdin:2:1: E901 TokenError: EOF in multi-line statement''')
>>> for r in result:
... print r
...
(' e901', 1, 10, 'SyntaxError: unexpected EOF while parsing')
(' e901', 2, 1, 'TokenError: EOF in multi-line statement')
"""
result = []
for warning in warnings.splitlines():
cols = warning.split(':')
result.append((cols[3][:5].lower(),
int(cols[1]),
int(cols[2]),
cols[3][6:] + ':' + ':'.join(cols[4:])))
return result
[docs]def check_code_and_get_formated_result(code, ignore=(), complexity=-1):
"""Function used to return the printed result of flake8 check_code function
>>> result = check_code_with_flake8("a = 42")
>>> print(result)
<BLANKLINE>
>>> result = check_code_with_flake8("a = f(42")
>>> print(result)
stdin:1:10: E901 SyntaxError: unexpected EOF while parsing
stdin:2:1: E901 TokenError: EOF in multi-line statement
<BLANKLINE>
"""
return _format_flake8_results(
_intercept_printed(
check_code,
**{"code": code, "ignore": ignore, "complexity": complexity}))
if __name__ == '__main__':
import doctest
doctest.testmod()