run-clang-format.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. #!/usr/bin/env python
  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. NOTE: pulled from https://github.com/Sarcasm/run-clang-format, which is
  8. licensed under the MIT license.
  9. """
  10. from __future__ import print_function, unicode_literals
  11. import argparse
  12. import codecs
  13. import difflib
  14. import fnmatch
  15. import io
  16. import multiprocessing
  17. import os
  18. import signal
  19. import subprocess
  20. import sys
  21. import traceback
  22. from functools import partial
  23. try:
  24. from subprocess import DEVNULL # py3k
  25. except ImportError:
  26. DEVNULL = open(os.devnull, "wb")
  27. DEFAULT_EXTENSIONS = 'c,h,C,H,cpp,hpp,cc,hh,c++,h++,cxx,hxx'
  28. class ExitStatus:
  29. SUCCESS = 0
  30. DIFF = 1
  31. TROUBLE = 2
  32. def list_files(files, recursive=False, extensions=None, exclude=None):
  33. if extensions is None:
  34. extensions = []
  35. if exclude is None:
  36. exclude = []
  37. out = []
  38. for file in files:
  39. if recursive and os.path.isdir(file):
  40. for dirpath, dnames, fnames in os.walk(file):
  41. fpaths = [os.path.join(dirpath, fname) for fname in fnames]
  42. for pattern in exclude:
  43. # os.walk() supports trimming down the dnames list
  44. # by modifying it in-place,
  45. # to avoid unnecessary directory listings.
  46. dnames[:] = [
  47. x for x in dnames
  48. if
  49. not fnmatch.fnmatch(os.path.join(dirpath, x), pattern)
  50. ]
  51. fpaths = [
  52. x for x in fpaths if not fnmatch.fnmatch(x, pattern)
  53. ]
  54. for f in fpaths:
  55. ext = os.path.splitext(f)[1][1:]
  56. if ext in extensions:
  57. out.append(f)
  58. else:
  59. out.append(file)
  60. return out
  61. def make_diff(file, original, reformatted):
  62. return list(
  63. difflib.unified_diff(
  64. original,
  65. reformatted,
  66. fromfile='{}\t(original)'.format(file),
  67. tofile='{}\t(reformatted)'.format(file),
  68. n=3))
  69. class DiffError(Exception):
  70. def __init__(self, message, errs=None):
  71. super(DiffError, self).__init__(message)
  72. self.errs = errs or []
  73. class UnexpectedError(Exception):
  74. def __init__(self, message, exc=None):
  75. super(UnexpectedError, self).__init__(message)
  76. self.formatted_traceback = traceback.format_exc()
  77. self.exc = exc
  78. def run_clang_format_diff_wrapper(args, file):
  79. try:
  80. ret = run_clang_format_diff(args, file)
  81. return ret
  82. except DiffError:
  83. raise
  84. except Exception as e:
  85. raise UnexpectedError('{}: {}: {}'.format(file, e.__class__.__name__,
  86. e), e)
  87. def run_clang_format_diff(args, file):
  88. try:
  89. with io.open(file, 'r', encoding='utf-8') as f:
  90. original = f.readlines()
  91. except IOError as exc:
  92. raise DiffError(str(exc))
  93. invocation = [args.clang_format_executable, file]
  94. # Use of utf-8 to decode the process output.
  95. #
  96. # Hopefully, this is the correct thing to do.
  97. #
  98. # It's done due to the following assumptions (which may be incorrect):
  99. # - clang-format will returns the bytes read from the files as-is,
  100. # without conversion, and it is already assumed that the files use utf-8.
  101. # - if the diagnostics were internationalized, they would use utf-8:
  102. # > Adding Translations to Clang
  103. # >
  104. # > Not possible yet!
  105. # > Diagnostic strings should be written in UTF-8,
  106. # > the client can translate to the relevant code page if needed.
  107. # > Each translation completely replaces the format string
  108. # > for the diagnostic.
  109. # > -- http://clang.llvm.org/docs/InternalsManual.html#internals-diag-translation
  110. #
  111. # It's not pretty, due to Python 2 & 3 compatibility.
  112. encoding_py3 = {}
  113. if sys.version_info[0] >= 3:
  114. encoding_py3['encoding'] = 'utf-8'
  115. try:
  116. proc = subprocess.Popen(
  117. invocation,
  118. stdout=subprocess.PIPE,
  119. stderr=subprocess.PIPE,
  120. universal_newlines=True,
  121. **encoding_py3)
  122. except OSError as exc:
  123. raise DiffError(
  124. "Command '{}' failed to start: {}".format(
  125. subprocess.list2cmdline(invocation), exc
  126. )
  127. )
  128. proc_stdout = proc.stdout
  129. proc_stderr = proc.stderr
  130. if sys.version_info[0] < 3:
  131. # make the pipes compatible with Python 3,
  132. # reading lines should output unicode
  133. encoding = 'utf-8'
  134. proc_stdout = codecs.getreader(encoding)(proc_stdout)
  135. proc_stderr = codecs.getreader(encoding)(proc_stderr)
  136. # hopefully the stderr pipe won't get full and block the process
  137. outs = list(proc_stdout.readlines())
  138. errs = list(proc_stderr.readlines())
  139. proc.wait()
  140. if proc.returncode:
  141. raise DiffError(
  142. "Command '{}' returned non-zero exit status {}".format(
  143. subprocess.list2cmdline(invocation), proc.returncode
  144. ),
  145. errs,
  146. )
  147. return make_diff(file, original, outs), errs
  148. def bold_red(s):
  149. return '\x1b[1m\x1b[31m' + s + '\x1b[0m'
  150. def colorize(diff_lines):
  151. def bold(s):
  152. return '\x1b[1m' + s + '\x1b[0m'
  153. def cyan(s):
  154. return '\x1b[36m' + s + '\x1b[0m'
  155. def green(s):
  156. return '\x1b[32m' + s + '\x1b[0m'
  157. def red(s):
  158. return '\x1b[31m' + s + '\x1b[0m'
  159. for line in diff_lines:
  160. if line[:4] in ['--- ', '+++ ']:
  161. yield bold(line)
  162. elif line.startswith('@@ '):
  163. yield cyan(line)
  164. elif line.startswith('+'):
  165. yield green(line)
  166. elif line.startswith('-'):
  167. yield red(line)
  168. else:
  169. yield line
  170. def print_diff(diff_lines, use_color):
  171. if use_color:
  172. diff_lines = colorize(diff_lines)
  173. if sys.version_info[0] < 3:
  174. sys.stdout.writelines((l.encode('utf-8') for l in diff_lines))
  175. else:
  176. sys.stdout.writelines(diff_lines)
  177. def print_trouble(prog, message, use_colors):
  178. error_text = 'error:'
  179. if use_colors:
  180. error_text = bold_red(error_text)
  181. print("{}: {} {}".format(prog, error_text, message), file=sys.stderr)
  182. def main():
  183. parser = argparse.ArgumentParser(description=__doc__)
  184. parser.add_argument(
  185. '--clang-format-executable',
  186. metavar='EXECUTABLE',
  187. help='path to the clang-format executable',
  188. default='clang-format')
  189. parser.add_argument(
  190. '--extensions',
  191. help='comma separated list of file extensions (default: {})'.format(
  192. DEFAULT_EXTENSIONS),
  193. default=DEFAULT_EXTENSIONS)
  194. parser.add_argument(
  195. '-r',
  196. '--recursive',
  197. action='store_true',
  198. help='run recursively over directories')
  199. parser.add_argument('files', metavar='file', nargs='+')
  200. parser.add_argument(
  201. '-q',
  202. '--quiet',
  203. action='store_true')
  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. args = parser.parse_args()
  225. # use default signal handling, like diff return SIGINT value on ^C
  226. # https://bugs.python.org/issue14229#msg156446
  227. signal.signal(signal.SIGINT, signal.SIG_DFL)
  228. try:
  229. signal.SIGPIPE
  230. except AttributeError:
  231. # compatibility, SIGPIPE does not exist on Windows
  232. pass
  233. else:
  234. signal.signal(signal.SIGPIPE, signal.SIG_DFL)
  235. colored_stdout = False
  236. colored_stderr = False
  237. if args.color == 'always':
  238. colored_stdout = True
  239. colored_stderr = True
  240. elif args.color == 'auto':
  241. colored_stdout = sys.stdout.isatty()
  242. colored_stderr = sys.stderr.isatty()
  243. version_invocation = [args.clang_format_executable, str("--version")]
  244. try:
  245. subprocess.check_call(version_invocation, stdout=DEVNULL)
  246. except subprocess.CalledProcessError as e:
  247. print_trouble(parser.prog, str(e), use_colors=colored_stderr)
  248. return ExitStatus.TROUBLE
  249. except OSError as e:
  250. print_trouble(
  251. parser.prog,
  252. "Command '{}' failed to start: {}".format(
  253. subprocess.list2cmdline(version_invocation), e
  254. ),
  255. use_colors=colored_stderr,
  256. )
  257. return ExitStatus.TROUBLE
  258. retcode = ExitStatus.SUCCESS
  259. files = list_files(
  260. args.files,
  261. recursive=args.recursive,
  262. exclude=args.exclude,
  263. extensions=args.extensions.split(','))
  264. if not files:
  265. return
  266. njobs = args.j
  267. if njobs == 0:
  268. njobs = multiprocessing.cpu_count() + 1
  269. njobs = min(len(files), njobs)
  270. if njobs == 1:
  271. # execute directly instead of in a pool,
  272. # less overhead, simpler stacktraces
  273. it = (run_clang_format_diff_wrapper(args, file) for file in files)
  274. pool = None
  275. else:
  276. pool = multiprocessing.Pool(njobs)
  277. it = pool.imap_unordered(
  278. partial(run_clang_format_diff_wrapper, args), files)
  279. while True:
  280. try:
  281. outs, errs = next(it)
  282. except StopIteration:
  283. break
  284. except DiffError as e:
  285. print_trouble(parser.prog, str(e), use_colors=colored_stderr)
  286. retcode = ExitStatus.TROUBLE
  287. sys.stderr.writelines(e.errs)
  288. except UnexpectedError as e:
  289. print_trouble(parser.prog, str(e), use_colors=colored_stderr)
  290. sys.stderr.write(e.formatted_traceback)
  291. retcode = ExitStatus.TROUBLE
  292. # stop at the first unexpected error,
  293. # something could be very wrong,
  294. # don't process all files unnecessarily
  295. if pool:
  296. pool.terminate()
  297. break
  298. else:
  299. sys.stderr.writelines(errs)
  300. if outs == []:
  301. continue
  302. if not args.quiet:
  303. print_diff(outs, use_color=colored_stdout)
  304. if retcode == ExitStatus.SUCCESS:
  305. retcode = ExitStatus.DIFF
  306. return retcode
  307. if __name__ == '__main__':
  308. sys.exit(main())