summaryrefslogtreecommitdiff
path: root/tools/lint/flake8.lint
blob: 2609bfbb28fcb70aab8b016eb37bd07c7b03b576 (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import json
import os
import signal
import subprocess

import which
from mozprocess import ProcessHandler

from mozlint import result


here = os.path.abspath(os.path.dirname(__file__))
FLAKE8_REQUIREMENTS_PATH = os.path.join(here, 'flake8', 'flake8_requirements.txt')

FLAKE8_NOT_FOUND = """
Could not find flake8! Install flake8 and try again.

    $ pip install -U --require-hashes -r {}
""".strip().format(FLAKE8_REQUIREMENTS_PATH)


FLAKE8_INSTALL_ERROR = """
Unable to install correct version of flake8
Try to install it manually with:
    $ pip install -U --require-hashes -r {}
""".strip().format(FLAKE8_REQUIREMENTS_PATH)

LINE_OFFSETS = {
    # continuation line under-indented for hanging indent
    'E121': (-1, 2),
    # continuation line missing indentation or outdented
    'E122': (-1, 2),
    # continuation line over-indented for hanging indent
    'E126': (-1, 2),
    # continuation line over-indented for visual indent
    'E127': (-1, 2),
    # continuation line under-indented for visual indent
    'E128': (-1, 2),
    # continuation line unaligned for hanging indend
    'E131': (-1, 2),
    # expected 1 blank line, found 0
    'E301': (-1, 2),
    # expected 2 blank lines, found 1
    'E302': (-2, 3),
}
"""Maps a flake8 error to a lineoffset tuple.

The offset is of the form (lineno_offset, num_lines) and is passed
to the lineoffset property of `ResultContainer`.
"""

EXTENSIONS = ['.py', '.lint']
results = []


def process_line(line):
    # Escape slashes otherwise JSON conversion will not work
    line = line.replace('\\', '\\\\')
    try:
        res = json.loads(line)
    except ValueError:
        print('Non JSON output from linter, will not be processed: {}'.format(line))
        return

    if 'code' in res:
        if res['code'].startswith('W'):
            res['level'] = 'warning'

        if res['code'] in LINE_OFFSETS:
            res['lineoffset'] = LINE_OFFSETS[res['code']]

    results.append(result.from_linter(LINTER, **res))


def run_process(cmdargs):
    # flake8 seems to handle SIGINT poorly. Handle it here instead
    # so we can kill the process without a cryptic traceback.
    orig = signal.signal(signal.SIGINT, signal.SIG_IGN)
    proc = ProcessHandler(cmdargs, env=os.environ,
                          processOutputLine=process_line)
    proc.run()
    signal.signal(signal.SIGINT, orig)

    try:
        proc.wait()
    except KeyboardInterrupt:
        proc.kill()


def get_flake8_binary():
    """
    Returns the path of the first flake8 binary available
    if not found returns None
    """
    binary = os.environ.get('FLAKE8')
    if binary:
        return binary

    try:
        return which.which('flake8')
    except which.WhichError:
        return None


def _run_pip(*args):
    """
    Helper function that runs pip with subprocess
    """
    try:
        subprocess.check_output(['pip'] + list(args),
                                      stderr=subprocess.STDOUT)
        return True
    except subprocess.CalledProcessError as e:
        print(e.output)
        return False


def reinstall_flake8():
    """
    Try to install flake8 at the target version, returns True on success
    otherwise prints the otuput of the pip command and returns False
    """
    if _run_pip('install', '-U',
                '--require-hashes', '-r',
                FLAKE8_REQUIREMENTS_PATH):
        return True

    return False


def lint(files, **lintargs):

    if not reinstall_flake8():
        print(FLAKE8_INSTALL_ERROR)
        return 1

    binary = get_flake8_binary()

    cmdargs = [
        binary,
        '--format', '{"path":"%(path)s","lineno":%(row)s,'
                    '"column":%(col)s,"rule":"%(code)s","message":"%(text)s"}',
    ]

    # Run any paths with a .flake8 file in the directory separately so
    # it gets picked up. This means only .flake8 files that live in
    # directories that are explicitly included will be considered.
    # See bug 1277851
    no_config = []
    for f in files:
        if not os.path.isfile(os.path.join(f, '.flake8')):
            no_config.append(f)
            continue
        run_process(cmdargs+[f])

    # XXX For some reason passing in --exclude results in flake8 not using
    # the local .flake8 file. So for now only pass in --exclude if there
    # is no local config.
    exclude = lintargs.get('exclude')
    if exclude:
        cmdargs += ['--exclude', ','.join(lintargs['exclude'])]

    if no_config:
        run_process(cmdargs+no_config)

    return results


LINTER = {
    'name': "flake8",
    'description': "Python linter",
    'include': [
        'python/mozlint',
        'taskcluster',
        'testing/firefox-ui',
        'testing/marionette/client',
        'testing/marionette/harness',
        'testing/marionette/puppeteer',
        'testing/mozbase',
        'testing/mochitest',
        'testing/talos/',
        'tools/lint',
    ],
    'exclude': ["testing/mozbase/mozdevice/mozdevice/Zeroconf.py",
                'testing/mochitest/pywebsocket'],
    'extensions': EXTENSIONS,
    'type': 'external',
    'payload': lint,
}