run-clang-format.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. """
  8. from __future__ import print_function, unicode_literals
  9. import argparse
  10. import codecs
  11. import difflib
  12. import fnmatch
  13. import io
  14. import errno
  15. import multiprocessing
  16. import os
  17. import signal
  18. import subprocess
  19. import sys
  20. import traceback
  21. import platform
  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. DEFAULT_CLANG_FORMAT_IGNORE = ".clang-format-ignore"
  29. class ExitStatus:
  30. SUCCESS = 0
  31. DIFF = 1
  32. TROUBLE = 2
  33. def excludes_from_file(ignore_file):
  34. excludes = []
  35. try:
  36. with io.open(ignore_file, "r", encoding="utf-8") as f:
  37. for line in f:
  38. if line.startswith("#"):
  39. # ignore comments
  40. continue
  41. pattern = line.rstrip()
  42. if not pattern:
  43. # allow empty lines
  44. continue
  45. excludes.append(pattern)
  46. except EnvironmentError as e:
  47. if e.errno != errno.ENOENT:
  48. raise
  49. return excludes
  50. def list_files(files, recursive=False, extensions=None, exclude=None):
  51. if extensions is None:
  52. extensions = []
  53. if exclude is None:
  54. exclude = []
  55. out = []
  56. for file in files:
  57. if recursive and os.path.isdir(file):
  58. for dirpath, dnames, fnames in os.walk(file):
  59. fpaths = [
  60. os.path.relpath(os.path.join(dirpath, fname), os.getcwd())
  61. for fname in fnames
  62. ]
  63. for pattern in exclude:
  64. # os.walk() supports trimming down the dnames list
  65. # by modifying it in-place,
  66. # to avoid unnecessary directory listings.
  67. dnames[:] = [
  68. x
  69. for x in dnames
  70. if not fnmatch.fnmatch(os.path.join(dirpath, x), pattern)
  71. ]
  72. fpaths = [x for x in fpaths if not fnmatch.fnmatch(x, pattern)]
  73. for f in fpaths:
  74. ext = os.path.splitext(f)[1][1:]
  75. if ext in extensions:
  76. out.append(f)
  77. else:
  78. out.append(file)
  79. return out
  80. def make_diff(file, original, reformatted):
  81. return list(
  82. difflib.unified_diff(
  83. original,
  84. reformatted,
  85. fromfile="{}\t(original)".format(file),
  86. tofile="{}\t(reformatted)".format(file),
  87. n=3,
  88. )
  89. )
  90. class DiffError(Exception):
  91. def __init__(self, message, errs=None):
  92. super(DiffError, self).__init__(message)
  93. self.errs = errs or []
  94. class UnexpectedError(Exception):
  95. def __init__(self, message, exc=None):
  96. super(UnexpectedError, self).__init__(message)
  97. self.formatted_traceback = traceback.format_exc()
  98. self.exc = exc
  99. def run_clang_format_diff_wrapper(args, file):
  100. try:
  101. ret = run_clang_format_diff(args, file)
  102. return ret
  103. except DiffError:
  104. raise
  105. except Exception as e:
  106. raise UnexpectedError("{}: {}: {}".format(file, e.__class__.__name__, e), e)
  107. def run_clang_format_diff(args, file):
  108. # try:
  109. # with io.open(file, "r", encoding="utf-8") as f:
  110. # original = f.readlines()
  111. # except IOError as exc:
  112. # raise DiffError(str(exc))
  113. if args.in_place:
  114. invocation = [args.clang_format_executable, "-i", file]
  115. else:
  116. invocation = [args.clang_format_executable, file]
  117. if args.style:
  118. invocation.extend(["--style", args.style])
  119. if args.dry_run:
  120. print(" ".join(invocation))
  121. return [], []
  122. # Use of utf-8 to decode the process output.
  123. #
  124. # Hopefully, this is the correct thing to do.
  125. #
  126. # It's done due to the following assumptions (which may be incorrect):
  127. # - clang-format will returns the bytes read from the files as-is,
  128. # without conversion, and it is already assumed that the files use utf-8.
  129. # - if the diagnostics were internationalized, they would use utf-8:
  130. # > Adding Translations to Clang
  131. # >
  132. # > Not possible yet!
  133. # > Diagnostic strings should be written in UTF-8,
  134. # > the client can translate to the relevant code page if needed.
  135. # > Each translation completely replaces the format string
  136. # > for the diagnostic.
  137. # > -- http://clang.llvm.org/docs/InternalsManual.html#internals-diag-translation
  138. #
  139. # It's not pretty, due to Python 2 & 3 compatibility.
  140. encoding_py3 = {}
  141. if sys.version_info[0] >= 3:
  142. encoding_py3["encoding"] = "utf-8"
  143. try:
  144. proc = subprocess.Popen(
  145. invocation,
  146. stdout=subprocess.PIPE,
  147. stderr=subprocess.PIPE,
  148. universal_newlines=True,
  149. **encoding_py3
  150. )
  151. except OSError as exc:
  152. raise DiffError(
  153. "Command '{}' failed to start: {}".format(
  154. subprocess.list2cmdline(invocation), exc
  155. )
  156. )
  157. proc_stdout = proc.stdout
  158. proc_stderr = proc.stderr
  159. if sys.version_info[0] < 3:
  160. # make the pipes compatible with Python 3,
  161. # reading lines should output unicode
  162. encoding = "utf-8"
  163. proc_stdout = codecs.getreader(encoding)(proc_stdout)
  164. proc_stderr = codecs.getreader(encoding)(proc_stderr)
  165. # hopefully the stderr pipe won't get full and block the process
  166. outs = list(proc_stdout.readlines())
  167. errs = list(proc_stderr.readlines())
  168. proc.wait()
  169. if proc.returncode:
  170. raise DiffError(
  171. "Command '{}' returned non-zero exit status {}".format(
  172. subprocess.list2cmdline(invocation), proc.returncode
  173. ),
  174. errs,
  175. )
  176. if args.in_place:
  177. return [], errs
  178. return make_diff(file, original, outs), errs
  179. def bold_red(s):
  180. return "\x1b[1m\x1b[31m" + s + "\x1b[0m"
  181. def colorize(diff_lines):
  182. def bold(s):
  183. return "\x1b[1m" + s + "\x1b[0m"
  184. def cyan(s):
  185. return "\x1b[36m" + s + "\x1b[0m"
  186. def green(s):
  187. return "\x1b[32m" + s + "\x1b[0m"
  188. def red(s):
  189. return "\x1b[31m" + s + "\x1b[0m"
  190. for line in diff_lines:
  191. if line[:4] in ["--- ", "+++ "]:
  192. yield bold(line)
  193. elif line.startswith("@@ "):
  194. yield cyan(line)
  195. elif line.startswith("+"):
  196. yield green(line)
  197. elif line.startswith("-"):
  198. yield red(line)
  199. else:
  200. yield line
  201. def print_diff(diff_lines, use_color):
  202. if use_color:
  203. diff_lines = colorize(diff_lines)
  204. if sys.version_info[0] < 3:
  205. sys.stdout.writelines((l.encode("utf-8") for l in diff_lines))
  206. else:
  207. sys.stdout.writelines(diff_lines)
  208. def print_trouble(prog, message, use_colors):
  209. error_text = "error:"
  210. if use_colors:
  211. error_text = bold_red(error_text)
  212. print("{}: {} {}".format(prog, error_text, message), file=sys.stderr)
  213. def main():
  214. parser = argparse.ArgumentParser(description=__doc__)
  215. parser.add_argument(
  216. "--clang-format-executable",
  217. metavar="EXECUTABLE",
  218. help="path to the clang-format executable",
  219. default="clang-format",
  220. )
  221. parser.add_argument(
  222. "--extensions",
  223. help="comma separated list of file extensions (default: {})".format(
  224. DEFAULT_EXTENSIONS
  225. ),
  226. default=DEFAULT_EXTENSIONS,
  227. )
  228. parser.add_argument(
  229. "-r",
  230. "--recursive",
  231. action="store_true",
  232. help="run recursively over directories",
  233. )
  234. parser.add_argument(
  235. "-d", "--dry-run", action="store_true", help="just print the list of files"
  236. )
  237. parser.add_argument(
  238. "-i",
  239. "--in-place",
  240. action="store_true",
  241. help="format file instead of printing differences",
  242. )
  243. parser.add_argument("files", metavar="file", nargs="+")
  244. parser.add_argument(
  245. "-q",
  246. "--quiet",
  247. action="store_true",
  248. help="disable output, useful for the exit code",
  249. )
  250. parser.add_argument(
  251. "-j",
  252. metavar="N",
  253. type=int,
  254. default=0,
  255. help="run N clang-format jobs in parallel" " (default number of cpus + 1)",
  256. )
  257. parser.add_argument(
  258. "--color",
  259. default="auto",
  260. choices=["auto", "always", "never"],
  261. help="show colored diff (default: auto)",
  262. )
  263. parser.add_argument(
  264. "-e",
  265. "--exclude",
  266. metavar="PATTERN",
  267. action="append",
  268. default=[],
  269. help="exclude paths matching the given glob-like pattern(s)"
  270. " from recursive search",
  271. )
  272. parser.add_argument(
  273. "--style",
  274. default="file",
  275. help="formatting style to apply (LLVM, Google, Chromium, Mozilla, WebKit)",
  276. )
  277. args = parser.parse_args()
  278. # use default signal handling, like diff return SIGINT value on ^C
  279. # https://bugs.python.org/issue14229#msg156446
  280. signal.signal(signal.SIGINT, signal.SIG_DFL)
  281. try:
  282. signal.SIGPIPE
  283. except AttributeError:
  284. # compatibility, SIGPIPE does not exist on Windows
  285. pass
  286. else:
  287. signal.signal(signal.SIGPIPE, signal.SIG_DFL)
  288. colored_stdout = False
  289. colored_stderr = False
  290. if args.color == "always":
  291. colored_stdout = True
  292. colored_stderr = True
  293. elif args.color == "auto":
  294. colored_stdout = sys.stdout.isatty()
  295. colored_stderr = sys.stderr.isatty()
  296. version_invocation = [args.clang_format_executable, str("--version")]
  297. try:
  298. subprocess.check_call(version_invocation, stdout=DEVNULL)
  299. except subprocess.CalledProcessError as e:
  300. print_trouble(parser.prog, str(e), use_colors=colored_stderr)
  301. return ExitStatus.TROUBLE
  302. except OSError as e:
  303. print_trouble(
  304. parser.prog,
  305. "Command '{}' failed to start: {}".format(
  306. subprocess.list2cmdline(version_invocation), e
  307. ),
  308. use_colors=colored_stderr,
  309. )
  310. return ExitStatus.TROUBLE
  311. retcode = ExitStatus.SUCCESS
  312. if os.path.exists(DEFAULT_CLANG_FORMAT_IGNORE):
  313. excludes = excludes_from_file(DEFAULT_CLANG_FORMAT_IGNORE)
  314. else:
  315. excludes = []
  316. excludes.extend(args.exclude)
  317. files = list_files(
  318. args.files,
  319. recursive=args.recursive,
  320. exclude=excludes,
  321. extensions=args.extensions.split(","),
  322. )
  323. if not files:
  324. return
  325. njobs = args.j
  326. if njobs == 0:
  327. njobs = multiprocessing.cpu_count() + 1
  328. njobs = min(len(files), njobs)
  329. if njobs == 1:
  330. # execute directly instead of in a pool,
  331. # less overhead, simpler stacktraces
  332. it = (run_clang_format_diff_wrapper(args, file) for file in files)
  333. pool = None
  334. else:
  335. pool = multiprocessing.Pool(njobs)
  336. it = pool.imap_unordered(partial(run_clang_format_diff_wrapper, args), files)
  337. pool.close()
  338. while True:
  339. try:
  340. outs, errs = next(it)
  341. except StopIteration:
  342. break
  343. except DiffError as e:
  344. print_trouble(parser.prog, str(e), use_colors=colored_stderr)
  345. retcode = ExitStatus.TROUBLE
  346. sys.stderr.writelines(e.errs)
  347. except UnexpectedError as e:
  348. print_trouble(parser.prog, str(e), use_colors=colored_stderr)
  349. sys.stderr.write(e.formatted_traceback)
  350. retcode = ExitStatus.TROUBLE
  351. # stop at the first unexpected error,
  352. # something could be very wrong,
  353. # don't process all files unnecessarily
  354. if pool:
  355. pool.terminate()
  356. break
  357. else:
  358. sys.stderr.writelines(errs)
  359. if outs == []:
  360. continue
  361. if not args.quiet:
  362. print_diff(outs, use_color=colored_stdout)
  363. if retcode == ExitStatus.SUCCESS:
  364. retcode = ExitStatus.DIFF
  365. if pool:
  366. pool.join()
  367. return retcode
  368. if __name__ == "__main__":
  369. sys.exit(main())