run-clang-tidy.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. import argparse
  31. import json
  32. import multiprocessing
  33. import os
  34. import Queue
  35. import re
  36. import shutil
  37. import subprocess
  38. import sys
  39. import tempfile
  40. import threading
  41. def find_compilation_database(path):
  42. """Adjusts the directory until a compilation database is found."""
  43. result = './'
  44. while not os.path.isfile(os.path.join(result, path)):
  45. if os.path.realpath(result) == '/':
  46. print 'Error: could not find compilation database.'
  47. sys.exit(1)
  48. result += '../'
  49. return os.path.realpath(result)
  50. def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path,
  51. header_filter):
  52. """Gets a command line for clang-tidy."""
  53. start = [clang_tidy_binary]
  54. if header_filter is not None:
  55. start.append('-header-filter=' + header_filter)
  56. else:
  57. # Show warnings in all in-project headers by default.
  58. start.append('-header-filter=^' + build_path + '/.*')
  59. if checks:
  60. start.append('-checks=' + checks)
  61. if tmpdir is not None:
  62. start.append('-export-fixes')
  63. # Get a temporary file. We immediately close the handle so clang-tidy can
  64. # overwrite it.
  65. (handle, name) = tempfile.mkstemp(suffix='.yaml', dir=tmpdir)
  66. os.close(handle)
  67. start.append(name)
  68. start.append('-p=' + build_path)
  69. start.append(f)
  70. return start
  71. def apply_fixes(args, tmpdir):
  72. """Calls clang-apply-fixes on a given directory. Deletes the dir when done."""
  73. invocation = [args.clang_apply_replacements_binary]
  74. if args.format:
  75. invocation.append('-format')
  76. invocation.append(tmpdir)
  77. subprocess.call(invocation)
  78. shutil.rmtree(tmpdir)
  79. def run_tidy(args, tmpdir, build_path, queue):
  80. """Takes filenames out of queue and runs clang-tidy on them."""
  81. while True:
  82. name = queue.get()
  83. invocation = get_tidy_invocation(name, args.clang_tidy_binary, args.checks,
  84. tmpdir, build_path, args.header_filter)
  85. sys.stdout.write(' '.join(invocation) + '\n')
  86. subprocess.call(invocation)
  87. queue.task_done()
  88. def main():
  89. parser = argparse.ArgumentParser(description='Runs clang-tidy over all files '
  90. 'in a compilation database. Requires '
  91. 'clang-tidy and clang-apply-replacements in '
  92. '$PATH.')
  93. parser.add_argument('-clang-tidy-binary', metavar='PATH',
  94. default='clang-tidy',
  95. help='path to clang-tidy binary')
  96. parser.add_argument('-clang-apply-replacements-binary', metavar='PATH',
  97. default='clang-apply-replacements',
  98. help='path to clang-apply-replacements binary')
  99. parser.add_argument('-checks', default=None,
  100. help='checks filter, when not specified, use clang-tidy '
  101. 'default')
  102. parser.add_argument('-header-filter', default=None,
  103. help='regular expression matching the names of the '
  104. 'headers to output diagnostics from. Diagnostics from '
  105. 'the main file of each translation unit are always '
  106. 'displayed.')
  107. parser.add_argument('-j', type=int, default=0,
  108. help='number of tidy instances to be run in parallel.')
  109. parser.add_argument('files', nargs='*', default=['.*'],
  110. help='files to be processed (regex on path)')
  111. parser.add_argument('-fix', action='store_true', help='apply fix-its')
  112. parser.add_argument('-format', action='store_true', help='Reformat code '
  113. 'after applying fixes')
  114. parser.add_argument('-p', dest='build_path',
  115. help='Path used to read a compile command database.')
  116. args = parser.parse_args()
  117. db_path = 'compile_commands.json'
  118. if args.build_path is not None:
  119. build_path = args.build_path
  120. else:
  121. # Find our database
  122. build_path = find_compilation_database(db_path)
  123. try:
  124. invocation = [args.clang_tidy_binary, '-list-checks']
  125. invocation.append('-p=' + build_path)
  126. if args.checks:
  127. invocation.append('-checks=' + args.checks)
  128. invocation.append('-')
  129. print subprocess.check_output(invocation)
  130. except:
  131. print >>sys.stderr, "Unable to run clang-tidy."
  132. sys.exit(1)
  133. # Load the database and extract all files.
  134. database = json.load(open(os.path.join(build_path, db_path)))
  135. files = [entry['file'] for entry in database]
  136. max_task = args.j
  137. if max_task == 0:
  138. max_task = multiprocessing.cpu_count()
  139. tmpdir = None
  140. if args.fix:
  141. tmpdir = tempfile.mkdtemp()
  142. # Build up a big regexy filter from all command line arguments.
  143. file_name_re = re.compile('(' + ')|('.join(args.files) + ')')
  144. try:
  145. # Spin up a bunch of tidy-launching threads.
  146. queue = Queue.Queue(max_task)
  147. for _ in range(max_task):
  148. t = threading.Thread(target=run_tidy,
  149. args=(args, tmpdir, build_path, queue))
  150. t.daemon = True
  151. t.start()
  152. # Fill the queue with files.
  153. for name in files:
  154. if file_name_re.search(name):
  155. queue.put(name)
  156. # Wait for all threads to be done.
  157. queue.join()
  158. except KeyboardInterrupt:
  159. # This is a sad hack. Unfortunately subprocess goes
  160. # bonkers with ctrl-c and we start forking merrily.
  161. print '\nCtrl-C detected, goodbye.'
  162. if args.fix:
  163. shutil.rmtree(tmpdir)
  164. os.kill(0, 9)
  165. if args.fix:
  166. print 'Applying fixes ...'
  167. apply_fixes(args, tmpdir)
  168. if __name__ == '__main__':
  169. main()