blob: 212cdb82a113119a77d80d4fe6463f1e3570f58d [file] [log] [blame]
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +00001#!/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"""
14Parallel clang-tidy runner
15==========================
16
17Runs clang-tidy over all files in a compilation database. Requires clang-tidy
18and clang-apply-replacements in $PATH.
19
20Example invocations.
21- Run clang-tidy on all files in the current working directory with a default
22 set of checks and show warnings in the cpp files and all project headers.
23 run-clang-tidy.py $PWD
24
25- Fix all header guards.
26 run-clang-tidy.py -fix -checks=-*,llvm-header-guard
27
28- Fix all header guards included from clang-tidy and header guards
29 for clang-tidy headers.
30 run-clang-tidy.py -fix -checks=-*,llvm-header-guard extra/clang-tidy \
31 -header-filter=extra/clang-tidy
32
33Compilation database setup:
34http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
35"""
36
Jakub Kuderskia7410fd2017-04-25 22:38:39 +000037from __future__ import print_function
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000038import argparse
Alexander Kornienko16300e12017-07-21 10:31:26 +000039import glob
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000040import json
41import multiprocessing
42import os
43import Queue
44import re
45import shutil
46import subprocess
47import sys
48import tempfile
49import threading
Jakub Kuderskia7410fd2017-04-25 22:38:39 +000050import traceback
Alexander Kornienko16300e12017-07-21 10:31:26 +000051import yaml
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000052
53
54def find_compilation_database(path):
55 """Adjusts the directory until a compilation database is found."""
56 result = './'
57 while not os.path.isfile(os.path.join(result, path)):
58 if os.path.realpath(result) == '/':
Jakub Kuderskia7410fd2017-04-25 22:38:39 +000059 print('Error: could not find compilation database.')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000060 sys.exit(1)
61 result += '../'
62 return os.path.realpath(result)
63
64
Benjamin Kramer815dbad2014-09-08 14:56:40 +000065def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path,
Ehsan Akhgarib7418d32017-02-09 18:32:02 +000066 header_filter, extra_arg, extra_arg_before, quiet):
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000067 """Gets a command line for clang-tidy."""
Benjamin Kramer815dbad2014-09-08 14:56:40 +000068 start = [clang_tidy_binary]
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000069 if header_filter is not None:
70 start.append('-header-filter=' + header_filter)
71 else:
72 # Show warnings in all in-project headers by default.
73 start.append('-header-filter=^' + build_path + '/.*')
74 if checks:
Alexander Kornienko3f115382015-09-08 10:31:36 +000075 start.append('-checks=' + checks)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000076 if tmpdir is not None:
77 start.append('-export-fixes')
78 # Get a temporary file. We immediately close the handle so clang-tidy can
79 # overwrite it.
80 (handle, name) = tempfile.mkstemp(suffix='.yaml', dir=tmpdir)
Benjamin Kramer815dbad2014-09-08 14:56:40 +000081 os.close(handle)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000082 start.append(name)
Ehsan Akhgari221ab772017-01-18 17:49:35 +000083 for arg in extra_arg:
84 start.append('-extra-arg=%s' % arg)
85 for arg in extra_arg_before:
86 start.append('-extra-arg-before=%s' % arg)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000087 start.append('-p=' + build_path)
Ehsan Akhgarib7418d32017-02-09 18:32:02 +000088 if quiet:
89 start.append('-quiet')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000090 start.append(f)
91 return start
92
93
Alexander Kornienko16300e12017-07-21 10:31:26 +000094def merge_replacement_files(tmpdir, mergefile):
95 """Merge all replacement files in a directory into a single file"""
96 # The fixes suggested by clang-tidy >= 4.0.0 are given under
97 # the top level key 'Diagnostics' in the output yaml files
98 mergekey="Diagnostics"
99 merged=[]
100 for replacefile in glob.iglob(os.path.join(tmpdir, '*.yaml')):
101 content = yaml.safe_load(open(replacefile, 'r'))
102 if not content:
103 continue # Skip empty files.
104 merged.extend(content.get(mergekey, []))
105
106 if merged:
107 # MainSourceFile: The key is required by the definition inside
108 # include/clang/Tooling/ReplacementsYaml.h, but the value
109 # is actually never used inside clang-apply-replacements,
110 # so we set it to '' here.
111 output = { 'MainSourceFile': '', mergekey: merged }
112 with open(mergefile, 'w') as out:
113 yaml.safe_dump(output, out)
114 else:
115 # Empty the file:
116 open(mergefile, 'w').close()
117
118
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000119def check_clang_apply_replacements_binary(args):
120 """Checks if invoking supplied clang-apply-replacements binary works."""
121 try:
122 subprocess.check_call([args.clang_apply_replacements_binary, '--version'])
123 except:
124 print('Unable to run clang-apply-replacements. Is clang-apply-replacements '
125 'binary correctly specified?', file=sys.stderr)
126 traceback.print_exc()
127 sys.exit(1)
128
129
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000130def apply_fixes(args, tmpdir):
Alexander Kornienko16300e12017-07-21 10:31:26 +0000131 """Calls clang-apply-fixes on a given directory."""
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000132 invocation = [args.clang_apply_replacements_binary]
133 if args.format:
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000134 invocation.append('-format')
Vassil Vassilevc4c33ce2017-06-09 22:23:03 +0000135 if args.style:
136 invocation.append('-style=' + args.style)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000137 invocation.append(tmpdir)
138 subprocess.call(invocation)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000139
140
141def run_tidy(args, tmpdir, build_path, queue):
142 """Takes filenames out of queue and runs clang-tidy on them."""
143 while True:
144 name = queue.get()
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000145 invocation = get_tidy_invocation(name, args.clang_tidy_binary, args.checks,
Ehsan Akhgari221ab772017-01-18 17:49:35 +0000146 tmpdir, build_path, args.header_filter,
Ehsan Akhgarib7418d32017-02-09 18:32:02 +0000147 args.extra_arg, args.extra_arg_before,
148 args.quiet)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000149 sys.stdout.write(' '.join(invocation) + '\n')
150 subprocess.call(invocation)
151 queue.task_done()
152
153
154def main():
155 parser = argparse.ArgumentParser(description='Runs clang-tidy over all files '
156 'in a compilation database. Requires '
157 'clang-tidy and clang-apply-replacements in '
158 '$PATH.')
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000159 parser.add_argument('-clang-tidy-binary', metavar='PATH',
160 default='clang-tidy',
161 help='path to clang-tidy binary')
162 parser.add_argument('-clang-apply-replacements-binary', metavar='PATH',
163 default='clang-apply-replacements',
164 help='path to clang-apply-replacements binary')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000165 parser.add_argument('-checks', default=None,
166 help='checks filter, when not specified, use clang-tidy '
167 'default')
168 parser.add_argument('-header-filter', default=None,
169 help='regular expression matching the names of the '
170 'headers to output diagnostics from. Diagnostics from '
171 'the main file of each translation unit are always '
172 'displayed.')
Alexander Kornienko16300e12017-07-21 10:31:26 +0000173 parser.add_argument('-export-fixes', metavar='filename', dest='export_fixes',
174 help='Create a yaml file to store suggested fixes in, '
175 'which can be applied with clang-apply-replacements.')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000176 parser.add_argument('-j', type=int, default=0,
177 help='number of tidy instances to be run in parallel.')
178 parser.add_argument('files', nargs='*', default=['.*'],
179 help='files to be processed (regex on path)')
180 parser.add_argument('-fix', action='store_true', help='apply fix-its')
181 parser.add_argument('-format', action='store_true', help='Reformat code '
182 'after applying fixes')
Vassil Vassilevc4c33ce2017-06-09 22:23:03 +0000183 parser.add_argument('-style', default='file', help='The style of reformat '
184 'code after applying fixes')
Guillaume Papin68b59102015-09-28 17:53:04 +0000185 parser.add_argument('-p', dest='build_path',
186 help='Path used to read a compile command database.')
Ehsan Akhgari221ab772017-01-18 17:49:35 +0000187 parser.add_argument('-extra-arg', dest='extra_arg',
188 action='append', default=[],
189 help='Additional argument to append to the compiler '
190 'command line.')
191 parser.add_argument('-extra-arg-before', dest='extra_arg_before',
192 action='append', default=[],
193 help='Additional argument to prepend to the compiler '
194 'command line.')
Ehsan Akhgarib7418d32017-02-09 18:32:02 +0000195 parser.add_argument('-quiet', action='store_true',
196 help='Run clang-tidy in quiet mode')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000197 args = parser.parse_args()
198
Guillaume Papin68b59102015-09-28 17:53:04 +0000199 db_path = 'compile_commands.json'
200
201 if args.build_path is not None:
202 build_path = args.build_path
203 else:
204 # Find our database
205 build_path = find_compilation_database(db_path)
206
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000207 try:
Alexander Kornienkof73fe3a2014-09-22 00:07:07 +0000208 invocation = [args.clang_tidy_binary, '-list-checks']
Guillaume Papin68b59102015-09-28 17:53:04 +0000209 invocation.append('-p=' + build_path)
Alexander Kornienkof73fe3a2014-09-22 00:07:07 +0000210 if args.checks:
Alexander Kornienko3f115382015-09-08 10:31:36 +0000211 invocation.append('-checks=' + args.checks)
Alexander Kornienkof73fe3a2014-09-22 00:07:07 +0000212 invocation.append('-')
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000213 print(subprocess.check_output(invocation))
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000214 except:
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000215 print("Unable to run clang-tidy.", file=sys.stderr)
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000216 sys.exit(1)
217
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000218 # Load the database and extract all files.
219 database = json.load(open(os.path.join(build_path, db_path)))
220 files = [entry['file'] for entry in database]
221
222 max_task = args.j
223 if max_task == 0:
224 max_task = multiprocessing.cpu_count()
225
226 tmpdir = None
Alexander Kornienko16300e12017-07-21 10:31:26 +0000227 if args.fix or args.export_fixes:
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000228 check_clang_apply_replacements_binary(args)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000229 tmpdir = tempfile.mkdtemp()
230
231 # Build up a big regexy filter from all command line arguments.
Alexander Kornienkoeaada5c2017-03-23 16:29:39 +0000232 file_name_re = re.compile('|'.join(args.files))
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000233
234 try:
235 # Spin up a bunch of tidy-launching threads.
236 queue = Queue.Queue(max_task)
237 for _ in range(max_task):
238 t = threading.Thread(target=run_tidy,
239 args=(args, tmpdir, build_path, queue))
240 t.daemon = True
241 t.start()
242
243 # Fill the queue with files.
244 for name in files:
245 if file_name_re.search(name):
246 queue.put(name)
247
248 # Wait for all threads to be done.
249 queue.join()
250
251 except KeyboardInterrupt:
252 # This is a sad hack. Unfortunately subprocess goes
253 # bonkers with ctrl-c and we start forking merrily.
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000254 print('\nCtrl-C detected, goodbye.')
Alexander Kornienko16300e12017-07-21 10:31:26 +0000255 if tmpdir:
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000256 shutil.rmtree(tmpdir)
257 os.kill(0, 9)
258
Alexander Kornienko16300e12017-07-21 10:31:26 +0000259 return_code = 0
260 if args.export_fixes:
261 print('Writing fixes to ' + args.export_fixes + ' ...')
262 try:
263 merge_replacement_files(tmpdir, args.export_fixes)
264 except:
265 print('Error exporting fixes.\n', file=sys.stderr)
266 traceback.print_exc()
267 return_code=1
268
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000269 if args.fix:
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000270 print('Applying fixes ...')
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000271 try:
272 apply_fixes(args, tmpdir)
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000273 except:
274 print('Error applying fixes.\n', file=sys.stderr)
275 traceback.print_exc()
Alexander Kornienko16300e12017-07-21 10:31:26 +0000276 return_code=1
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000277
Alexander Kornienko16300e12017-07-21 10:31:26 +0000278 if tmpdir:
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000279 shutil.rmtree(tmpdir)
Alexander Kornienko16300e12017-07-21 10:31:26 +0000280 sys.exit(return_code)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000281
282if __name__ == '__main__':
283 main()