run-clang-format.py 10 KB

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