run-clang-format.py 11 KB

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