run-clang-format.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. if args.fix:
  90. invocation.append('-i')
  91. try:
  92. proc = subprocess.Popen(
  93. ' '.join(invocation),
  94. stdout=subprocess.PIPE,
  95. stderr=subprocess.PIPE,
  96. universal_newlines=True,
  97. shell=True)
  98. except OSError as exc:
  99. raise DiffError(str(exc))
  100. proc_stdout = proc.stdout
  101. proc_stderr = proc.stderr
  102. if sys.version_info[0] < 3:
  103. # make the pipes compatible with Python 3,
  104. # reading lines should output unicode
  105. encoding = 'utf-8'
  106. proc_stdout = codecs.getreader(encoding)(proc_stdout)
  107. proc_stderr = codecs.getreader(encoding)(proc_stderr)
  108. # hopefully the stderr pipe won't get full and block the process
  109. outs = list(proc_stdout.readlines())
  110. errs = list(proc_stderr.readlines())
  111. proc.wait()
  112. if proc.returncode:
  113. raise DiffError("clang-format exited with status {}: '{}'".format(
  114. proc.returncode, file_name), errs)
  115. if args.fix:
  116. return None, errs
  117. return make_diff(file_name, original, outs), errs
  118. def bold_red(s):
  119. return '\x1b[1m\x1b[31m' + s + '\x1b[0m'
  120. def colorize(diff_lines):
  121. def bold(s):
  122. return '\x1b[1m' + s + '\x1b[0m'
  123. def cyan(s):
  124. return '\x1b[36m' + s + '\x1b[0m'
  125. def green(s):
  126. return '\x1b[32m' + s + '\x1b[0m'
  127. def red(s):
  128. return '\x1b[31m' + s + '\x1b[0m'
  129. for line in diff_lines:
  130. if line[:4] in ['--- ', '+++ ']:
  131. yield bold(line)
  132. elif line.startswith('@@ '):
  133. yield cyan(line)
  134. elif line.startswith('+'):
  135. yield green(line)
  136. elif line.startswith('-'):
  137. yield red(line)
  138. else:
  139. yield line
  140. def print_diff(diff_lines, use_color):
  141. if use_color:
  142. diff_lines = colorize(diff_lines)
  143. if sys.version_info[0] < 3:
  144. sys.stdout.writelines((l.encode('utf-8') for l in diff_lines))
  145. else:
  146. sys.stdout.writelines(diff_lines)
  147. def print_trouble(prog, message, use_colors):
  148. error_text = 'error:'
  149. if use_colors:
  150. error_text = bold_red(error_text)
  151. print("{}: {} {}".format(prog, error_text, message), file=sys.stderr)
  152. def main():
  153. parser = argparse.ArgumentParser(description=__doc__)
  154. parser.add_argument(
  155. '--clang-format-executable',
  156. metavar='EXECUTABLE',
  157. help='path to the clang-format executable',
  158. default='clang-format')
  159. parser.add_argument(
  160. '--extensions',
  161. help='comma separated list of file extensions (default: {})'.format(
  162. DEFAULT_EXTENSIONS),
  163. default=DEFAULT_EXTENSIONS)
  164. parser.add_argument(
  165. '--fix',
  166. help='if specified, reformat files in-place',
  167. action='store_true')
  168. parser.add_argument(
  169. '-r',
  170. '--recursive',
  171. action='store_true',
  172. help='run recursively over directories')
  173. parser.add_argument('files', metavar='file', nargs='+')
  174. parser.add_argument(
  175. '-q',
  176. '--quiet',
  177. action='store_true')
  178. parser.add_argument(
  179. '-c',
  180. '--changed',
  181. action='store_true',
  182. help='only run on changed files')
  183. parser.add_argument(
  184. '-j',
  185. metavar='N',
  186. type=int,
  187. default=0,
  188. help='run N clang-format jobs in parallel'
  189. ' (default number of cpus + 1)')
  190. parser.add_argument(
  191. '--color',
  192. default='auto',
  193. choices=['auto', 'always', 'never'],
  194. help='show colored diff (default: auto)')
  195. parser.add_argument(
  196. '-e',
  197. '--exclude',
  198. metavar='PATTERN',
  199. action='append',
  200. default=[],
  201. help='exclude paths matching the given glob-like pattern(s)'
  202. ' from recursive search')
  203. args = parser.parse_args()
  204. # use default signal handling, like diff return SIGINT value on ^C
  205. # https://bugs.python.org/issue14229#msg156446
  206. signal.signal(signal.SIGINT, signal.SIG_DFL)
  207. try:
  208. signal.SIGPIPE
  209. except AttributeError:
  210. # compatibility, SIGPIPE does not exist on Windows
  211. pass
  212. else:
  213. signal.signal(signal.SIGPIPE, signal.SIG_DFL)
  214. colored_stdout = False
  215. colored_stderr = False
  216. if args.color == 'always':
  217. colored_stdout = True
  218. colored_stderr = True
  219. elif args.color == 'auto':
  220. colored_stdout = sys.stdout.isatty()
  221. colored_stderr = sys.stderr.isatty()
  222. retcode = ExitStatus.SUCCESS
  223. parse_files = []
  224. if args.changed:
  225. popen = subprocess.Popen(
  226. 'git diff --name-only --cached',
  227. stdout=subprocess.PIPE,
  228. stderr=subprocess.STDOUT,
  229. shell=True
  230. )
  231. for line in popen.stdout:
  232. file_name = line.rstrip()
  233. # don't check deleted files
  234. if os.path.isfile(file_name):
  235. parse_files.append(file_name)
  236. else:
  237. parse_files = args.files
  238. files = list_files(
  239. parse_files,
  240. recursive=args.recursive,
  241. exclude=args.exclude,
  242. extensions=args.extensions.split(','))
  243. if not files:
  244. return
  245. njobs = args.j
  246. if njobs == 0:
  247. njobs = multiprocessing.cpu_count() + 1
  248. njobs = min(len(files), njobs)
  249. if not args.fix:
  250. patch_file = tempfile.NamedTemporaryFile(delete=False,
  251. prefix='electron-format-')
  252. if njobs == 1:
  253. # execute directly instead of in a pool,
  254. # less overhead, simpler stacktraces
  255. it = (run_clang_format_diff_wrapper(args, file) for file in files)
  256. pool = None
  257. else:
  258. pool = multiprocessing.Pool(njobs)
  259. it = pool.imap_unordered(
  260. partial(run_clang_format_diff_wrapper, args), files)
  261. while True:
  262. try:
  263. outs, errs = next(it)
  264. except StopIteration:
  265. break
  266. except DiffError as e:
  267. print_trouble(parser.prog, str(e), use_colors=colored_stderr)
  268. retcode = ExitStatus.TROUBLE
  269. sys.stderr.writelines(e.errs)
  270. except UnexpectedError as e:
  271. print_trouble(parser.prog, str(e), use_colors=colored_stderr)
  272. sys.stderr.write(e.formatted_traceback)
  273. retcode = ExitStatus.TROUBLE
  274. # stop at the first unexpected error,
  275. # something could be very wrong,
  276. # don't process all files unnecessarily
  277. if pool:
  278. pool.terminate()
  279. break
  280. else:
  281. sys.stderr.writelines(errs)
  282. if outs == []:
  283. continue
  284. if not args.fix:
  285. if not args.quiet:
  286. print_diff(outs, use_color=colored_stdout)
  287. for line in outs:
  288. patch_file.write(line)
  289. patch_file.write('\n')
  290. if retcode == ExitStatus.SUCCESS:
  291. retcode = ExitStatus.DIFF
  292. if not args.fix:
  293. if patch_file.tell() == 0:
  294. patch_file.close()
  295. os.unlink(patch_file.name)
  296. else:
  297. print("\nTo patch these files, run:\n$ git apply {}\n"
  298. .format(patch_file.name))
  299. return retcode
  300. if __name__ == '__main__':
  301. sys.exit(main())