blob: 648c17eadd1bd5dfedeff25c9e48c5d575180291 [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#
Chandler Carruth2946cd72019-01-19 08:50:56 +00005# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
6# See https://llvm.org/LICENSE.txt for license information.
7# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +00008#
9#===------------------------------------------------------------------------===#
10# FIXME: Integrate with clang-tidy-diff.py
11
12"""
13Parallel clang-tidy runner
14==========================
15
16Runs clang-tidy over all files in a compilation database. Requires clang-tidy
17and clang-apply-replacements in $PATH.
18
19Example invocations.
20- Run clang-tidy on all files in the current working directory with a default
21 set of checks and show warnings in the cpp files and all project headers.
22 run-clang-tidy.py $PWD
23
24- Fix all header guards.
25 run-clang-tidy.py -fix -checks=-*,llvm-header-guard
26
27- Fix all header guards included from clang-tidy and header guards
28 for clang-tidy headers.
29 run-clang-tidy.py -fix -checks=-*,llvm-header-guard extra/clang-tidy \
30 -header-filter=extra/clang-tidy
31
32Compilation database setup:
33http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
34"""
35
Jakub Kuderskia7410fd2017-04-25 22:38:39 +000036from __future__ import print_function
Kevin Funkd331cb62017-09-05 12:36:33 +000037
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
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000043import re
44import shutil
45import subprocess
46import sys
47import tempfile
48import threading
Jakub Kuderskia7410fd2017-04-25 22:38:39 +000049import traceback
Zinovy Nisf8b7269f2019-03-27 19:21:32 +000050
51try:
52 import yaml
53except ImportError:
54 yaml = None
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000055
Kevin Funkd331cb62017-09-05 12:36:33 +000056is_py2 = sys.version[0] == '2'
57
58if is_py2:
59 import Queue as queue
60else:
61 import queue as queue
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000062
63def find_compilation_database(path):
64 """Adjusts the directory until a compilation database is found."""
65 result = './'
66 while not os.path.isfile(os.path.join(result, path)):
67 if os.path.realpath(result) == '/':
Jakub Kuderskia7410fd2017-04-25 22:38:39 +000068 print('Error: could not find compilation database.')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000069 sys.exit(1)
70 result += '../'
71 return os.path.realpath(result)
72
73
Gabor Horvath8de900a2017-11-06 10:36:02 +000074def make_absolute(f, directory):
75 if os.path.isabs(f):
76 return f
77 return os.path.normpath(os.path.join(directory, f))
78
79
Benjamin Kramer815dbad2014-09-08 14:56:40 +000080def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path,
Julie Hockettc3716ca2018-03-09 23:26:56 +000081 header_filter, extra_arg, extra_arg_before, quiet,
82 config):
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000083 """Gets a command line for clang-tidy."""
Benjamin Kramer815dbad2014-09-08 14:56:40 +000084 start = [clang_tidy_binary]
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000085 if header_filter is not None:
86 start.append('-header-filter=' + header_filter)
87 else:
88 # Show warnings in all in-project headers by default.
89 start.append('-header-filter=^' + build_path + '/.*')
90 if checks:
Alexander Kornienko3f115382015-09-08 10:31:36 +000091 start.append('-checks=' + checks)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000092 if tmpdir is not None:
93 start.append('-export-fixes')
94 # Get a temporary file. We immediately close the handle so clang-tidy can
95 # overwrite it.
96 (handle, name) = tempfile.mkstemp(suffix='.yaml', dir=tmpdir)
Benjamin Kramer815dbad2014-09-08 14:56:40 +000097 os.close(handle)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000098 start.append(name)
Ehsan Akhgari221ab772017-01-18 17:49:35 +000099 for arg in extra_arg:
100 start.append('-extra-arg=%s' % arg)
101 for arg in extra_arg_before:
102 start.append('-extra-arg-before=%s' % arg)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000103 start.append('-p=' + build_path)
Ehsan Akhgarib7418d32017-02-09 18:32:02 +0000104 if quiet:
105 start.append('-quiet')
Julie Hockettc3716ca2018-03-09 23:26:56 +0000106 if config:
107 start.append('-config=' + config)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000108 start.append(f)
109 return start
110
111
Alexander Kornienko16300e12017-07-21 10:31:26 +0000112def merge_replacement_files(tmpdir, mergefile):
113 """Merge all replacement files in a directory into a single file"""
114 # The fixes suggested by clang-tidy >= 4.0.0 are given under
115 # the top level key 'Diagnostics' in the output yaml files
116 mergekey="Diagnostics"
117 merged=[]
118 for replacefile in glob.iglob(os.path.join(tmpdir, '*.yaml')):
119 content = yaml.safe_load(open(replacefile, 'r'))
120 if not content:
121 continue # Skip empty files.
122 merged.extend(content.get(mergekey, []))
123
124 if merged:
125 # MainSourceFile: The key is required by the definition inside
126 # include/clang/Tooling/ReplacementsYaml.h, but the value
127 # is actually never used inside clang-apply-replacements,
128 # so we set it to '' here.
129 output = { 'MainSourceFile': '', mergekey: merged }
130 with open(mergefile, 'w') as out:
131 yaml.safe_dump(output, out)
132 else:
133 # Empty the file:
134 open(mergefile, 'w').close()
135
136
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000137def check_clang_apply_replacements_binary(args):
138 """Checks if invoking supplied clang-apply-replacements binary works."""
139 try:
140 subprocess.check_call([args.clang_apply_replacements_binary, '--version'])
141 except:
142 print('Unable to run clang-apply-replacements. Is clang-apply-replacements '
143 'binary correctly specified?', file=sys.stderr)
144 traceback.print_exc()
145 sys.exit(1)
146
147
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000148def apply_fixes(args, tmpdir):
Alexander Kornienko16300e12017-07-21 10:31:26 +0000149 """Calls clang-apply-fixes on a given directory."""
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000150 invocation = [args.clang_apply_replacements_binary]
151 if args.format:
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000152 invocation.append('-format')
Vassil Vassilevc4c33ce2017-06-09 22:23:03 +0000153 if args.style:
154 invocation.append('-style=' + args.style)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000155 invocation.append(tmpdir)
156 subprocess.call(invocation)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000157
158
Andi-Bogdan Postelnicubebcd6f2018-08-10 11:50:47 +0000159def run_tidy(args, tmpdir, build_path, queue, lock, failed_files):
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000160 """Takes filenames out of queue and runs clang-tidy on them."""
161 while True:
162 name = queue.get()
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000163 invocation = get_tidy_invocation(name, args.clang_tidy_binary, args.checks,
Ehsan Akhgari221ab772017-01-18 17:49:35 +0000164 tmpdir, build_path, args.header_filter,
Ehsan Akhgarib7418d32017-02-09 18:32:02 +0000165 args.extra_arg, args.extra_arg_before,
Julie Hockettc3716ca2018-03-09 23:26:56 +0000166 args.quiet, args.config)
Andi-Bogdan Postelnicubebcd6f2018-08-10 11:50:47 +0000167
168 proc = subprocess.Popen(invocation, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
169 output, err = proc.communicate()
170 if proc.returncode != 0:
Miklos Vajna10fe9bc2018-03-19 14:43:59 +0000171 failed_files.append(name)
Andi-Bogdan Postelnicubebcd6f2018-08-10 11:50:47 +0000172 with lock:
Andi-Bogdan Postelnicu1a056972018-09-19 11:52:20 +0000173 sys.stdout.write(' '.join(invocation) + '\n' + output.decode('utf-8') + '\n')
174 if len(err) > 0:
Andi-Bogdan Postelnicu965c5812019-04-09 11:17:02 +0000175 sys.stdout.flush()
Andi-Bogdan Postelnicu1a056972018-09-19 11:52:20 +0000176 sys.stderr.write(err.decode('utf-8') + '\n')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000177 queue.task_done()
178
179
180def main():
181 parser = argparse.ArgumentParser(description='Runs clang-tidy over all files '
182 'in a compilation database. Requires '
183 'clang-tidy and clang-apply-replacements in '
184 '$PATH.')
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000185 parser.add_argument('-clang-tidy-binary', metavar='PATH',
186 default='clang-tidy',
187 help='path to clang-tidy binary')
188 parser.add_argument('-clang-apply-replacements-binary', metavar='PATH',
189 default='clang-apply-replacements',
190 help='path to clang-apply-replacements binary')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000191 parser.add_argument('-checks', default=None,
192 help='checks filter, when not specified, use clang-tidy '
193 'default')
Julie Hockettc3716ca2018-03-09 23:26:56 +0000194 parser.add_argument('-config', default=None,
195 help='Specifies a configuration in YAML/JSON format: '
196 ' -config="{Checks: \'*\', '
197 ' CheckOptions: [{key: x, '
198 ' value: y}]}" '
199 'When the value is empty, clang-tidy will '
200 'attempt to find a file named .clang-tidy for '
201 'each source file in its parent directories.')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000202 parser.add_argument('-header-filter', default=None,
203 help='regular expression matching the names of the '
204 'headers to output diagnostics from. Diagnostics from '
205 'the main file of each translation unit are always '
206 'displayed.')
Zinovy Nisf8b7269f2019-03-27 19:21:32 +0000207 if yaml:
208 parser.add_argument('-export-fixes', metavar='filename', dest='export_fixes',
209 help='Create a yaml file to store suggested fixes in, '
210 'which can be applied with clang-apply-replacements.')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000211 parser.add_argument('-j', type=int, default=0,
212 help='number of tidy instances to be run in parallel.')
213 parser.add_argument('files', nargs='*', default=['.*'],
214 help='files to be processed (regex on path)')
215 parser.add_argument('-fix', action='store_true', help='apply fix-its')
216 parser.add_argument('-format', action='store_true', help='Reformat code '
217 'after applying fixes')
Vassil Vassilevc4c33ce2017-06-09 22:23:03 +0000218 parser.add_argument('-style', default='file', help='The style of reformat '
219 'code after applying fixes')
Guillaume Papin68b59102015-09-28 17:53:04 +0000220 parser.add_argument('-p', dest='build_path',
221 help='Path used to read a compile command database.')
Ehsan Akhgari221ab772017-01-18 17:49:35 +0000222 parser.add_argument('-extra-arg', dest='extra_arg',
223 action='append', default=[],
224 help='Additional argument to append to the compiler '
225 'command line.')
226 parser.add_argument('-extra-arg-before', dest='extra_arg_before',
227 action='append', default=[],
228 help='Additional argument to prepend to the compiler '
229 'command line.')
Ehsan Akhgarib7418d32017-02-09 18:32:02 +0000230 parser.add_argument('-quiet', action='store_true',
231 help='Run clang-tidy in quiet mode')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000232 args = parser.parse_args()
233
Guillaume Papin68b59102015-09-28 17:53:04 +0000234 db_path = 'compile_commands.json'
235
236 if args.build_path is not None:
237 build_path = args.build_path
238 else:
239 # Find our database
240 build_path = find_compilation_database(db_path)
241
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000242 try:
Alexander Kornienkof73fe3a2014-09-22 00:07:07 +0000243 invocation = [args.clang_tidy_binary, '-list-checks']
Guillaume Papin68b59102015-09-28 17:53:04 +0000244 invocation.append('-p=' + build_path)
Alexander Kornienkof73fe3a2014-09-22 00:07:07 +0000245 if args.checks:
Alexander Kornienko3f115382015-09-08 10:31:36 +0000246 invocation.append('-checks=' + args.checks)
Alexander Kornienkof73fe3a2014-09-22 00:07:07 +0000247 invocation.append('-')
Kevin Funk08c2f0f2017-11-28 07:17:01 +0000248 subprocess.check_call(invocation)
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000249 except:
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000250 print("Unable to run clang-tidy.", file=sys.stderr)
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000251 sys.exit(1)
252
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000253 # Load the database and extract all files.
254 database = json.load(open(os.path.join(build_path, db_path)))
Gabor Horvath8de900a2017-11-06 10:36:02 +0000255 files = [make_absolute(entry['file'], entry['directory'])
256 for entry in database]
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000257
258 max_task = args.j
259 if max_task == 0:
260 max_task = multiprocessing.cpu_count()
261
262 tmpdir = None
Zinovy Nisf8b7269f2019-03-27 19:21:32 +0000263 if args.fix or (yaml and args.export_fixes):
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000264 check_clang_apply_replacements_binary(args)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000265 tmpdir = tempfile.mkdtemp()
266
267 # Build up a big regexy filter from all command line arguments.
Alexander Kornienkoeaada5c2017-03-23 16:29:39 +0000268 file_name_re = re.compile('|'.join(args.files))
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000269
Miklos Vajna10fe9bc2018-03-19 14:43:59 +0000270 return_code = 0
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000271 try:
272 # Spin up a bunch of tidy-launching threads.
Kevin Funkd331cb62017-09-05 12:36:33 +0000273 task_queue = queue.Queue(max_task)
Miklos Vajna10fe9bc2018-03-19 14:43:59 +0000274 # List of files with a non-zero return code.
275 failed_files = []
Andi-Bogdan Postelnicubebcd6f2018-08-10 11:50:47 +0000276 lock = threading.Lock()
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000277 for _ in range(max_task):
278 t = threading.Thread(target=run_tidy,
Andi-Bogdan Postelnicubebcd6f2018-08-10 11:50:47 +0000279 args=(args, tmpdir, build_path, task_queue, lock, failed_files))
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000280 t.daemon = True
281 t.start()
282
283 # Fill the queue with files.
284 for name in files:
285 if file_name_re.search(name):
Kevin Funkd331cb62017-09-05 12:36:33 +0000286 task_queue.put(name)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000287
288 # Wait for all threads to be done.
Kevin Funkd331cb62017-09-05 12:36:33 +0000289 task_queue.join()
Miklos Vajna10fe9bc2018-03-19 14:43:59 +0000290 if len(failed_files):
291 return_code = 1
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000292
293 except KeyboardInterrupt:
294 # This is a sad hack. Unfortunately subprocess goes
295 # bonkers with ctrl-c and we start forking merrily.
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000296 print('\nCtrl-C detected, goodbye.')
Alexander Kornienko16300e12017-07-21 10:31:26 +0000297 if tmpdir:
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000298 shutil.rmtree(tmpdir)
299 os.kill(0, 9)
300
Zinovy Nisf8b7269f2019-03-27 19:21:32 +0000301 if yaml and args.export_fixes:
Alexander Kornienko16300e12017-07-21 10:31:26 +0000302 print('Writing fixes to ' + args.export_fixes + ' ...')
303 try:
304 merge_replacement_files(tmpdir, args.export_fixes)
305 except:
306 print('Error exporting fixes.\n', file=sys.stderr)
307 traceback.print_exc()
308 return_code=1
309
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000310 if args.fix:
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000311 print('Applying fixes ...')
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000312 try:
313 apply_fixes(args, tmpdir)
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000314 except:
315 print('Error applying fixes.\n', file=sys.stderr)
316 traceback.print_exc()
Alexander Kornienko16300e12017-07-21 10:31:26 +0000317 return_code=1
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000318
Alexander Kornienko16300e12017-07-21 10:31:26 +0000319 if tmpdir:
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000320 shutil.rmtree(tmpdir)
Alexander Kornienko16300e12017-07-21 10:31:26 +0000321 sys.exit(return_code)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000322
323if __name__ == '__main__':
324 main()