blob: cce1f44f861f92b323d7cf53f0d4f7fe81514b5e [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:
Jonas Tothf12c9732019-05-16 12:39:22 +0000173 sys.stdout.write(' '.join(invocation) + '\n' + output.decode('utf-8'))
Andi-Bogdan Postelnicu1a056972018-09-19 11:52:20 +0000174 if len(err) > 0:
Andi-Bogdan Postelnicu965c5812019-04-09 11:17:02 +0000175 sys.stdout.flush()
Jonas Tothf12c9732019-05-16 12:39:22 +0000176 sys.stderr.write(err.decode('utf-8'))
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('-')
Jonas Toth3cbf3c82019-05-16 09:22:39 +0000248 if args.quiet:
249 # Even with -quiet we still want to check if we can call clang-tidy.
250 with open(os.devnull, 'w') as dev_null:
251 subprocess.check_call(invocation, stdout=dev_null)
252 else:
253 subprocess.check_call(invocation)
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000254 except:
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000255 print("Unable to run clang-tidy.", file=sys.stderr)
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000256 sys.exit(1)
257
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000258 # Load the database and extract all files.
259 database = json.load(open(os.path.join(build_path, db_path)))
Gabor Horvath8de900a2017-11-06 10:36:02 +0000260 files = [make_absolute(entry['file'], entry['directory'])
261 for entry in database]
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000262
263 max_task = args.j
264 if max_task == 0:
265 max_task = multiprocessing.cpu_count()
266
267 tmpdir = None
Zinovy Nisf8b7269f2019-03-27 19:21:32 +0000268 if args.fix or (yaml and args.export_fixes):
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000269 check_clang_apply_replacements_binary(args)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000270 tmpdir = tempfile.mkdtemp()
271
272 # Build up a big regexy filter from all command line arguments.
Alexander Kornienkoeaada5c2017-03-23 16:29:39 +0000273 file_name_re = re.compile('|'.join(args.files))
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000274
Miklos Vajna10fe9bc2018-03-19 14:43:59 +0000275 return_code = 0
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000276 try:
277 # Spin up a bunch of tidy-launching threads.
Kevin Funkd331cb62017-09-05 12:36:33 +0000278 task_queue = queue.Queue(max_task)
Miklos Vajna10fe9bc2018-03-19 14:43:59 +0000279 # List of files with a non-zero return code.
280 failed_files = []
Andi-Bogdan Postelnicubebcd6f2018-08-10 11:50:47 +0000281 lock = threading.Lock()
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000282 for _ in range(max_task):
283 t = threading.Thread(target=run_tidy,
Andi-Bogdan Postelnicubebcd6f2018-08-10 11:50:47 +0000284 args=(args, tmpdir, build_path, task_queue, lock, failed_files))
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000285 t.daemon = True
286 t.start()
287
288 # Fill the queue with files.
289 for name in files:
290 if file_name_re.search(name):
Kevin Funkd331cb62017-09-05 12:36:33 +0000291 task_queue.put(name)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000292
293 # Wait for all threads to be done.
Kevin Funkd331cb62017-09-05 12:36:33 +0000294 task_queue.join()
Miklos Vajna10fe9bc2018-03-19 14:43:59 +0000295 if len(failed_files):
296 return_code = 1
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000297
298 except KeyboardInterrupt:
299 # This is a sad hack. Unfortunately subprocess goes
300 # bonkers with ctrl-c and we start forking merrily.
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000301 print('\nCtrl-C detected, goodbye.')
Alexander Kornienko16300e12017-07-21 10:31:26 +0000302 if tmpdir:
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000303 shutil.rmtree(tmpdir)
304 os.kill(0, 9)
305
Zinovy Nisf8b7269f2019-03-27 19:21:32 +0000306 if yaml and args.export_fixes:
Alexander Kornienko16300e12017-07-21 10:31:26 +0000307 print('Writing fixes to ' + args.export_fixes + ' ...')
308 try:
309 merge_replacement_files(tmpdir, args.export_fixes)
310 except:
311 print('Error exporting fixes.\n', file=sys.stderr)
312 traceback.print_exc()
313 return_code=1
314
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000315 if args.fix:
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000316 print('Applying fixes ...')
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000317 try:
318 apply_fixes(args, tmpdir)
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000319 except:
320 print('Error applying fixes.\n', file=sys.stderr)
321 traceback.print_exc()
Alexander Kornienko16300e12017-07-21 10:31:26 +0000322 return_code=1
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000323
Alexander Kornienko16300e12017-07-21 10:31:26 +0000324 if tmpdir:
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000325 shutil.rmtree(tmpdir)
Alexander Kornienko16300e12017-07-21 10:31:26 +0000326 sys.exit(return_code)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000327
328if __name__ == '__main__':
329 main()