run-clang-format.py 10.4 KB
Newer Older
1
#!/usr/bin/env python
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
"""
MIT License

Copyright (c) 2017 Guillaume Papin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
24
25

A wrapper script around clang-format, suitable for linting multiple files
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
and to use for continuous integration.

This is an alternative API for the clang-format command line.
It runs over multiple files and directories in parallel.
A diff output is produced and a sensible exit code is returned.

"""

import argparse
import difflib
import fnmatch
import multiprocessing
import os
import signal
import subprocess
import sys
import traceback
from functools import partial

try:
    from subprocess import DEVNULL  # py3k
except ImportError:
    DEVNULL = open(os.devnull, "wb")


51
DEFAULT_EXTENSIONS = "c,h,C,H,cpp,hpp,cc,hh,c++,h++,cxx,hxx,cu"
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74


class ExitStatus:
    SUCCESS = 0
    DIFF = 1
    TROUBLE = 2


def list_files(files, recursive=False, extensions=None, exclude=None):
    if extensions is None:
        extensions = []
    if exclude is None:
        exclude = []

    out = []
    for file in files:
        if recursive and os.path.isdir(file):
            for dirpath, dnames, fnames in os.walk(file):
                fpaths = [os.path.join(dirpath, fname) for fname in fnames]
                for pattern in exclude:
                    # os.walk() supports trimming down the dnames list
                    # by modifying it in-place,
                    # to avoid unnecessary directory listings.
75
76
                    dnames[:] = [x for x in dnames if not fnmatch.fnmatch(os.path.join(dirpath, x), pattern)]
                    fpaths = [x for x in fpaths if not fnmatch.fnmatch(x, pattern)]
77
78
79
80
81
82
83
84
85
86
87
88
                for f in fpaths:
                    ext = os.path.splitext(f)[1][1:]
                    if ext in extensions:
                        out.append(f)
        else:
            out.append(file)
    return out


def make_diff(file, original, reformatted):
    return list(
        difflib.unified_diff(
89
            original, reformatted, fromfile=f"{file}\t(original)", tofile=f"{file}\t(reformatted)", n=3
90
91
        )
    )
92
93
94
95


class DiffError(Exception):
    def __init__(self, message, errs=None):
96
        super().__init__(message)
97
98
99
100
101
        self.errs = errs or []


class UnexpectedError(Exception):
    def __init__(self, message, exc=None):
102
        super().__init__(message)
103
104
105
106
107
108
109
110
111
112
113
        self.formatted_traceback = traceback.format_exc()
        self.exc = exc


def run_clang_format_diff_wrapper(args, file):
    try:
        ret = run_clang_format_diff(args, file)
        return ret
    except DiffError:
        raise
    except Exception as e:
114
        raise UnexpectedError(f"{file}: {e.__class__.__name__}: {e}", e)
115
116
117
118


def run_clang_format_diff(args, file):
    try:
119
        with open(file, encoding="utf-8") as f:
120
            original = f.readlines()
121
    except OSError as exc:
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
        raise DiffError(str(exc))
    invocation = [args.clang_format_executable, file]

    # Use of utf-8 to decode the process output.
    #
    # Hopefully, this is the correct thing to do.
    #
    # It's done due to the following assumptions (which may be incorrect):
    # - clang-format will returns the bytes read from the files as-is,
    #   without conversion, and it is already assumed that the files use utf-8.
    # - if the diagnostics were internationalized, they would use utf-8:
    #   > Adding Translations to Clang
    #   >
    #   > Not possible yet!
    #   > Diagnostic strings should be written in UTF-8,
    #   > the client can translate to the relevant code page if needed.
    #   > Each translation completely replaces the format string
    #   > for the diagnostic.
    #   > -- http://clang.llvm.org/docs/InternalsManual.html#internals-diag-translation

    try:
        proc = subprocess.Popen(
144
            invocation, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, encoding="utf-8"
145
        )
146
    except OSError as exc:
147
        raise DiffError(f"Command '{subprocess.list2cmdline(invocation)}' failed to start: {exc}")
148
149
    proc_stdout = proc.stdout
    proc_stderr = proc.stderr
150

151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
    # hopefully the stderr pipe won't get full and block the process
    outs = list(proc_stdout.readlines())
    errs = list(proc_stderr.readlines())
    proc.wait()
    if proc.returncode:
        raise DiffError(
            "Command '{}' returned non-zero exit status {}".format(
                subprocess.list2cmdline(invocation), proc.returncode
            ),
            errs,
        )
    return make_diff(file, original, outs), errs


def bold_red(s):
166
    return "\x1b[1m\x1b[31m" + s + "\x1b[0m"
167
168
169
170


def colorize(diff_lines):
    def bold(s):
171
        return "\x1b[1m" + s + "\x1b[0m"
172
173

    def cyan(s):
174
        return "\x1b[36m" + s + "\x1b[0m"
175
176

    def green(s):
177
        return "\x1b[32m" + s + "\x1b[0m"
178
179

    def red(s):
180
        return "\x1b[31m" + s + "\x1b[0m"
181
182

    for line in diff_lines:
183
        if line[:4] in ["--- ", "+++ "]:
184
            yield bold(line)
185
        elif line.startswith("@@ "):
186
            yield cyan(line)
187
        elif line.startswith("+"):
188
            yield green(line)
189
        elif line.startswith("-"):
190
191
192
193
194
195
196
197
            yield red(line)
        else:
            yield line


def print_diff(diff_lines, use_color):
    if use_color:
        diff_lines = colorize(diff_lines)
198
    sys.stdout.writelines(diff_lines)
199
200
201


def print_trouble(prog, message, use_colors):
202
    error_text = "error:"
203
204
    if use_colors:
        error_text = bold_red(error_text)
205
    print(f"{prog}: {error_text} {message}", file=sys.stderr)
206
207
208
209
210


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
211
212
213
214
215
        "--clang-format-executable",
        metavar="EXECUTABLE",
        help="path to the clang-format executable",
        default="clang-format",
    )
216
    parser.add_argument(
217
        "--extensions",
218
        help=f"comma separated list of file extensions (default: {DEFAULT_EXTENSIONS})",
219
220
221
222
223
        default=DEFAULT_EXTENSIONS,
    )
    parser.add_argument("-r", "--recursive", action="store_true", help="run recursively over directories")
    parser.add_argument("files", metavar="file", nargs="+")
    parser.add_argument("-q", "--quiet", action="store_true")
224
    parser.add_argument(
225
226
        "-j",
        metavar="N",
227
228
        type=int,
        default=0,
229
        help="run N clang-format jobs in parallel (default number of cpus + 1)",
230
    )
231
    parser.add_argument(
232
233
        "--color", default="auto", choices=["auto", "always", "never"], help="show colored diff (default: auto)"
    )
234
    parser.add_argument(
235
236
237
238
        "-e",
        "--exclude",
        metavar="PATTERN",
        action="append",
239
        default=[],
240
        help="exclude paths matching the given glob-like pattern(s) from recursive search",
241
    )
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257

    args = parser.parse_args()

    # use default signal handling, like diff return SIGINT value on ^C
    # https://bugs.python.org/issue14229#msg156446
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    try:
        signal.SIGPIPE
    except AttributeError:
        # compatibility, SIGPIPE does not exist on Windows
        pass
    else:
        signal.signal(signal.SIGPIPE, signal.SIG_DFL)

    colored_stdout = False
    colored_stderr = False
258
    if args.color == "always":
259
260
        colored_stdout = True
        colored_stderr = True
261
    elif args.color == "auto":
262
263
264
        colored_stdout = sys.stdout.isatty()
        colored_stderr = sys.stderr.isatty()

265
    version_invocation = [args.clang_format_executable, "--version"]
266
267
268
269
270
271
272
273
    try:
        subprocess.check_call(version_invocation, stdout=DEVNULL)
    except subprocess.CalledProcessError as e:
        print_trouble(parser.prog, str(e), use_colors=colored_stderr)
        return ExitStatus.TROUBLE
    except OSError as e:
        print_trouble(
            parser.prog,
274
            f"Command '{subprocess.list2cmdline(version_invocation)}' failed to start: {e}",
275
276
277
278
279
280
            use_colors=colored_stderr,
        )
        return ExitStatus.TROUBLE

    retcode = ExitStatus.SUCCESS
    files = list_files(
281
282
        args.files, recursive=args.recursive, exclude=args.exclude, extensions=args.extensions.split(",")
    )
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298

    if not files:
        return

    njobs = args.j
    if njobs == 0:
        njobs = multiprocessing.cpu_count() + 1
    njobs = min(len(files), njobs)

    if njobs == 1:
        # execute directly instead of in a pool,
        # less overhead, simpler stacktraces
        it = (run_clang_format_diff_wrapper(args, file) for file in files)
        pool = None
    else:
        pool = multiprocessing.Pool(njobs)
299
        it = pool.imap_unordered(partial(run_clang_format_diff_wrapper, args), files)
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
    while True:
        try:
            outs, errs = next(it)
        except StopIteration:
            break
        except DiffError as e:
            print_trouble(parser.prog, str(e), use_colors=colored_stderr)
            retcode = ExitStatus.TROUBLE
            sys.stderr.writelines(e.errs)
        except UnexpectedError as e:
            print_trouble(parser.prog, str(e), use_colors=colored_stderr)
            sys.stderr.write(e.formatted_traceback)
            retcode = ExitStatus.TROUBLE
            # stop at the first unexpected error,
            # something could be very wrong,
            # don't process all files unnecessarily
            if pool:
                pool.terminate()
            break
        else:
            sys.stderr.writelines(errs)
            if outs == []:
                continue
            if not args.quiet:
                print_diff(outs, use_color=colored_stdout)
            if retcode == ExitStatus.SUCCESS:
                retcode = ExitStatus.DIFF
    return retcode


330
if __name__ == "__main__":
331
    sys.exit(main())