run-clang-tidy.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. #!/usr/bin/env python
  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 glob
  33. import json
  34. import multiprocessing
  35. import os
  36. import re
  37. import shutil
  38. import subprocess
  39. import sys
  40. import tempfile
  41. import threading
  42. import traceback
  43. import yaml
  44. is_py2 = sys.version[0] == '2'
  45. if is_py2:
  46. import Queue as queue
  47. else:
  48. import queue as queue
  49. def find_compilation_database(path):
  50. """Adjusts the directory until a compilation database is found."""
  51. result = './'
  52. while not os.path.isfile(os.path.join(result, path)):
  53. if os.path.realpath(result) == '/':
  54. print('Error: could not find compilation database.')
  55. sys.exit(1)
  56. result += '../'
  57. return os.path.realpath(result)
  58. def make_absolute(f, directory):
  59. if os.path.isabs(f):
  60. return f
  61. return os.path.normpath(os.path.join(directory, f))
  62. def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path,
  63. header_filter, extra_arg, extra_arg_before, quiet):
  64. """Gets a command line for clang-tidy."""
  65. start = [clang_tidy_binary]
  66. if header_filter is not None:
  67. start.append('-header-filter=' + header_filter)
  68. else:
  69. # Show warnings in all in-project headers by default.
  70. start.append('-header-filter=^' + build_path + '/.*')
  71. if checks:
  72. start.append('-checks=' + checks)
  73. if tmpdir is not None:
  74. start.append('-export-fixes')
  75. # Get a temporary file. We immediately close the handle so clang-tidy can
  76. # overwrite it.
  77. (handle, name) = tempfile.mkstemp(suffix='.yaml', dir=tmpdir)
  78. os.close(handle)
  79. start.append(name)
  80. for arg in extra_arg:
  81. start.append('-extra-arg=%s' % arg)
  82. for arg in extra_arg_before:
  83. start.append('-extra-arg-before=%s' % arg)
  84. start.append('-p=' + build_path)
  85. if quiet:
  86. start.append('-quiet')
  87. start.append(f)
  88. return start
  89. def merge_replacement_files(tmpdir, mergefile):
  90. """Merge all replacement files in a directory into a single file"""
  91. # The fixes suggested by clang-tidy >= 4.0.0 are given under
  92. # the top level key 'Diagnostics' in the output yaml files
  93. mergekey="Diagnostics"
  94. merged=[]
  95. for replacefile in glob.iglob(os.path.join(tmpdir, '*.yaml')):
  96. content = yaml.safe_load(open(replacefile, 'r'))
  97. if not content:
  98. continue # Skip empty files.
  99. merged.extend(content.get(mergekey, []))
  100. if merged:
  101. # MainSourceFile: The key is required by the definition inside
  102. # include/clang/Tooling/ReplacementsYaml.h, but the value
  103. # is actually never used inside clang-apply-replacements,
  104. # so we set it to '' here.
  105. output = { 'MainSourceFile': '', mergekey: merged }
  106. with open(mergefile, 'w') as out:
  107. yaml.safe_dump(output, out)
  108. else:
  109. # Empty the file:
  110. open(mergefile, 'w').close()
  111. def check_clang_apply_replacements_binary(args):
  112. """Checks if invoking supplied clang-apply-replacements binary works."""
  113. try:
  114. subprocess.check_call([args.clang_apply_replacements_binary, '--version'])
  115. except:
  116. print('Unable to run clang-apply-replacements. Is clang-apply-replacements '
  117. 'binary correctly specified?', file=sys.stderr)
  118. traceback.print_exc()
  119. sys.exit(1)
  120. def apply_fixes(args, tmpdir):
  121. """Calls clang-apply-fixes on a given directory."""
  122. invocation = [args.clang_apply_replacements_binary]
  123. if args.format:
  124. invocation.append('-format')
  125. if args.style:
  126. invocation.append('-style=' + args.style)
  127. invocation.append(tmpdir)
  128. subprocess.call(invocation)
  129. def run_tidy(args, tmpdir, build_path, queue):
  130. """Takes filenames out of queue and runs clang-tidy on them."""
  131. while True:
  132. name = queue.get()
  133. invocation = get_tidy_invocation(name, args.clang_tidy_binary, args.checks,
  134. tmpdir, build_path, args.header_filter,
  135. args.extra_arg, args.extra_arg_before,
  136. args.quiet)
  137. sys.stdout.write(' '.join(invocation) + '\n')
  138. subprocess.call(invocation)
  139. queue.task_done()
  140. def main():
  141. parser = argparse.ArgumentParser(description='Runs clang-tidy over all files '
  142. 'in a compilation database. Requires '
  143. 'clang-tidy and clang-apply-replacements in '
  144. '$PATH.')
  145. parser.add_argument('-clang-tidy-binary', metavar='PATH',
  146. default='clang-tidy',
  147. help='path to clang-tidy binary')
  148. parser.add_argument('-clang-apply-replacements-binary', metavar='PATH',
  149. default='clang-apply-replacements',
  150. help='path to clang-apply-replacements binary')
  151. parser.add_argument('-checks', default=None,
  152. help='checks filter, when not specified, use clang-tidy '
  153. 'default')
  154. parser.add_argument('-header-filter', default=None,
  155. help='regular expression matching the names of the '
  156. 'headers to output diagnostics from. Diagnostics from '
  157. 'the main file of each translation unit are always '
  158. 'displayed.')
  159. parser.add_argument('-export-fixes', metavar='filename', dest='export_fixes',
  160. help='Create a yaml file to store suggested fixes in, '
  161. 'which can be applied with clang-apply-replacements.')
  162. parser.add_argument('-j', type=int, default=0,
  163. help='number of tidy instances to be run in parallel.')
  164. parser.add_argument('files', nargs='*', default=['.*'],
  165. help='files to be processed (regex on path)')
  166. parser.add_argument('-fix', action='store_true', help='apply fix-its')
  167. parser.add_argument('-format', action='store_true', help='Reformat code '
  168. 'after applying fixes')
  169. parser.add_argument('-style', default='file', help='The style of reformat '
  170. 'code after applying fixes')
  171. parser.add_argument('-p', dest='build_path',
  172. help='Path used to read a compile command database.')
  173. parser.add_argument('-extra-arg', dest='extra_arg',
  174. action='append', default=[],
  175. help='Additional argument to append to the compiler '
  176. 'command line.')
  177. parser.add_argument('-extra-arg-before', dest='extra_arg_before',
  178. action='append', default=[],
  179. help='Additional argument to prepend to the compiler '
  180. 'command line.')
  181. parser.add_argument('-quiet', action='store_true',
  182. help='Run clang-tidy in quiet mode')
  183. args = parser.parse_args()
  184. db_path = 'compile_commands.json'
  185. if args.build_path is not None:
  186. build_path = args.build_path
  187. else:
  188. # Find our database
  189. build_path = find_compilation_database(db_path)
  190. try:
  191. invocation = [args.clang_tidy_binary, '-list-checks']
  192. invocation.append('-p=' + build_path)
  193. if args.checks:
  194. invocation.append('-checks=' + args.checks)
  195. invocation.append('-')
  196. subprocess.check_call(invocation)
  197. except:
  198. print("Unable to run clang-tidy.", file=sys.stderr)
  199. sys.exit(1)
  200. # Load the database and extract all files.
  201. database = json.load(open(os.path.join(build_path, db_path)))
  202. files = [make_absolute(entry['file'], entry['directory'])
  203. for entry in database]
  204. max_task = args.j
  205. if max_task == 0:
  206. max_task = multiprocessing.cpu_count()
  207. tmpdir = None
  208. if args.fix or args.export_fixes:
  209. check_clang_apply_replacements_binary(args)
  210. tmpdir = tempfile.mkdtemp()
  211. # Build up a big regexy filter from all command line arguments.
  212. file_name_re = re.compile('|'.join(args.files))
  213. try:
  214. # Spin up a bunch of tidy-launching threads.
  215. task_queue = queue.Queue(max_task)
  216. for _ in range(max_task):
  217. t = threading.Thread(target=run_tidy,
  218. args=(args, tmpdir, build_path, task_queue))
  219. t.daemon = True
  220. t.start()
  221. # Fill the queue with files.
  222. for name in files:
  223. if file_name_re.search(name):
  224. task_queue.put(name)
  225. # Wait for all threads to be done.
  226. task_queue.join()
  227. except KeyboardInterrupt:
  228. # This is a sad hack. Unfortunately subprocess goes
  229. # bonkers with ctrl-c and we start forking merrily.
  230. print('\nCtrl-C detected, goodbye.')
  231. if tmpdir:
  232. shutil.rmtree(tmpdir)
  233. os.kill(0, 9)
  234. return_code = 0
  235. if args.export_fixes:
  236. print('Writing fixes to ' + args.export_fixes + ' ...')
  237. try:
  238. merge_replacement_files(tmpdir, args.export_fixes)
  239. except:
  240. print('Error exporting fixes.\n', file=sys.stderr)
  241. traceback.print_exc()
  242. return_code=1
  243. if args.fix:
  244. print('Applying fixes ...')
  245. try:
  246. apply_fixes(args, tmpdir)
  247. except:
  248. print('Error applying fixes.\n', file=sys.stderr)
  249. traceback.print_exc()
  250. return_code=1
  251. if tmpdir:
  252. shutil.rmtree(tmpdir)
  253. sys.exit(return_code)
  254. if __name__ == '__main__':
  255. main()