run-clang-format.py 9.7 KB

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