run-clang-format.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. #!/usr/bin/env python
  2. """
  3. MIT License
  4. Copyright (c) 2017 Guillaume Papin
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in all
  12. copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. SOFTWARE.
  20. A wrapper script around clang-format, suitable for linting multiple files
  21. and to use for continuous integration.
  22. This is an alternative API for the clang-format command line.
  23. It runs over multiple files and directories in parallel.
  24. A diff output is produced and a sensible exit code is returned.
  25. """
  26. import argparse
  27. import difflib
  28. import fnmatch
  29. import multiprocessing
  30. import os
  31. import signal
  32. import subprocess
  33. import sys
  34. import traceback
  35. from functools import partial
  36. try:
  37. from subprocess import DEVNULL # py3k
  38. except ImportError:
  39. DEVNULL = open(os.devnull, "wb")
  40. DEFAULT_EXTENSIONS = "c,h,C,H,cpp,hpp,cc,hh,c++,h++,cxx,hxx,cu,mm"
  41. class ExitStatus:
  42. SUCCESS = 0
  43. DIFF = 1
  44. TROUBLE = 2
  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 file in files:
  52. if recursive and os.path.isdir(file):
  53. for dirpath, dnames, fnames in os.walk(file):
  54. fpaths = [os.path.join(dirpath, fname) for fname in fnames]
  55. for pattern in exclude:
  56. # os.walk() supports trimming down the dnames list
  57. # by modifying it in-place,
  58. # to avoid unnecessary directory listings.
  59. dnames[:] = [x for x in dnames if not fnmatch.fnmatch(os.path.join(dirpath, x), pattern)]
  60. fpaths = [x for x in fpaths if not fnmatch.fnmatch(x, pattern)]
  61. for f in fpaths:
  62. ext = os.path.splitext(f)[1][1:]
  63. if ext in extensions:
  64. out.append(f)
  65. else:
  66. out.append(file)
  67. return out
  68. def make_diff(file, original, reformatted):
  69. return list(
  70. difflib.unified_diff(
  71. original, reformatted, fromfile=f"{file}\t(original)", tofile=f"{file}\t(reformatted)", n=3
  72. )
  73. )
  74. class DiffError(Exception):
  75. def __init__(self, message, errs=None):
  76. super().__init__(message)
  77. self.errs = errs or []
  78. class UnexpectedError(Exception):
  79. def __init__(self, message, exc=None):
  80. super().__init__(message)
  81. self.formatted_traceback = traceback.format_exc()
  82. self.exc = exc
  83. def run_clang_format_diff_wrapper(args, file):
  84. try:
  85. ret = run_clang_format_diff(args, file)
  86. return ret
  87. except DiffError:
  88. raise
  89. except Exception as e:
  90. raise UnexpectedError(f"{file}: {e.__class__.__name__}: {e}", e)
  91. def run_clang_format_diff(args, file):
  92. try:
  93. with open(file, encoding="utf-8") as f:
  94. original = f.readlines()
  95. except OSError as exc:
  96. raise DiffError(str(exc))
  97. invocation = [args.clang_format_executable, file]
  98. # Use of utf-8 to decode the process output.
  99. #
  100. # Hopefully, this is the correct thing to do.
  101. #
  102. # It's done due to the following assumptions (which may be incorrect):
  103. # - clang-format will returns the bytes read from the files as-is,
  104. # without conversion, and it is already assumed that the files use utf-8.
  105. # - if the diagnostics were internationalized, they would use utf-8:
  106. # > Adding Translations to Clang
  107. # >
  108. # > Not possible yet!
  109. # > Diagnostic strings should be written in UTF-8,
  110. # > the client can translate to the relevant code page if needed.
  111. # > Each translation completely replaces the format string
  112. # > for the diagnostic.
  113. # > -- http://clang.llvm.org/docs/InternalsManual.html#internals-diag-translation
  114. try:
  115. proc = subprocess.Popen(
  116. invocation, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, encoding="utf-8"
  117. )
  118. except OSError as exc:
  119. raise DiffError(f"Command '{subprocess.list2cmdline(invocation)}' failed to start: {exc}")
  120. proc_stdout = proc.stdout
  121. proc_stderr = proc.stderr
  122. # hopefully the stderr pipe won't get full and block the process
  123. outs = list(proc_stdout.readlines())
  124. errs = list(proc_stderr.readlines())
  125. proc.wait()
  126. if proc.returncode:
  127. raise DiffError(
  128. "Command '{}' returned non-zero exit status {}".format(
  129. subprocess.list2cmdline(invocation), proc.returncode
  130. ),
  131. errs,
  132. )
  133. return make_diff(file, original, outs), errs
  134. def bold_red(s):
  135. return "\x1b[1m\x1b[31m" + s + "\x1b[0m"
  136. def colorize(diff_lines):
  137. def bold(s):
  138. return "\x1b[1m" + s + "\x1b[0m"
  139. def cyan(s):
  140. return "\x1b[36m" + s + "\x1b[0m"
  141. def green(s):
  142. return "\x1b[32m" + s + "\x1b[0m"
  143. def red(s):
  144. return "\x1b[31m" + s + "\x1b[0m"
  145. for line in diff_lines:
  146. if line[:4] in ["--- ", "+++ "]:
  147. yield bold(line)
  148. elif line.startswith("@@ "):
  149. yield cyan(line)
  150. elif line.startswith("+"):
  151. yield green(line)
  152. elif line.startswith("-"):
  153. yield red(line)
  154. else:
  155. yield line
  156. def print_diff(diff_lines, use_color):
  157. if use_color:
  158. diff_lines = colorize(diff_lines)
  159. sys.stdout.writelines(diff_lines)
  160. def print_trouble(prog, message, use_colors):
  161. error_text = "error:"
  162. if use_colors:
  163. error_text = bold_red(error_text)
  164. print(f"{prog}: {error_text} {message}", file=sys.stderr)
  165. def main():
  166. parser = argparse.ArgumentParser(description=__doc__)
  167. parser.add_argument(
  168. "--clang-format-executable",
  169. metavar="EXECUTABLE",
  170. help="path to the clang-format executable",
  171. default="clang-format",
  172. )
  173. parser.add_argument(
  174. "--extensions",
  175. help=f"comma separated list of file extensions (default: {DEFAULT_EXTENSIONS})",
  176. default=DEFAULT_EXTENSIONS,
  177. )
  178. parser.add_argument("-r", "--recursive", action="store_true", help="run recursively over directories")
  179. parser.add_argument("files", metavar="file", nargs="+")
  180. parser.add_argument("-q", "--quiet", action="store_true")
  181. parser.add_argument(
  182. "-j",
  183. metavar="N",
  184. type=int,
  185. default=0,
  186. help="run N clang-format jobs in parallel (default number of cpus + 1)",
  187. )
  188. parser.add_argument(
  189. "--color", default="auto", choices=["auto", "always", "never"], help="show colored diff (default: auto)"
  190. )
  191. parser.add_argument(
  192. "-e",
  193. "--exclude",
  194. metavar="PATTERN",
  195. action="append",
  196. default=[],
  197. help="exclude paths matching the given glob-like pattern(s) from recursive search",
  198. )
  199. args = parser.parse_args()
  200. # use default signal handling, like diff return SIGINT value on ^C
  201. # https://bugs.python.org/issue14229#msg156446
  202. signal.signal(signal.SIGINT, signal.SIG_DFL)
  203. try:
  204. signal.SIGPIPE
  205. except AttributeError:
  206. # compatibility, SIGPIPE does not exist on Windows
  207. pass
  208. else:
  209. signal.signal(signal.SIGPIPE, signal.SIG_DFL)
  210. colored_stdout = False
  211. colored_stderr = False
  212. if args.color == "always":
  213. colored_stdout = True
  214. colored_stderr = True
  215. elif args.color == "auto":
  216. colored_stdout = sys.stdout.isatty()
  217. colored_stderr = sys.stderr.isatty()
  218. version_invocation = [args.clang_format_executable, "--version"]
  219. try:
  220. subprocess.check_call(version_invocation, stdout=DEVNULL)
  221. except subprocess.CalledProcessError as e:
  222. print_trouble(parser.prog, str(e), use_colors=colored_stderr)
  223. return ExitStatus.TROUBLE
  224. except OSError as e:
  225. print_trouble(
  226. parser.prog,
  227. f"Command '{subprocess.list2cmdline(version_invocation)}' failed to start: {e}",
  228. use_colors=colored_stderr,
  229. )
  230. return ExitStatus.TROUBLE
  231. retcode = ExitStatus.SUCCESS
  232. files = list_files(
  233. args.files, recursive=args.recursive, exclude=args.exclude, extensions=args.extensions.split(",")
  234. )
  235. if not files:
  236. return
  237. njobs = args.j
  238. if njobs == 0:
  239. njobs = multiprocessing.cpu_count() + 1
  240. njobs = min(len(files), njobs)
  241. if njobs == 1:
  242. # execute directly instead of in a pool,
  243. # less overhead, simpler stacktraces
  244. it = (run_clang_format_diff_wrapper(args, file) for file in files)
  245. pool = None
  246. else:
  247. pool = multiprocessing.Pool(njobs)
  248. it = pool.imap_unordered(partial(run_clang_format_diff_wrapper, args), files)
  249. while True:
  250. try:
  251. outs, errs = next(it)
  252. except StopIteration:
  253. break
  254. except DiffError as e:
  255. print_trouble(parser.prog, str(e), use_colors=colored_stderr)
  256. retcode = ExitStatus.TROUBLE
  257. sys.stderr.writelines(e.errs)
  258. except UnexpectedError as e:
  259. print_trouble(parser.prog, str(e), use_colors=colored_stderr)
  260. sys.stderr.write(e.formatted_traceback)
  261. retcode = ExitStatus.TROUBLE
  262. # stop at the first unexpected error,
  263. # something could be very wrong,
  264. # don't process all files unnecessarily
  265. if pool:
  266. pool.terminate()
  267. break
  268. else:
  269. sys.stderr.writelines(errs)
  270. if outs == []:
  271. continue
  272. if not args.quiet:
  273. print_diff(outs, use_color=colored_stdout)
  274. if retcode == ExitStatus.SUCCESS:
  275. retcode = ExitStatus.DIFF
  276. return retcode
  277. if __name__ == "__main__":
  278. sys.exit(main())