run-clang-format.py 11 KB

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