summaryrefslogtreecommitdiffstats
path: root/python/mozlint/mozlint/cli.py
blob: 02621733677f6c55b6caf5243ac124b7f7dde1d2 (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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
# 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 os
import sys
from argparse import REMAINDER, SUPPRESS, ArgumentParser
from pathlib import Path

from mozlint.errors import NoValidLinter
from mozlint.formatters import all_formatters


class MozlintParser(ArgumentParser):
    arguments = [
        [
            ["paths"],
            {
                "nargs": "*",
                "default": None,
                "help": "Paths to file or directories to lint, like "
                "'browser/components/loop' or 'mobile/android'. "
                "If not provided, defaults to the files changed according "
                "to --outgoing and --workdir.",
            },
        ],
        [
            ["-l", "--linter"],
            {
                "dest": "linters",
                "default": [],
                "action": "append",
                "help": "Linters to run, e.g 'eslint'. By default all linters "
                "are run for all the appropriate files.",
            },
        ],
        [
            ["--list"],
            {
                "dest": "list_linters",
                "default": False,
                "action": "store_true",
                "help": "List all available linters and exit.",
            },
        ],
        [
            ["-W", "--warnings"],
            {
                "const": True,
                "nargs": "?",
                "choices": ["soft"],
                "dest": "show_warnings",
                "help": "Display and fail on warnings in addition to errors. "
                "--warnings=soft can be used to report warnings but only fail "
                "on errors.",
            },
        ],
        [
            ["-v", "--verbose"],
            {
                "dest": "show_verbose",
                "default": False,
                "action": "store_true",
                "help": "Enable verbose logging.",
            },
        ],
        [
            ["-f", "--format"],
            {
                "dest": "formats",
                "action": "append",
                "help": "Formatter to use. Defaults to 'stylish' on stdout. "
                "You can specify an optional path as --format formatter:path "
                "that will be used instead of stdout. "
                "You can also use multiple formatters at the same time. "
                "Formatters available: {}.".format(", ".join(all_formatters.keys())),
            },
        ],
        [
            ["-n", "--no-filter"],
            {
                "dest": "use_filters",
                "default": True,
                "action": "store_false",
                "help": "Ignore all filtering. This is useful for quickly "
                "testing a directory that otherwise wouldn't be run, "
                "without needing to modify the config file.",
            },
        ],
        [
            ["--include-third-party"],
            {
                "dest": "include_third-party",
                "default": False,
                "action": "store_true",
                "help": "Also run the linter(s) on third-party code",
            },
        ],
        [
            ["-o", "--outgoing"],
            {
                "const": True,
                "nargs": "?",
                "help": "Lint files touched by commits that are not on the remote repository. "
                "Without arguments, finds the default remote that would be pushed to. "
                "The remote branch can also be specified manually. Works with "
                "mercurial or git.",
            },
        ],
        [
            ["-w", "--workdir"],
            {
                "const": "all",
                "nargs": "?",
                "choices": ["staged", "all"],
                "help": "Lint files touched by changes in the working directory "
                "(i.e haven't been committed yet). On git, --workdir=staged "
                "can be used to only consider staged files. Works with "
                "mercurial or git.",
            },
        ],
        [
            ["-r", "--rev"],
            {
                "default": None,
                "type": str,
                "help": "Lint files touched by changes in revisions described by REV. "
                "For mercurial, it may be any revset. For git, it is a single tree-ish.",
            },
        ],
        [
            ["--fix"],
            {
                "action": "store_true",
                "default": False,
                "help": "Fix lint errors if possible. Any errors that could not be fixed "
                "will be printed as normal.",
            },
        ],
        [
            ["--edit"],
            {
                "action": "store_true",
                "default": False,
                "help": "Each file containing lint errors will be opened in $EDITOR one after "
                "the other.",
            },
        ],
        [
            ["--setup"],
            {
                "action": "store_true",
                "default": False,
                "help": "Bootstrap linter dependencies without running any of the linters.",
            },
        ],
        [
            ["-j", "--jobs"],
            {
                "default": None,
                "dest": "num_procs",
                "type": int,
                "help": "Number of worker processes to spawn when running linters. "
                "Defaults to the number of cores in your CPU.",
            },
        ],
        # Paths to check for linter configurations.
        # Default: tools/lint set in tools/lint/mach_commands.py
        [
            ["--config-path"],
            {
                "action": "append",
                "default": [],
                "dest": "config_paths",
                "help": SUPPRESS,
            },
        ],
        [
            ["--check-exclude-list"],
            {
                "dest": "check_exclude_list",
                "default": False,
                "action": "store_true",
                "help": "Run linters for all the paths in the exclude list.",
            },
        ],
        [
            ["extra_args"],
            {
                "nargs": REMAINDER,
                "help": "Extra arguments that will be forwarded to the underlying linter.",
            },
        ],
    ]

    def __init__(self, **kwargs):
        ArgumentParser.__init__(self, usage=self.__doc__, **kwargs)

        for cli, args in self.arguments:
            self.add_argument(*cli, **args)

    def parse_known_args(self, *args, **kwargs):
        # Allow '-wo' or '-ow' as shorthand for both --workdir and --outgoing.
        for token in ("-wo", "-ow"):
            if token in args[0]:
                i = args[0].index(token)
                args[0].pop(i)
                args[0][i:i] = [token[:2], "-" + token[2]]

        # This is here so the eslint mach command doesn't lose 'extra_args'
        # when using mach's dispatch functionality.
        args, extra = ArgumentParser.parse_known_args(self, *args, **kwargs)
        args.extra_args = extra

        self.validate(args)
        return args, extra

    def validate(self, args):
        if args.edit and not os.environ.get("EDITOR"):
            self.error("must set the $EDITOR environment variable to use --edit")

        if args.paths:
            invalid = [p for p in args.paths if not os.path.exists(p)]
            if invalid:
                self.error(
                    "the following paths do not exist:\n{}".format("\n".join(invalid))
                )

        if args.formats:
            formats = []
            for fmt in args.formats:
                if isinstance(fmt, tuple):  # format is already processed
                    formats.append(fmt)
                    continue

                path = None
                if ":" in fmt:
                    # Detect optional formatter path
                    pos = fmt.index(":")
                    fmt, path = fmt[:pos], os.path.realpath(fmt[pos + 1 :])

                    # Check path is writable
                    fmt_dir = os.path.dirname(path)
                    if not os.access(fmt_dir, os.W_OK | os.X_OK):
                        self.error(
                            "the following directory is not writable: {}".format(
                                fmt_dir
                            )
                        )

                if fmt not in all_formatters.keys():
                    self.error(
                        "the following formatter is not available: {}".format(fmt)
                    )

                formats.append((fmt, path))
            args.formats = formats
        else:
            # Can't use argparse default or this choice will be always present
            args.formats = [("stylish", None)]


def find_linters(config_paths, linters=None):
    lints = {}
    for search_path in config_paths:
        if not os.path.isdir(search_path):
            continue

        sys.path.insert(0, search_path)
        files = os.listdir(search_path)
        for f in files:
            name = os.path.basename(f)

            if not name.endswith(".yml"):
                continue

            name = name.rsplit(".", 1)[0]

            if linters and name not in linters:
                continue

            lints[name] = os.path.join(search_path, f)

    linters_not_found = list(set(linters).difference(set(lints.keys())))
    return {"lint_paths": lints.values(), "linters_not_found": linters_not_found}


def get_exclude_list_output(result, paths):
    # Store the paths of all the subdirectories leading to the error files
    error_file_paths = set()
    for issues in result.issues.values():
        error_file = issues[0].relpath
        error_file_paths.add(error_file)
        parent_dir = os.path.dirname(error_file)
        while parent_dir:
            error_file_paths.add(parent_dir)
            parent_dir = os.path.dirname(parent_dir)

    paths = [os.path.dirname(path) if path[-1] == "/" else path for path in paths]
    # Remove all the error paths to get the list of green paths
    green_paths = sorted(set(paths).difference(error_file_paths))

    if green_paths:
        out = (
            "The following list of paths are now green "
            "and can be removed from the exclude list:\n\n"
        )
        out += "\n".join(green_paths)

    else:
        out = "No path in the exclude list is green."

    return out


def run(
    paths,
    linters,
    formats,
    outgoing,
    workdir,
    rev,
    edit,
    check_exclude_list,
    setup=False,
    list_linters=False,
    num_procs=None,
    virtualenv_manager=None,
    setupargs=None,
    **lintargs
):
    from mozlint import LintRoller, formatters
    from mozlint.editor import edit_issues

    lintargs["config_paths"] = [
        os.path.join(lintargs["root"], p) for p in lintargs["config_paths"]
    ]

    # Always perform exhaustive linting for exclude list paths
    lintargs["use_filters"] = lintargs["use_filters"] and not check_exclude_list

    if list_linters:
        lint_paths = find_linters(lintargs["config_paths"], linters)
        linters = [
            os.path.splitext(os.path.basename(l))[0] for l in lint_paths["lint_paths"]
        ]
        print("\n".join(sorted(linters)))
        print(
            "\nNote that clang-tidy checks are not run as part of this "
            "command, but using the static-analysis command."
        )
        return 0

    lint = LintRoller(setupargs=setupargs or {}, **lintargs)
    linters_info = find_linters(lintargs["config_paths"], linters)

    result = None

    try:

        lint.read(linters_info["lint_paths"])

        if check_exclude_list:
            if len(lint.linters) > 1:
                print("error: specify a single linter to check with `-l/--linter`")
                return 1
            paths = lint.linters[0]["local_exclude"]

        if (
            not paths
            and Path.cwd() == Path(lint.root)
            and not (outgoing or workdir or rev)
        ):
            print(
                "warning: linting the entire repo takes a long time, using --outgoing and "
                "--workdir instead. If you want to lint the entire repo, run `./mach lint .`"
            )
            # Setting the default values
            outgoing = True
            workdir = "all"

        # Always run bootstrapping, but return early if --setup was passed in.
        ret = lint.setup(virtualenv_manager=virtualenv_manager)
        if setup:
            return ret

        if linters_info["linters_not_found"] != []:
            raise NoValidLinter

        # run all linters
        result = lint.roll(
            paths, outgoing=outgoing, workdir=workdir, rev=rev, num_procs=num_procs
        )
    except NoValidLinter as e:
        result = lint.result
        print(str(e))

    if edit and result.issues:
        edit_issues(result)
        result = lint.roll(result.issues.keys(), num_procs=num_procs)

    for every in linters_info["linters_not_found"]:
        result.failed_setup.add(every)

    if check_exclude_list:
        # Get and display all those paths in the exclude list which are
        # now green and can be safely removed from the list
        out = get_exclude_list_output(result, paths)
        print(out, file=sys.stdout)
        return result.returncode

    for formatter_name, path in formats:
        formatter = formatters.get(formatter_name)

        out = formatter(result)
        # We do this only for `json` that is mostly used in automation
        if not out and formatter_name == "json":
            out = "{}"

        if out:
            fh = open(path, "w") if path else sys.stdout

            if not path and fh.encoding == "ascii":
                # If sys.stdout.encoding is ascii, printing output will fail
                # due to the stylish formatter's use of unicode characters.
                # Ideally the user should fix their environment by setting
                # `LC_ALL=C.UTF-8` or similar. But this is a common enough
                # problem that we help them out a little here by manually
                # encoding and writing to the stdout buffer directly.
                out += "\n"
                fh.buffer.write(out.encode("utf-8", errors="replace"))
                fh.buffer.flush()
            else:
                print(out, file=fh)

            if path:
                fh.close()

    return result.returncode


if __name__ == "__main__":
    parser = MozlintParser()
    args = vars(parser.parse_args())
    sys.exit(run(**args))