Exemple #1
0
class PyCodeChecker():
    def __init__(self, filename):
        self.checker = Checker(filename)

    def getString(self):

        with io.StringIO() as buf, redirect_stdout(buf):

            self.checker.check_all()
            output = buf.getvalue()

        return output

    def getListFromString(self, text):

        rawList = []

        rawList = text.split("\n")

        parseList = []
        for line in rawList:
            obj = line.split(':')
            parseList.append(obj)

        lineList = []
        cursorList = []
        textList = []

        for obj in parseList[:-1]:  # last element is ''
            lineList.append(obj[1])
            cursorList.append(obj[2])
            textList.append(obj[3])

        return lineList, cursorList, textList
Exemple #2
0
def rate(request):
    if request.method == 'POST':
        form = forms.CodeForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
        with open("source_code.py", "w") as file:
            file.write(data["code"])
        checker = Checker('source_code.py')
        output = io.StringIO()
        with redirect_stdout(output):
            checker.check_all()
        os.remove("source_code.py")
        issues = output.getvalue()
        response_string = format_output(issues)
        return render(
            request, 'rate_form.html', {
                'form': form,
                'message': 'Checking done!',
                'code': data["code"],
                'response_string': response_string,
            })
    else:
        form = forms.CodeForm

    return render(request, 'rate_form.html', {
        'form': form,
        'message': "Let's rate your code."
    })
 def execute_pep8(file_path):
     try:
         absolute_path = abspath(file_path)
     except FileNotFoundError:
         print('File at ' + file_path +' is not found')
     except Exception as e:
         print(e)
     checker = Checker(absolute_path, reporter=QuietReport)
     checker.check_all()
     return checker.report.full_error_results()
Exemple #4
0
 def check_and_get_results(filename, file_content=None):
     file_content = bytes(file_content) if file_content else b""
     py_file = io.BytesIO(file_content)
     chk = Checker(filename, lines=read_file_line(py_file))
     chk.max_line_length = DEFAULT_LINE_WIDTH
     results = chk.check_all()
     results = chk.report._deferred_print
     if not results:
         return iter(())
     for result in chk.report._deferred_print:
         line, col, err_code, msg, smry = result
         msg = get_show_msg(err_code, msg, line, col)
         yield (line, msg)
Exemple #5
0
def check_pycodestyle(code):
    """
    Given some code, uses the PyCodeStyle module (was PEP8) to return a list
    of items describing issues of coding style. See:

    https://pycodestyle.readthedocs.io/en/latest/intro.html
    """
    # PyCodeStyle reads input from files, so make a temporary file containing
    # the code.
    code_fd, code_filename = tempfile.mkstemp()
    os.close(code_fd)
    with open(code_filename, 'w', newline='') as code_file:
        write_and_flush(code_file, code)
    # Configure which PEP8 rules to ignore.
    ignore = ('E121', 'E123', 'E126', 'E226', 'E302', 'E305', 'E24', 'E704',
              'W291', 'W292', 'W293', 'W391', 'W503', )
    style = StyleGuide(parse_argv=False, config_file=False)
    style.options.ignore = ignore
    checker = Checker(code_filename, options=style.options)
    # Re-route stdout to a temporary buffer to be parsed below.
    temp_out = io.StringIO()
    sys.stdout = temp_out
    # Check the code.
    checker.check_all()
    # Put stdout back and read the content of the buffer. Remove the temporary
    # file created at the start.
    sys.stdout = sys.__stdout__
    temp_out.seek(0)
    results = temp_out.read()
    temp_out.close()
    code_file.close()
    os.remove(code_filename)
    # Parse the output from the tool into a dictionary of structured data.
    style_feedback = {}
    for result in results.split('\n'):
        matcher = STYLE_REGEX.match(result)
        if matcher:
            line_no, col, msg = matcher.groups()
            line_no = int(line_no) - 1
            code, description = msg.split(' ', 1)
            if code == 'E303':
                description += _(' above this line')
            if line_no not in style_feedback:
                style_feedback[line_no] = []
            style_feedback[line_no].append({
                'line_no': line_no,
                'column': int(col) - 1,
                'message': description.capitalize(),
                'code': code,
            })
    return style_feedback
Exemple #6
0
def check_pycodestyle(code):
    """
    Given some code, uses the PyCodeStyle module (was PEP8) to return a list
    of items describing issues of coding style. See:

    https://pycodestyle.readthedocs.io/en/latest/intro.html
    """
    # PyCodeStyle reads input from files, so make a temporary file containing
    # the code.
    code_fd, code_filename = tempfile.mkstemp()
    os.close(code_fd)
    with open(code_filename, 'w', newline='') as code_file:
        write_and_flush(code_file, code)
    # Configure which PEP8 rules to ignore.
    ignore = ('E121', 'E123', 'E126', 'E226', 'E302', 'E305', 'E24', 'E704',
              'W291', 'W292', 'W293', 'W391', 'W503', )
    style = StyleGuide(parse_argv=False, config_file=False)
    style.options.ignore = ignore
    checker = Checker(code_filename, options=style.options)
    # Re-route stdout to a temporary buffer to be parsed below.
    temp_out = io.StringIO()
    sys.stdout = temp_out
    # Check the code.
    checker.check_all()
    # Put stdout back and read the content of the buffer. Remove the temporary
    # file created at the start.
    sys.stdout = sys.__stdout__
    temp_out.seek(0)
    results = temp_out.read()
    temp_out.close()
    code_file.close()
    os.remove(code_filename)
    # Parse the output from the tool into a dictionary of structured data.
    style_feedback = {}
    for result in results.split('\n'):
        matcher = STYLE_REGEX.match(result)
        if matcher:
            line_no, col, msg = matcher.groups()
            line_no = int(line_no) - 1
            code, description = msg.split(' ', 1)
            if code == 'E303':
                description += _(' above this line')
            if line_no not in style_feedback:
                style_feedback[line_no] = []
            style_feedback[line_no].append({
                'line_no': line_no,
                'column': int(col) - 1,
                'message': description.capitalize(),
                'code': code,
            })
    return style_feedback
Exemple #7
0
def selftest(options):
    """
    Test all check functions with test cases in docstrings.
    """
    count_failed = count_all = 0
    report = BaseReport(options)
    counters = report.counters
    checks = options.physical_checks + options.logical_checks
    for name, check, argument_names in checks:
        for line in check.__doc__.splitlines():
            line = line.lstrip()
            match = SELFTEST_REGEX.match(line)
            if match is None:
                continue
            code, source = match.groups()
            lines = [
                part.replace(r'\t', '\t') + '\n'
                for part in source.split(r'\n')
            ]
            checker = Checker(lines=lines, options=options, report=report)
            checker.check_all()
            error = None
            if code == 'Okay':
                if len(counters) > len(options.benchmark_keys):
                    codes = [
                        key for key in counters
                        if key not in options.benchmark_keys
                    ]
                    error = "incorrectly found %s" % ', '.join(codes)
            elif not counters.get(code):
                error = "failed to find %s" % code
            # Keep showing errors for multiple tests
            for key in set(counters) - set(options.benchmark_keys):
                del counters[key]
            count_all += 1
            if not error:
                if options.verbose:
                    print("%s: %s" % (code, source))
            else:
                count_failed += 1
                print("pycodestyle.py: %s:" % error)
                for line in checker.lines:
                    print(line.rstrip())
    return count_failed, count_all
    def run_check(self, ctx: RunContext):  # noqa
        """Check code with pycodestyle."""
        params = ctx.get_params("pycodestyle")
        options = ctx.options
        if options:
            params.setdefault("max_line_length", options.max_line_length)

        if params:
            parser = get_parser()
            for option in parser.option_list:
                if option.dest and option.dest in params:
                    value = params[option.dest]
                    if isinstance(value, str):
                        params[option.dest] = option.convert_value(
                            option, value)

        style = StyleGuide(reporter=_PycodestyleReport, **params)
        options = style.options
        options.report.ctx = ctx  # type: ignore
        checker = Checker(ctx.filename, lines=ctx.lines, options=options)
        checker.check_all()
Exemple #9
0
def selftest(options):
    """
    Test all check functions with test cases in docstrings.
    """
    count_failed = count_all = 0
    report = BaseReport(options)
    counters = report.counters
    checks = options.physical_checks + options.logical_checks
    for name, check, argument_names in checks:
        for line in check.__doc__.splitlines():
            line = line.lstrip()
            match = SELFTEST_REGEX.match(line)
            if match is None:
                continue
            code, source = match.groups()
            lines = [part.replace(r'\t', '\t') + '\n'
                     for part in source.split(r'\n')]
            checker = Checker(lines=lines, options=options, report=report)
            checker.check_all()
            error = None
            if code == 'Okay':
                if len(counters) > len(options.benchmark_keys):
                    codes = [key for key in counters
                             if key not in options.benchmark_keys]
                    error = "incorrectly found %s" % ', '.join(codes)
            elif not counters.get(code):
                error = "failed to find %s" % code
            # Keep showing errors for multiple tests
            for key in set(counters) - set(options.benchmark_keys):
                del counters[key]
            count_all += 1
            if not error:
                if options.verbose:
                    print("%s: %s" % (code, source))
            else:
                count_failed += 1
                print("pycodestyle.py: %s:" % error)
                for line in checker.lines:
                    print(line.rstrip())
    return count_failed, count_all
Exemple #10
0
 def __init__(self, filename):
     self.checker = Checker(filename)
Exemple #11
0
from pycodestyle import Checker, StyleGuide
import re

source = [
    "firstImage = hdu1[1].data['FLUX'][0]\n",
    "fig = plt.figure(figsize=(8,8))\n",
    "plt.imshow(firstImage, origin = 'lower', cmap = plt.cm.viridis, \\\n",
    "           vmax = np.percentile(firstImage,92), vmin = np.percentile(firstImage,5))\n",
    "plt.xlabel('CCD Column', fontsize = 14)\n",
    "plt.ylabel('CCD Row', fontsize = 14)\n",
    "plt.grid(axis = 'both', color = 'white', ls = 'solid')"
]

c = Checker(lines=source, quiet=1, ignore=('W292', 'E122'))
c.check_all()
report = c.report
l = []

for line_number, offset, code, text, doc in report._deferred_print:
    if line_number > len(report.lines):
        line = ''
    else:
        line = report.lines[line_number - 1]
    l.append(
        '%(path)s:%(row)d:%(col)d: %(code)s %(text)s \n%(source)s' % {
            'path':
            report.filename,
            'row':
            report.line_offset + line_number,
            'col':
            offset + 1,
Exemple #12
0
def pep8_file(filename):
    """return whether the given file passes PEP8 standards"""
    checker = Checker(filename=filename, options=PEP8_OPTIONS)
    return checker.check_all() == 0
Exemple #13
0
    buf = bytes()
    while len(buf) < size:
        buf += stdin.buffer.read(min(1024, size - len(buf)))
    lines = buf.decode("utf-8").splitlines()
    opts, text = lines[:3], [l + "\n" for l in lines[3:]]

    if Checker is not None:
        style_guide = StyleGuide()
        options = style_guide.options
        select = [x for x in opts[0].strip().split(',') if len(x) > 0]
        ignore = [x for x in opts[1].strip().split(',') if len(x) > 0]
        options.select = tuple(select)
        options.ignore = tuple(ignore)
        options.max_line_length = int(opts[2])
        stderr.flush()
        c = Checker(lines=text, options=options)
        output = StringIO()
        with redirect_stdout(output):
            # writes directly to stdout, so catch it ...
            c.check_all()
        output = output.getvalue()
        output = output[:2**15]

        stdout.write("{0:>10}".format(len(output)))
        stdout.write(output)
        stdout.flush()
    else:
        stderr.write(
            "The `pycodestyle` (previously `pep8`) module is not installed.")
        stderr.flush()