run-clang-format.py 11 KB

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