run-clang-format.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. This is an alternative API for the clang-format command line.
  5. It runs over multiple files and directories in parallel.
  6. A diff output is produced and a sensible exit code is returned.
  7. """
  8. from __future__ import print_function, unicode_literals
  9. import argparse
  10. import codecs
  11. import difflib
  12. import fnmatch
  13. import io
  14. import multiprocessing
  15. import os
  16. import signal
  17. import subprocess
  18. import sys
  19. import traceback
  20. from functools import partial
  21. DEFAULT_EXTENSIONS = 'c,h,C,H,cpp,hpp,cc,hh,c++,h++,cxx,hxx,mm'
  22. class ExitStatus:
  23. SUCCESS = 0
  24. DIFF = 1
  25. TROUBLE = 2
  26. def list_files(files, recursive=False, extensions=None, exclude=None):
  27. if extensions is None:
  28. extensions = []
  29. if exclude is None:
  30. exclude = []
  31. out = []
  32. for f in files:
  33. if recursive and os.path.isdir(f):
  34. for dirpath, dnames, fnames in os.walk(f):
  35. fpaths = [os.path.join(dirpath, fname) for fname in fnames]
  36. for pattern in exclude:
  37. dnames[:] = [
  38. x for x in dnames
  39. if
  40. not fnmatch.fnmatch(os.path.join(dirpath, x), pattern)
  41. ]
  42. fpaths = [
  43. x for x in fpaths if not fnmatch.fnmatch(x, pattern)
  44. ]
  45. for fp in fpaths:
  46. ext = os.path.splitext(f)[1][1:]
  47. print(ext)
  48. if ext in extensions:
  49. out.append(fp)
  50. else:
  51. ext = os.path.splitext(f)[1][1:]
  52. if ext in extensions:
  53. out.append(f)
  54. return out
  55. def make_diff(diff_file, original, reformatted):
  56. return list(
  57. difflib.unified_diff(
  58. original,
  59. reformatted,
  60. fromfile='{}\t(original)'.format(diff_file),
  61. tofile='{}\t(reformatted)'.format(diff_file),
  62. n=3))
  63. class DiffError(Exception):
  64. def __init__(self, message, errs=None):
  65. super(DiffError, self).__init__(message)
  66. self.errs = errs or []
  67. class UnexpectedError(Exception):
  68. def __init__(self, message, exc=None):
  69. super(UnexpectedError, self).__init__(message)
  70. self.formatted_traceback = traceback.format_exc()
  71. self.exc = exc
  72. def run_clang_format_diff_wrapper(args, file_name):
  73. try:
  74. ret = run_clang_format_diff(args, file_name)
  75. return ret
  76. except DiffError:
  77. raise
  78. except Exception as e:
  79. raise UnexpectedError('{}: {}: {}'.format(
  80. file_name, e.__class__.__name__, e), e)
  81. def run_clang_format_diff(args, file_name):
  82. try:
  83. with io.open(file_name, 'r', encoding='utf-8') as f:
  84. original = f.readlines()
  85. except IOError as exc:
  86. raise DiffError(str(exc))
  87. invocation = [args.clang_format_executable, file_name]
  88. try:
  89. proc = subprocess.Popen(
  90. invocation,
  91. stdout=subprocess.PIPE,
  92. stderr=subprocess.PIPE,
  93. universal_newlines=True)
  94. except OSError as exc:
  95. raise DiffError(str(exc))
  96. proc_stdout = proc.stdout
  97. proc_stderr = proc.stderr
  98. if sys.version_info[0] < 3:
  99. # make the pipes compatible with Python 3,
  100. # reading lines should output unicode
  101. encoding = 'utf-8'
  102. proc_stdout = codecs.getreader(encoding)(proc_stdout)
  103. proc_stderr = codecs.getreader(encoding)(proc_stderr)
  104. # hopefully the stderr pipe won't get full and block the process
  105. outs = list(proc_stdout.readlines())
  106. errs = list(proc_stderr.readlines())
  107. proc.wait()
  108. if proc.returncode:
  109. raise DiffError("clang-format exited with status {}: '{}'".format(
  110. proc.returncode, file_name), errs)
  111. return make_diff(file_name, original, outs), errs
  112. def bold_red(s):
  113. return '\x1b[1m\x1b[31m' + s + '\x1b[0m'
  114. def colorize(diff_lines):
  115. def bold(s):
  116. return '\x1b[1m' + s + '\x1b[0m'
  117. def cyan(s):
  118. return '\x1b[36m' + s + '\x1b[0m'
  119. def green(s):
  120. return '\x1b[32m' + s + '\x1b[0m'
  121. def red(s):
  122. return '\x1b[31m' + s + '\x1b[0m'
  123. for line in diff_lines:
  124. if line[:4] in ['--- ', '+++ ']:
  125. yield bold(line)
  126. elif line.startswith('@@ '):
  127. yield cyan(line)
  128. elif line.startswith('+'):
  129. yield green(line)
  130. elif line.startswith('-'):
  131. yield red(line)
  132. else:
  133. yield line
  134. def print_diff(diff_lines, use_color):
  135. if use_color:
  136. diff_lines = colorize(diff_lines)
  137. if sys.version_info[0] < 3:
  138. sys.stdout.writelines((l.encode('utf-8') for l in diff_lines))
  139. else:
  140. sys.stdout.writelines(diff_lines)
  141. def print_trouble(prog, message, use_colors):
  142. error_text = 'error:'
  143. if use_colors:
  144. error_text = bold_red(error_text)
  145. print("{}: {} {}".format(prog, error_text, message), file=sys.stderr)
  146. def main():
  147. parser = argparse.ArgumentParser(description=__doc__)
  148. parser.add_argument(
  149. '--clang-format-executable',
  150. metavar='EXECUTABLE',
  151. help='path to the clang-format executable',
  152. default='clang-format')
  153. parser.add_argument(
  154. '--extensions',
  155. help='comma separated list of file extensions (default: {})'.format(
  156. DEFAULT_EXTENSIONS),
  157. default=DEFAULT_EXTENSIONS)
  158. parser.add_argument(
  159. '-r',
  160. '--recursive',
  161. action='store_true',
  162. help='run recursively over directories')
  163. parser.add_argument('files', metavar='file', nargs='+')
  164. parser.add_argument(
  165. '-q',
  166. '--quiet',
  167. action='store_true')
  168. parser.add_argument(
  169. '-c',
  170. '--changed',
  171. action='store_true',
  172. help='only run on changed files')
  173. parser.add_argument(
  174. '-j',
  175. metavar='N',
  176. type=int,
  177. default=0,
  178. help='run N clang-format jobs in parallel'
  179. ' (default number of cpus + 1)')
  180. parser.add_argument(
  181. '--color',
  182. default='auto',
  183. choices=['auto', 'always', 'never'],
  184. help='show colored diff (default: auto)')
  185. parser.add_argument(
  186. '-e',
  187. '--exclude',
  188. metavar='PATTERN',
  189. action='append',
  190. default=[],
  191. help='exclude paths matching the given glob-like pattern(s)'
  192. ' from recursive search')
  193. args = parser.parse_args()
  194. # use default signal handling, like diff return SIGINT value on ^C
  195. # https://bugs.python.org/issue14229#msg156446
  196. signal.signal(signal.SIGINT, signal.SIG_DFL)
  197. try:
  198. signal.SIGPIPE
  199. except AttributeError:
  200. # compatibility, SIGPIPE does not exist on Windows
  201. pass
  202. else:
  203. signal.signal(signal.SIGPIPE, signal.SIG_DFL)
  204. colored_stdout = False
  205. colored_stderr = False
  206. if args.color == 'always':
  207. colored_stdout = True
  208. colored_stderr = True
  209. elif args.color == 'auto':
  210. colored_stdout = sys.stdout.isatty()
  211. colored_stderr = sys.stderr.isatty()
  212. retcode = ExitStatus.SUCCESS
  213. parse_files = []
  214. if args.changed:
  215. popen = subprocess.Popen(
  216. ["git", "diff", "--name-only", "--cached"],
  217. stdout=subprocess.PIPE,
  218. stderr=subprocess.STDOUT
  219. )
  220. for line in popen.stdout:
  221. file_name = line.rstrip()
  222. # don't check deleted files
  223. if os.path.isfile(file_name):
  224. parse_files.append(file_name)
  225. else:
  226. parse_files = args.files
  227. files = list_files(
  228. parse_files,
  229. recursive=args.recursive,
  230. exclude=args.exclude,
  231. extensions=args.extensions.split(','))
  232. if not files:
  233. return
  234. njobs = args.j
  235. if njobs == 0:
  236. njobs = multiprocessing.cpu_count() + 1
  237. njobs = min(len(files), njobs)
  238. if njobs == 1:
  239. # execute directly instead of in a pool,
  240. # less overhead, simpler stacktraces
  241. it = (run_clang_format_diff_wrapper(args, file) for file in files)
  242. pool = None
  243. else:
  244. pool = multiprocessing.Pool(njobs)
  245. it = pool.imap_unordered(
  246. partial(run_clang_format_diff_wrapper, args), files)
  247. while True:
  248. try:
  249. outs, errs = next(it)
  250. except StopIteration:
  251. break
  252. except DiffError as e:
  253. print_trouble(parser.prog, str(e), use_colors=colored_stderr)
  254. retcode = ExitStatus.TROUBLE
  255. sys.stderr.writelines(e.errs)
  256. except UnexpectedError as e:
  257. print_trouble(parser.prog, str(e), use_colors=colored_stderr)
  258. sys.stderr.write(e.formatted_traceback)
  259. retcode = ExitStatus.TROUBLE
  260. # stop at the first unexpected error,
  261. # something could be very wrong,
  262. # don't process all files unnecessarily
  263. if pool:
  264. pool.terminate()
  265. break
  266. else:
  267. sys.stderr.writelines(errs)
  268. if outs == []:
  269. continue
  270. if not args.quiet:
  271. print_diff(outs, use_color=colored_stdout)
  272. if retcode == ExitStatus.SUCCESS:
  273. retcode = ExitStatus.DIFF
  274. return retcode
  275. if __name__ == '__main__':
  276. sys.exit(main())