run-clang-format.py 10 KB

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