run-clang-format.py 10 KB

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