run-clang-format.py 11 KB

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