run-clang-tidy.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. #!/usr/bin/env python2
  2. #
  3. # ===- run-clang-tidy.py - Parallel clang-tidy runner ---------*- python -*--===#
  4. #
  5. # The LLVM Compiler Infrastructure
  6. #
  7. # This file is distributed under the University of Illinois Open Source
  8. # License. See LICENSE.TXT for details.
  9. #
  10. # ===------------------------------------------------------------------------===#
  11. # FIXME: Integrate with clang-tidy-diff.py
  12. """
  13. Parallel clang-tidy runner
  14. ==========================
  15. Runs clang-tidy over all files in a compilation database. Requires clang-tidy
  16. and clang-apply-replacements in $PATH.
  17. Example invocations.
  18. - Run clang-tidy on all files in the current working directory with a default
  19. set of checks and show warnings in the cpp files and all project headers.
  20. run-clang-tidy.py $PWD
  21. - Fix all header guards.
  22. run-clang-tidy.py -fix -checks=-*,llvm-header-guard
  23. - Fix all header guards included from clang-tidy and header guards
  24. for clang-tidy headers.
  25. run-clang-tidy.py -fix -checks=-*,llvm-header-guard extra/clang-tidy \
  26. -header-filter=extra/clang-tidy
  27. Compilation database setup:
  28. http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
  29. """
  30. from __future__ import print_function
  31. import argparse
  32. import json
  33. import multiprocessing
  34. import os
  35. import Queue
  36. import re
  37. import shutil
  38. import subprocess
  39. import sys
  40. import tempfile
  41. import threading
  42. import traceback
  43. class TidyQueue(Queue.Queue):
  44. def __init__(self, max_task):
  45. Queue.Queue.__init__(self, max_task)
  46. self.has_error = False
  47. def find_compilation_database(path):
  48. """Adjusts the directory until a compilation database is found."""
  49. result = './'
  50. while not os.path.isfile(os.path.join(result, path)):
  51. if os.path.realpath(result) == '/':
  52. print('Error: could not find compilation database.')
  53. sys.exit(1)
  54. result += '../'
  55. return os.path.realpath(result)
  56. def get_tidy_invocation(f, clang_tidy_binary, checks, warningsaserrors,
  57. tmpdir, build_path,
  58. header_filter, extra_arg, extra_arg_before, quiet):
  59. """Gets a command line for clang-tidy."""
  60. start = [clang_tidy_binary]
  61. if header_filter is not None:
  62. start.append('-header-filter=' + header_filter)
  63. else:
  64. # Show warnings in all in-project headers by default.
  65. start.append('-header-filter=^' + build_path + '/.*')
  66. if checks:
  67. start.append('-checks=' + checks)
  68. if warningsaserrors:
  69. start.append('-warnings-as-errors=' + warningsaserrors)
  70. if tmpdir is not None:
  71. start.append('-export-fixes')
  72. # Get a temporary file. We immediately close the handle so clang-tidy can
  73. # overwrite it.
  74. (handle, name) = tempfile.mkstemp(suffix='.yaml', dir=tmpdir)
  75. os.close(handle)
  76. start.append(name)
  77. for arg in extra_arg:
  78. start.append('-extra-arg=%s' % arg)
  79. for arg in extra_arg_before:
  80. start.append('-extra-arg-before=%s' % arg)
  81. start.append('-p=' + build_path)
  82. if quiet:
  83. start.append('-quiet')
  84. start.append(f)
  85. return start
  86. def check_clang_apply_replacements_binary(args):
  87. """Checks if invoking supplied clang-apply-replacements binary works."""
  88. try:
  89. subprocess.check_call([args.clang_apply_replacements_binary, '--version'])
  90. except:
  91. print('Unable to run clang-apply-replacements. Is clang-apply-replacements '
  92. 'binary correctly specified?', file=sys.stderr)
  93. traceback.print_exc()
  94. sys.exit(1)
  95. def apply_fixes(args, tmpdir):
  96. """Calls clang-apply-fixes on a given directory. Deletes the dir when done."""
  97. invocation = [args.clang_apply_replacements_binary]
  98. if args.format:
  99. invocation.append('-format')
  100. if args.style:
  101. invocation.append('-style=' + args.style)
  102. invocation.append(tmpdir)
  103. subprocess.call(invocation)
  104. def run_tidy(args, tmpdir, build_path, queue):
  105. """Takes filenames out of queue and runs clang-tidy on them."""
  106. while True:
  107. name = queue.get()
  108. invocation = get_tidy_invocation(name, args.clang_tidy_binary, args.checks,
  109. args.warningsaserrors, tmpdir, build_path,
  110. args.header_filter, args.extra_arg,
  111. args.extra_arg_before, args.quiet)
  112. if not args.no_command_on_stdout:
  113. sys.stdout.write(' '.join(invocation) + '\n')
  114. try:
  115. subprocess.check_call(invocation)
  116. except subprocess.CalledProcessError:
  117. queue.has_error = True
  118. queue.task_done()
  119. def main():
  120. parser = argparse.ArgumentParser(description='Runs clang-tidy over all files '
  121. 'in a compilation database. Requires '
  122. 'clang-tidy and clang-apply-replacements in '
  123. '$PATH.')
  124. parser.add_argument('-clang-tidy-binary', metavar='PATH',
  125. default='clang-tidy',
  126. help='path to clang-tidy binary')
  127. parser.add_argument('-clang-apply-replacements-binary', metavar='PATH',
  128. default='clang-apply-replacements',
  129. help='path to clang-apply-replacements binary')
  130. parser.add_argument('-checks', default=None,
  131. help='checks filter, when not specified, use clang-tidy '
  132. 'default')
  133. parser.add_argument('-warningsaserrors', default=None,
  134. help='warnings-as-errors filter, when not specified, '
  135. 'use clang-tidy default')
  136. parser.add_argument('-header-filter', default=None,
  137. help='regular expression matching the names of the '
  138. 'headers to output diagnostics from. Diagnostics from '
  139. 'the main file of each translation unit are always '
  140. 'displayed.')
  141. parser.add_argument('-j', type=int, default=0,
  142. help='number of tidy instances to be run in parallel.')
  143. parser.add_argument('files', nargs='*', default=['.*'],
  144. help='files to be processed (regex on path)')
  145. parser.add_argument('-fix', action='store_true', help='apply fix-its')
  146. parser.add_argument('-format', action='store_true', help='Reformat code '
  147. 'after applying fixes')
  148. parser.add_argument('-style', default='file', help='The style of reformat '
  149. 'code after applying fixes')
  150. parser.add_argument('-p', dest='build_path',
  151. help='Path used to read a compile command database.')
  152. parser.add_argument('-extra-arg', dest='extra_arg',
  153. action='append', default=[],
  154. help='Additional argument to append to the compiler '
  155. 'command line.')
  156. parser.add_argument('-extra-arg-before', dest='extra_arg_before',
  157. action='append', default=[],
  158. help='Additional argument to prepend to the compiler '
  159. 'command line.')
  160. parser.add_argument('-quiet', action='store_true',
  161. help='Run clang-tidy in quiet mode')
  162. parser.add_argument('-no-command-on-stdout', action='store_true',
  163. help='Run clang-tidy without printing invocation on '
  164. 'stdout')
  165. args = parser.parse_args()
  166. db_path = 'compile_commands.json'
  167. if args.build_path is not None:
  168. build_path = args.build_path
  169. else:
  170. # Find our database
  171. build_path = find_compilation_database(db_path)
  172. try:
  173. invocation = [args.clang_tidy_binary, '-list-checks', '-p=' + build_path]
  174. if args.checks:
  175. invocation.append('-checks=' + args.checks)
  176. if args.warningsaserrors:
  177. invocation.append('-warnings-as-errors=' + args.warningsaserrors)
  178. invocation.append('-')
  179. print(subprocess.check_output(invocation))
  180. except:
  181. print("Unable to run clang-tidy.", file=sys.stderr)
  182. sys.exit(1)
  183. # Load the database and extract all files.
  184. database = json.load(open(os.path.join(build_path, db_path)))
  185. files = [entry['file'] for entry in database]
  186. max_task = args.j
  187. if max_task == 0:
  188. max_task = multiprocessing.cpu_count()
  189. tmpdir = None
  190. if args.fix:
  191. check_clang_apply_replacements_binary(args)
  192. tmpdir = tempfile.mkdtemp()
  193. # Build up a big regexy filter from all command line arguments.
  194. file_name_re = re.compile('|'.join(args.files))
  195. try:
  196. # Spin up a bunch of tidy-launching threads.
  197. queue = TidyQueue(max_task)
  198. for _ in range(max_task):
  199. t = threading.Thread(target=run_tidy,
  200. args=(args, tmpdir, build_path, queue))
  201. t.daemon = True
  202. t.start()
  203. # Fill the queue with files.
  204. for name in files:
  205. if file_name_re.search(name):
  206. queue.put(name)
  207. # Wait for all threads to be done.
  208. queue.join()
  209. # If one clang-tidy process found and error, exit with non-zero
  210. # status
  211. if queue.has_error:
  212. sys.exit(2)
  213. except KeyboardInterrupt:
  214. # This is a sad hack. Unfortunately subprocess goes
  215. # bonkers with ctrl-c and we start forking merrily.
  216. print('\nCtrl-C detected, goodbye.')
  217. if args.fix:
  218. shutil.rmtree(tmpdir)
  219. os.kill(0, 9)
  220. if args.fix:
  221. print('Applying fixes ...')
  222. successfully_applied = False
  223. try:
  224. apply_fixes(args, tmpdir)
  225. successfully_applied = True
  226. except:
  227. print('Error applying fixes.\n', file=sys.stderr)
  228. traceback.print_exc()
  229. shutil.rmtree(tmpdir)
  230. if not successfully_applied:
  231. sys.exit(1)
  232. if __name__ == '__main__':
  233. main()