blob: 5ec40f204de1f75e6db4cbae05e7ab88ff6d9a34 [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
Alexander Kornienko16300e12017-07-21 10:31:26 +000050import yaml
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000051
Kevin Funkd331cb62017-09-05 12:36:33 +000052is_py2 = sys.version[0] == '2'
53
54if is_py2:
55 import Queue as queue
56else:
57 import queue as queue
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000058
59def find_compilation_database(path):
60 """Adjusts the directory until a compilation database is found."""
61 result = './'
62 while not os.path.isfile(os.path.join(result, path)):
63 if os.path.realpath(result) == '/':
Jakub Kuderskia7410fd2017-04-25 22:38:39 +000064 print('Error: could not find compilation database.')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000065 sys.exit(1)
66 result += '../'
67 return os.path.realpath(result)
68
69
Gabor Horvath8de900a2017-11-06 10:36:02 +000070def make_absolute(f, directory):
71 if os.path.isabs(f):
72 return f
73 return os.path.normpath(os.path.join(directory, f))
74
75
Benjamin Kramer815dbad2014-09-08 14:56:40 +000076def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path,
Julie Hockettc3716ca2018-03-09 23:26:56 +000077 header_filter, extra_arg, extra_arg_before, quiet,
78 config):
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000079 """Gets a command line for clang-tidy."""
Benjamin Kramer815dbad2014-09-08 14:56:40 +000080 start = [clang_tidy_binary]
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000081 if header_filter is not None:
82 start.append('-header-filter=' + header_filter)
83 else:
84 # Show warnings in all in-project headers by default.
85 start.append('-header-filter=^' + build_path + '/.*')
86 if checks:
Alexander Kornienko3f115382015-09-08 10:31:36 +000087 start.append('-checks=' + checks)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000088 if tmpdir is not None:
89 start.append('-export-fixes')
90 # Get a temporary file. We immediately close the handle so clang-tidy can
91 # overwrite it.
92 (handle, name) = tempfile.mkstemp(suffix='.yaml', dir=tmpdir)
Benjamin Kramer815dbad2014-09-08 14:56:40 +000093 os.close(handle)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000094 start.append(name)
Ehsan Akhgari221ab772017-01-18 17:49:35 +000095 for arg in extra_arg:
96 start.append('-extra-arg=%s' % arg)
97 for arg in extra_arg_before:
98 start.append('-extra-arg-before=%s' % arg)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000099 start.append('-p=' + build_path)
Ehsan Akhgarib7418d32017-02-09 18:32:02 +0000100 if quiet:
101 start.append('-quiet')
Julie Hockettc3716ca2018-03-09 23:26:56 +0000102 if config:
103 start.append('-config=' + config)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000104 start.append(f)
105 return start
106
107
Alexander Kornienko16300e12017-07-21 10:31:26 +0000108def merge_replacement_files(tmpdir, mergefile):
109 """Merge all replacement files in a directory into a single file"""
110 # The fixes suggested by clang-tidy >= 4.0.0 are given under
111 # the top level key 'Diagnostics' in the output yaml files
112 mergekey="Diagnostics"
113 merged=[]
114 for replacefile in glob.iglob(os.path.join(tmpdir, '*.yaml')):
115 content = yaml.safe_load(open(replacefile, 'r'))
116 if not content:
117 continue # Skip empty files.
118 merged.extend(content.get(mergekey, []))
119
120 if merged:
121 # MainSourceFile: The key is required by the definition inside
122 # include/clang/Tooling/ReplacementsYaml.h, but the value
123 # is actually never used inside clang-apply-replacements,
124 # so we set it to '' here.
125 output = { 'MainSourceFile': '', mergekey: merged }
126 with open(mergefile, 'w') as out:
127 yaml.safe_dump(output, out)
128 else:
129 # Empty the file:
130 open(mergefile, 'w').close()
131
132
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000133def check_clang_apply_replacements_binary(args):
134 """Checks if invoking supplied clang-apply-replacements binary works."""
135 try:
136 subprocess.check_call([args.clang_apply_replacements_binary, '--version'])
137 except:
138 print('Unable to run clang-apply-replacements. Is clang-apply-replacements '
139 'binary correctly specified?', file=sys.stderr)
140 traceback.print_exc()
141 sys.exit(1)
142
143
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000144def apply_fixes(args, tmpdir):
Alexander Kornienko16300e12017-07-21 10:31:26 +0000145 """Calls clang-apply-fixes on a given directory."""
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000146 invocation = [args.clang_apply_replacements_binary]
147 if args.format:
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000148 invocation.append('-format')
Vassil Vassilevc4c33ce2017-06-09 22:23:03 +0000149 if args.style:
150 invocation.append('-style=' + args.style)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000151 invocation.append(tmpdir)
152 subprocess.call(invocation)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000153
154
Andi-Bogdan Postelnicubebcd6f2018-08-10 11:50:47 +0000155def run_tidy(args, tmpdir, build_path, queue, lock, failed_files):
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000156 """Takes filenames out of queue and runs clang-tidy on them."""
157 while True:
158 name = queue.get()
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000159 invocation = get_tidy_invocation(name, args.clang_tidy_binary, args.checks,
Ehsan Akhgari221ab772017-01-18 17:49:35 +0000160 tmpdir, build_path, args.header_filter,
Ehsan Akhgarib7418d32017-02-09 18:32:02 +0000161 args.extra_arg, args.extra_arg_before,
Julie Hockettc3716ca2018-03-09 23:26:56 +0000162 args.quiet, args.config)
Andi-Bogdan Postelnicubebcd6f2018-08-10 11:50:47 +0000163
164 proc = subprocess.Popen(invocation, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
165 output, err = proc.communicate()
166 if proc.returncode != 0:
Miklos Vajna10fe9bc2018-03-19 14:43:59 +0000167 failed_files.append(name)
Andi-Bogdan Postelnicubebcd6f2018-08-10 11:50:47 +0000168 with lock:
Andi-Bogdan Postelnicu1a056972018-09-19 11:52:20 +0000169 sys.stdout.write(' '.join(invocation) + '\n' + output.decode('utf-8') + '\n')
170 if len(err) > 0:
171 sys.stderr.write(err.decode('utf-8') + '\n')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000172 queue.task_done()
173
174
175def main():
176 parser = argparse.ArgumentParser(description='Runs clang-tidy over all files '
177 'in a compilation database. Requires '
178 'clang-tidy and clang-apply-replacements in '
179 '$PATH.')
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000180 parser.add_argument('-clang-tidy-binary', metavar='PATH',
181 default='clang-tidy',
182 help='path to clang-tidy binary')
183 parser.add_argument('-clang-apply-replacements-binary', metavar='PATH',
184 default='clang-apply-replacements',
185 help='path to clang-apply-replacements binary')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000186 parser.add_argument('-checks', default=None,
187 help='checks filter, when not specified, use clang-tidy '
188 'default')
Julie Hockettc3716ca2018-03-09 23:26:56 +0000189 parser.add_argument('-config', default=None,
190 help='Specifies a configuration in YAML/JSON format: '
191 ' -config="{Checks: \'*\', '
192 ' CheckOptions: [{key: x, '
193 ' value: y}]}" '
194 'When the value is empty, clang-tidy will '
195 'attempt to find a file named .clang-tidy for '
196 'each source file in its parent directories.')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000197 parser.add_argument('-header-filter', default=None,
198 help='regular expression matching the names of the '
199 'headers to output diagnostics from. Diagnostics from '
200 'the main file of each translation unit are always '
201 'displayed.')
Alexander Kornienko16300e12017-07-21 10:31:26 +0000202 parser.add_argument('-export-fixes', metavar='filename', dest='export_fixes',
203 help='Create a yaml file to store suggested fixes in, '
204 'which can be applied with clang-apply-replacements.')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000205 parser.add_argument('-j', type=int, default=0,
206 help='number of tidy instances to be run in parallel.')
207 parser.add_argument('files', nargs='*', default=['.*'],
208 help='files to be processed (regex on path)')
209 parser.add_argument('-fix', action='store_true', help='apply fix-its')
210 parser.add_argument('-format', action='store_true', help='Reformat code '
211 'after applying fixes')
Vassil Vassilevc4c33ce2017-06-09 22:23:03 +0000212 parser.add_argument('-style', default='file', help='The style of reformat '
213 'code after applying fixes')
Guillaume Papin68b59102015-09-28 17:53:04 +0000214 parser.add_argument('-p', dest='build_path',
215 help='Path used to read a compile command database.')
Ehsan Akhgari221ab772017-01-18 17:49:35 +0000216 parser.add_argument('-extra-arg', dest='extra_arg',
217 action='append', default=[],
218 help='Additional argument to append to the compiler '
219 'command line.')
220 parser.add_argument('-extra-arg-before', dest='extra_arg_before',
221 action='append', default=[],
222 help='Additional argument to prepend to the compiler '
223 'command line.')
Ehsan Akhgarib7418d32017-02-09 18:32:02 +0000224 parser.add_argument('-quiet', action='store_true',
225 help='Run clang-tidy in quiet mode')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000226 args = parser.parse_args()
227
Guillaume Papin68b59102015-09-28 17:53:04 +0000228 db_path = 'compile_commands.json'
229
230 if args.build_path is not None:
231 build_path = args.build_path
232 else:
233 # Find our database
234 build_path = find_compilation_database(db_path)
235
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000236 try:
Alexander Kornienkof73fe3a2014-09-22 00:07:07 +0000237 invocation = [args.clang_tidy_binary, '-list-checks']
Guillaume Papin68b59102015-09-28 17:53:04 +0000238 invocation.append('-p=' + build_path)
Alexander Kornienkof73fe3a2014-09-22 00:07:07 +0000239 if args.checks:
Alexander Kornienko3f115382015-09-08 10:31:36 +0000240 invocation.append('-checks=' + args.checks)
Alexander Kornienkof73fe3a2014-09-22 00:07:07 +0000241 invocation.append('-')
Kevin Funk08c2f0f2017-11-28 07:17:01 +0000242 subprocess.check_call(invocation)
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000243 except:
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000244 print("Unable to run clang-tidy.", file=sys.stderr)
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000245 sys.exit(1)
246
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000247 # Load the database and extract all files.
248 database = json.load(open(os.path.join(build_path, db_path)))
Gabor Horvath8de900a2017-11-06 10:36:02 +0000249 files = [make_absolute(entry['file'], entry['directory'])
250 for entry in database]
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000251
252 max_task = args.j
253 if max_task == 0:
254 max_task = multiprocessing.cpu_count()
255
256 tmpdir = None
Alexander Kornienko16300e12017-07-21 10:31:26 +0000257 if args.fix or args.export_fixes:
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000258 check_clang_apply_replacements_binary(args)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000259 tmpdir = tempfile.mkdtemp()
260
261 # Build up a big regexy filter from all command line arguments.
Alexander Kornienkoeaada5c2017-03-23 16:29:39 +0000262 file_name_re = re.compile('|'.join(args.files))
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000263
Miklos Vajna10fe9bc2018-03-19 14:43:59 +0000264 return_code = 0
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000265 try:
266 # Spin up a bunch of tidy-launching threads.
Kevin Funkd331cb62017-09-05 12:36:33 +0000267 task_queue = queue.Queue(max_task)
Miklos Vajna10fe9bc2018-03-19 14:43:59 +0000268 # List of files with a non-zero return code.
269 failed_files = []
Andi-Bogdan Postelnicubebcd6f2018-08-10 11:50:47 +0000270 lock = threading.Lock()
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000271 for _ in range(max_task):
272 t = threading.Thread(target=run_tidy,
Andi-Bogdan Postelnicubebcd6f2018-08-10 11:50:47 +0000273 args=(args, tmpdir, build_path, task_queue, lock, failed_files))
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000274 t.daemon = True
275 t.start()
276
277 # Fill the queue with files.
278 for name in files:
279 if file_name_re.search(name):
Kevin Funkd331cb62017-09-05 12:36:33 +0000280 task_queue.put(name)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000281
282 # Wait for all threads to be done.
Kevin Funkd331cb62017-09-05 12:36:33 +0000283 task_queue.join()
Miklos Vajna10fe9bc2018-03-19 14:43:59 +0000284 if len(failed_files):
285 return_code = 1
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000286
287 except KeyboardInterrupt:
288 # This is a sad hack. Unfortunately subprocess goes
289 # bonkers with ctrl-c and we start forking merrily.
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000290 print('\nCtrl-C detected, goodbye.')
Alexander Kornienko16300e12017-07-21 10:31:26 +0000291 if tmpdir:
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000292 shutil.rmtree(tmpdir)
293 os.kill(0, 9)
294
Alexander Kornienko16300e12017-07-21 10:31:26 +0000295 if args.export_fixes:
296 print('Writing fixes to ' + args.export_fixes + ' ...')
297 try:
298 merge_replacement_files(tmpdir, args.export_fixes)
299 except:
300 print('Error exporting fixes.\n', file=sys.stderr)
301 traceback.print_exc()
302 return_code=1
303
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000304 if args.fix:
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000305 print('Applying fixes ...')
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000306 try:
307 apply_fixes(args, tmpdir)
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000308 except:
309 print('Error applying fixes.\n', file=sys.stderr)
310 traceback.print_exc()
Alexander Kornienko16300e12017-07-21 10:31:26 +0000311 return_code=1
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000312
Alexander Kornienko16300e12017-07-21 10:31:26 +0000313 if tmpdir:
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000314 shutil.rmtree(tmpdir)
Alexander Kornienko16300e12017-07-21 10:31:26 +0000315 sys.exit(return_code)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000316
317if __name__ == '__main__':
318 main()