run-clang-format.py 11 KB

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