Skip to content

Commit 5537790

Browse files
ShahriarSSfmassa
authored andcommitted
Checking clang-format for C++ side (#1274)
* Added initial code * Changed clang version * Changed travis script * Changed travis script * Updated travis script * Updated travis script * Updated travis script
1 parent 4985978 commit 5537790

File tree

3 files changed

+388
-0
lines changed

3 files changed

+388
-0
lines changed

.travis.yml

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,18 @@ language: python
33
dist: xenial
44
matrix:
55
include:
6+
- env: FORMAT_CHECK
7+
language: cpp
8+
addons:
9+
apt:
10+
sources:
11+
- llvm-toolchain-xenial-7
12+
packages:
13+
- clang-7
14+
- clang-format-7
15+
before_install: skip
16+
install: skip
17+
script: ./travis-scripts/run-clang-format/run-clang-format.py -r torchvision/csrc
618
- env: LINT_CHECK
719
python: "2.7"
820
install: pip install flake8
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2017 Guillaume Papin
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.
Lines changed: 355 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,355 @@
1+
#!/usr/bin/env python
2+
"""A wrapper script around clang-format, suitable for linting multiple files
3+
and to use for continuous integration.
4+
5+
This is an alternative API for the clang-format command line.
6+
It runs over multiple files and directories in parallel.
7+
A diff output is produced and a sensible exit code is returned.
8+
9+
"""
10+
11+
from __future__ import print_function, unicode_literals
12+
13+
import argparse
14+
import codecs
15+
import difflib
16+
import fnmatch
17+
import io
18+
import multiprocessing
19+
import os
20+
import signal
21+
import subprocess
22+
import sys
23+
import traceback
24+
25+
from functools import partial
26+
27+
try:
28+
from subprocess import DEVNULL # py3k
29+
except ImportError:
30+
DEVNULL = open(os.devnull, "wb")
31+
32+
33+
DEFAULT_EXTENSIONS = 'c,h,C,H,cpp,hpp,cc,hh,c++,h++,cxx,hxx'
34+
35+
36+
class ExitStatus:
37+
SUCCESS = 0
38+
DIFF = 1
39+
TROUBLE = 2
40+
41+
42+
def list_files(files, recursive=False, extensions=None, exclude=None):
43+
if extensions is None:
44+
extensions = []
45+
if exclude is None:
46+
exclude = []
47+
48+
out = []
49+
for file in files:
50+
if recursive and os.path.isdir(file):
51+
for dirpath, dnames, fnames in os.walk(file):
52+
fpaths = [os.path.join(dirpath, fname) for fname in fnames]
53+
for pattern in exclude:
54+
# os.walk() supports trimming down the dnames list
55+
# by modifying it in-place,
56+
# to avoid unnecessary directory listings.
57+
dnames[:] = [
58+
x for x in dnames
59+
if
60+
not fnmatch.fnmatch(os.path.join(dirpath, x), pattern)
61+
]
62+
fpaths = [
63+
x for x in fpaths if not fnmatch.fnmatch(x, pattern)
64+
]
65+
for f in fpaths:
66+
ext = os.path.splitext(f)[1][1:]
67+
if ext in extensions:
68+
out.append(f)
69+
else:
70+
out.append(file)
71+
return out
72+
73+
74+
def make_diff(file, original, reformatted):
75+
return list(
76+
difflib.unified_diff(
77+
original,
78+
reformatted,
79+
fromfile='{}\t(original)'.format(file),
80+
tofile='{}\t(reformatted)'.format(file),
81+
n=3))
82+
83+
84+
class DiffError(Exception):
85+
def __init__(self, message, errs=None):
86+
super(DiffError, self).__init__(message)
87+
self.errs = errs or []
88+
89+
90+
class UnexpectedError(Exception):
91+
def __init__(self, message, exc=None):
92+
super(UnexpectedError, self).__init__(message)
93+
self.formatted_traceback = traceback.format_exc()
94+
self.exc = exc
95+
96+
97+
def run_clang_format_diff_wrapper(args, file):
98+
try:
99+
ret = run_clang_format_diff(args, file)
100+
return ret
101+
except DiffError:
102+
raise
103+
except Exception as e:
104+
raise UnexpectedError('{}: {}: {}'.format(file, e.__class__.__name__,
105+
e), e)
106+
107+
108+
def run_clang_format_diff(args, file):
109+
try:
110+
with io.open(file, 'r', encoding='utf-8') as f:
111+
original = f.readlines()
112+
except IOError as exc:
113+
raise DiffError(str(exc))
114+
invocation = [args.clang_format_executable, file]
115+
116+
# Use of utf-8 to decode the process output.
117+
#
118+
# Hopefully, this is the correct thing to do.
119+
#
120+
# It's done due to the following assumptions (which may be incorrect):
121+
# - clang-format will returns the bytes read from the files as-is,
122+
# without conversion, and it is already assumed that the files use utf-8.
123+
# - if the diagnostics were internationalized, they would use utf-8:
124+
# > Adding Translations to Clang
125+
# >
126+
# > Not possible yet!
127+
# > Diagnostic strings should be written in UTF-8,
128+
# > the client can translate to the relevant code page if needed.
129+
# > Each translation completely replaces the format string
130+
# > for the diagnostic.
131+
# > -- http://clang.llvm.org/docs/InternalsManual.html#internals-diag-translation
132+
#
133+
# It's not pretty, due to Python 2 & 3 compatibility.
134+
encoding_py3 = {}
135+
if sys.version_info[0] >= 3:
136+
encoding_py3['encoding'] = 'utf-8'
137+
138+
try:
139+
proc = subprocess.Popen(
140+
invocation,
141+
stdout=subprocess.PIPE,
142+
stderr=subprocess.PIPE,
143+
universal_newlines=True,
144+
**encoding_py3)
145+
except OSError as exc:
146+
raise DiffError(
147+
"Command '{}' failed to start: {}".format(
148+
subprocess.list2cmdline(invocation), exc
149+
)
150+
)
151+
proc_stdout = proc.stdout
152+
proc_stderr = proc.stderr
153+
if sys.version_info[0] < 3:
154+
# make the pipes compatible with Python 3,
155+
# reading lines should output unicode
156+
encoding = 'utf-8'
157+
proc_stdout = codecs.getreader(encoding)(proc_stdout)
158+
proc_stderr = codecs.getreader(encoding)(proc_stderr)
159+
# hopefully the stderr pipe won't get full and block the process
160+
outs = list(proc_stdout.readlines())
161+
errs = list(proc_stderr.readlines())
162+
proc.wait()
163+
if proc.returncode:
164+
raise DiffError(
165+
"Command '{}' returned non-zero exit status {}".format(
166+
subprocess.list2cmdline(invocation), proc.returncode
167+
),
168+
errs,
169+
)
170+
return make_diff(file, original, outs), errs
171+
172+
173+
def bold_red(s):
174+
return '\x1b[1m\x1b[31m' + s + '\x1b[0m'
175+
176+
177+
def colorize(diff_lines):
178+
def bold(s):
179+
return '\x1b[1m' + s + '\x1b[0m'
180+
181+
def cyan(s):
182+
return '\x1b[36m' + s + '\x1b[0m'
183+
184+
def green(s):
185+
return '\x1b[32m' + s + '\x1b[0m'
186+
187+
def red(s):
188+
return '\x1b[31m' + s + '\x1b[0m'
189+
190+
for line in diff_lines:
191+
if line[:4] in ['--- ', '+++ ']:
192+
yield bold(line)
193+
elif line.startswith('@@ '):
194+
yield cyan(line)
195+
elif line.startswith('+'):
196+
yield green(line)
197+
elif line.startswith('-'):
198+
yield red(line)
199+
else:
200+
yield line
201+
202+
203+
def print_diff(diff_lines, use_color):
204+
if use_color:
205+
diff_lines = colorize(diff_lines)
206+
if sys.version_info[0] < 3:
207+
sys.stdout.writelines((l.encode('utf-8') for l in diff_lines))
208+
else:
209+
sys.stdout.writelines(diff_lines)
210+
211+
212+
def print_trouble(prog, message, use_colors):
213+
error_text = 'error:'
214+
if use_colors:
215+
error_text = bold_red(error_text)
216+
print("{}: {} {}".format(prog, error_text, message), file=sys.stderr)
217+
218+
219+
def main():
220+
parser = argparse.ArgumentParser(description=__doc__)
221+
parser.add_argument(
222+
'--clang-format-executable',
223+
metavar='EXECUTABLE',
224+
help='path to the clang-format executable',
225+
default='clang-format')
226+
parser.add_argument(
227+
'--extensions',
228+
help='comma separated list of file extensions (default: {})'.format(
229+
DEFAULT_EXTENSIONS),
230+
default=DEFAULT_EXTENSIONS)
231+
parser.add_argument(
232+
'-r',
233+
'--recursive',
234+
action='store_true',
235+
help='run recursively over directories')
236+
parser.add_argument('files', metavar='file', nargs='+')
237+
parser.add_argument(
238+
'-q',
239+
'--quiet',
240+
action='store_true')
241+
parser.add_argument(
242+
'-j',
243+
metavar='N',
244+
type=int,
245+
default=0,
246+
help='run N clang-format jobs in parallel'
247+
' (default number of cpus + 1)')
248+
parser.add_argument(
249+
'--color',
250+
default='auto',
251+
choices=['auto', 'always', 'never'],
252+
help='show colored diff (default: auto)')
253+
parser.add_argument(
254+
'-e',
255+
'--exclude',
256+
metavar='PATTERN',
257+
action='append',
258+
default=[],
259+
help='exclude paths matching the given glob-like pattern(s)'
260+
' from recursive search')
261+
262+
args = parser.parse_args()
263+
264+
# use default signal handling, like diff return SIGINT value on ^C
265+
# https://bugs.python.org/issue14229#msg156446
266+
signal.signal(signal.SIGINT, signal.SIG_DFL)
267+
try:
268+
signal.SIGPIPE
269+
except AttributeError:
270+
# compatibility, SIGPIPE does not exist on Windows
271+
pass
272+
else:
273+
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
274+
275+
colored_stdout = False
276+
colored_stderr = False
277+
if args.color == 'always':
278+
colored_stdout = True
279+
colored_stderr = True
280+
elif args.color == 'auto':
281+
colored_stdout = sys.stdout.isatty()
282+
colored_stderr = sys.stderr.isatty()
283+
284+
version_invocation = [args.clang_format_executable, str("--version")]
285+
try:
286+
subprocess.check_call(version_invocation, stdout=DEVNULL)
287+
except subprocess.CalledProcessError as e:
288+
print_trouble(parser.prog, str(e), use_colors=colored_stderr)
289+
return ExitStatus.TROUBLE
290+
except OSError as e:
291+
print_trouble(
292+
parser.prog,
293+
"Command '{}' failed to start: {}".format(
294+
subprocess.list2cmdline(version_invocation), e
295+
),
296+
use_colors=colored_stderr,
297+
)
298+
return ExitStatus.TROUBLE
299+
300+
retcode = ExitStatus.SUCCESS
301+
files = list_files(
302+
args.files,
303+
recursive=args.recursive,
304+
exclude=args.exclude,
305+
extensions=args.extensions.split(','))
306+
307+
if not files:
308+
return
309+
310+
njobs = args.j
311+
if njobs == 0:
312+
njobs = multiprocessing.cpu_count() + 1
313+
njobs = min(len(files), njobs)
314+
315+
if njobs == 1:
316+
# execute directly instead of in a pool,
317+
# less overhead, simpler stacktraces
318+
it = (run_clang_format_diff_wrapper(args, file) for file in files)
319+
pool = None
320+
else:
321+
pool = multiprocessing.Pool(njobs)
322+
it = pool.imap_unordered(
323+
partial(run_clang_format_diff_wrapper, args), files)
324+
while True:
325+
try:
326+
outs, errs = next(it)
327+
except StopIteration:
328+
break
329+
except DiffError as e:
330+
print_trouble(parser.prog, str(e), use_colors=colored_stderr)
331+
retcode = ExitStatus.TROUBLE
332+
sys.stderr.writelines(e.errs)
333+
except UnexpectedError as e:
334+
print_trouble(parser.prog, str(e), use_colors=colored_stderr)
335+
sys.stderr.write(e.formatted_traceback)
336+
retcode = ExitStatus.TROUBLE
337+
# stop at the first unexpected error,
338+
# something could be very wrong,
339+
# don't process all files unnecessarily
340+
if pool:
341+
pool.terminate()
342+
break
343+
else:
344+
sys.stderr.writelines(errs)
345+
if outs == []:
346+
continue
347+
if not args.quiet:
348+
print_diff(outs, use_color=colored_stdout)
349+
if retcode == ExitStatus.SUCCESS:
350+
retcode = ExitStatus.DIFF
351+
return retcode
352+
353+
354+
if __name__ == '__main__':
355+
sys.exit(main())

0 commit comments

Comments
 (0)