blob: 24303122be0c4b8e96ecb325d0a84f999ab12499 [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
Kevin Funkd331cb62017-09-05 12:36:33 +000038
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000039import argparse
Alexander Kornienko16300e12017-07-21 10:31:26 +000040import glob
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000041import json
42import multiprocessing
43import os
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000044import 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
Kevin Funkd331cb62017-09-05 12:36:33 +000053is_py2 = sys.version[0] == '2'
54
55if is_py2:
56 import Queue as queue
57else:
58 import queue as queue
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000059
60def find_compilation_database(path):
61 """Adjusts the directory until a compilation database is found."""
62 result = './'
63 while not os.path.isfile(os.path.join(result, path)):
64 if os.path.realpath(result) == '/':
Jakub Kuderskia7410fd2017-04-25 22:38:39 +000065 print('Error: could not find compilation database.')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000066 sys.exit(1)
67 result += '../'
68 return os.path.realpath(result)
69
70
Gabor Horvath8de900a2017-11-06 10:36:02 +000071def make_absolute(f, directory):
72 if os.path.isabs(f):
73 return f
74 return os.path.normpath(os.path.join(directory, f))
75
76
Benjamin Kramer815dbad2014-09-08 14:56:40 +000077def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path,
Julie Hockettc3716ca2018-03-09 23:26:56 +000078 header_filter, extra_arg, extra_arg_before, quiet,
79 config):
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000080 """Gets a command line for clang-tidy."""
Benjamin Kramer815dbad2014-09-08 14:56:40 +000081 start = [clang_tidy_binary]
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000082 if header_filter is not None:
83 start.append('-header-filter=' + header_filter)
84 else:
85 # Show warnings in all in-project headers by default.
86 start.append('-header-filter=^' + build_path + '/.*')
87 if checks:
Alexander Kornienko3f115382015-09-08 10:31:36 +000088 start.append('-checks=' + checks)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000089 if tmpdir is not None:
90 start.append('-export-fixes')
91 # Get a temporary file. We immediately close the handle so clang-tidy can
92 # overwrite it.
93 (handle, name) = tempfile.mkstemp(suffix='.yaml', dir=tmpdir)
Benjamin Kramer815dbad2014-09-08 14:56:40 +000094 os.close(handle)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000095 start.append(name)
Ehsan Akhgari221ab772017-01-18 17:49:35 +000096 for arg in extra_arg:
97 start.append('-extra-arg=%s' % arg)
98 for arg in extra_arg_before:
99 start.append('-extra-arg-before=%s' % arg)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000100 start.append('-p=' + build_path)
Ehsan Akhgarib7418d32017-02-09 18:32:02 +0000101 if quiet:
102 start.append('-quiet')
Julie Hockettc3716ca2018-03-09 23:26:56 +0000103 if config:
104 start.append('-config=' + config)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000105 start.append(f)
106 return start
107
108
Alexander Kornienko16300e12017-07-21 10:31:26 +0000109def merge_replacement_files(tmpdir, mergefile):
110 """Merge all replacement files in a directory into a single file"""
111 # The fixes suggested by clang-tidy >= 4.0.0 are given under
112 # the top level key 'Diagnostics' in the output yaml files
113 mergekey="Diagnostics"
114 merged=[]
115 for replacefile in glob.iglob(os.path.join(tmpdir, '*.yaml')):
116 content = yaml.safe_load(open(replacefile, 'r'))
117 if not content:
118 continue # Skip empty files.
119 merged.extend(content.get(mergekey, []))
120
121 if merged:
122 # MainSourceFile: The key is required by the definition inside
123 # include/clang/Tooling/ReplacementsYaml.h, but the value
124 # is actually never used inside clang-apply-replacements,
125 # so we set it to '' here.
126 output = { 'MainSourceFile': '', mergekey: merged }
127 with open(mergefile, 'w') as out:
128 yaml.safe_dump(output, out)
129 else:
130 # Empty the file:
131 open(mergefile, 'w').close()
132
133
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000134def check_clang_apply_replacements_binary(args):
135 """Checks if invoking supplied clang-apply-replacements binary works."""
136 try:
137 subprocess.check_call([args.clang_apply_replacements_binary, '--version'])
138 except:
139 print('Unable to run clang-apply-replacements. Is clang-apply-replacements '
140 'binary correctly specified?', file=sys.stderr)
141 traceback.print_exc()
142 sys.exit(1)
143
144
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000145def apply_fixes(args, tmpdir):
Alexander Kornienko16300e12017-07-21 10:31:26 +0000146 """Calls clang-apply-fixes on a given directory."""
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000147 invocation = [args.clang_apply_replacements_binary]
148 if args.format:
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000149 invocation.append('-format')
Vassil Vassilevc4c33ce2017-06-09 22:23:03 +0000150 if args.style:
151 invocation.append('-style=' + args.style)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000152 invocation.append(tmpdir)
153 subprocess.call(invocation)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000154
155
156def run_tidy(args, tmpdir, build_path, queue):
157 """Takes filenames out of queue and runs clang-tidy on them."""
158 while True:
159 name = queue.get()
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000160 invocation = get_tidy_invocation(name, args.clang_tidy_binary, args.checks,
Ehsan Akhgari221ab772017-01-18 17:49:35 +0000161 tmpdir, build_path, args.header_filter,
Ehsan Akhgarib7418d32017-02-09 18:32:02 +0000162 args.extra_arg, args.extra_arg_before,
Julie Hockettc3716ca2018-03-09 23:26:56 +0000163 args.quiet, args.config)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000164 sys.stdout.write(' '.join(invocation) + '\n')
165 subprocess.call(invocation)
166 queue.task_done()
167
168
169def main():
170 parser = argparse.ArgumentParser(description='Runs clang-tidy over all files '
171 'in a compilation database. Requires '
172 'clang-tidy and clang-apply-replacements in '
173 '$PATH.')
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000174 parser.add_argument('-clang-tidy-binary', metavar='PATH',
175 default='clang-tidy',
176 help='path to clang-tidy binary')
177 parser.add_argument('-clang-apply-replacements-binary', metavar='PATH',
178 default='clang-apply-replacements',
179 help='path to clang-apply-replacements binary')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000180 parser.add_argument('-checks', default=None,
181 help='checks filter, when not specified, use clang-tidy '
182 'default')
Julie Hockettc3716ca2018-03-09 23:26:56 +0000183 parser.add_argument('-config', default=None,
184 help='Specifies a configuration in YAML/JSON format: '
185 ' -config="{Checks: \'*\', '
186 ' CheckOptions: [{key: x, '
187 ' value: y}]}" '
188 'When the value is empty, clang-tidy will '
189 'attempt to find a file named .clang-tidy for '
190 'each source file in its parent directories.')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000191 parser.add_argument('-header-filter', default=None,
192 help='regular expression matching the names of the '
193 'headers to output diagnostics from. Diagnostics from '
194 'the main file of each translation unit are always '
195 'displayed.')
Alexander Kornienko16300e12017-07-21 10:31:26 +0000196 parser.add_argument('-export-fixes', metavar='filename', dest='export_fixes',
197 help='Create a yaml file to store suggested fixes in, '
198 'which can be applied with clang-apply-replacements.')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000199 parser.add_argument('-j', type=int, default=0,
200 help='number of tidy instances to be run in parallel.')
201 parser.add_argument('files', nargs='*', default=['.*'],
202 help='files to be processed (regex on path)')
203 parser.add_argument('-fix', action='store_true', help='apply fix-its')
204 parser.add_argument('-format', action='store_true', help='Reformat code '
205 'after applying fixes')
Vassil Vassilevc4c33ce2017-06-09 22:23:03 +0000206 parser.add_argument('-style', default='file', help='The style of reformat '
207 'code after applying fixes')
Guillaume Papin68b59102015-09-28 17:53:04 +0000208 parser.add_argument('-p', dest='build_path',
209 help='Path used to read a compile command database.')
Ehsan Akhgari221ab772017-01-18 17:49:35 +0000210 parser.add_argument('-extra-arg', dest='extra_arg',
211 action='append', default=[],
212 help='Additional argument to append to the compiler '
213 'command line.')
214 parser.add_argument('-extra-arg-before', dest='extra_arg_before',
215 action='append', default=[],
216 help='Additional argument to prepend to the compiler '
217 'command line.')
Ehsan Akhgarib7418d32017-02-09 18:32:02 +0000218 parser.add_argument('-quiet', action='store_true',
219 help='Run clang-tidy in quiet mode')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000220 args = parser.parse_args()
221
Guillaume Papin68b59102015-09-28 17:53:04 +0000222 db_path = 'compile_commands.json'
223
224 if args.build_path is not None:
225 build_path = args.build_path
226 else:
227 # Find our database
228 build_path = find_compilation_database(db_path)
229
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000230 try:
Alexander Kornienkof73fe3a2014-09-22 00:07:07 +0000231 invocation = [args.clang_tidy_binary, '-list-checks']
Guillaume Papin68b59102015-09-28 17:53:04 +0000232 invocation.append('-p=' + build_path)
Alexander Kornienkof73fe3a2014-09-22 00:07:07 +0000233 if args.checks:
Alexander Kornienko3f115382015-09-08 10:31:36 +0000234 invocation.append('-checks=' + args.checks)
Alexander Kornienkof73fe3a2014-09-22 00:07:07 +0000235 invocation.append('-')
Kevin Funk08c2f0f2017-11-28 07:17:01 +0000236 subprocess.check_call(invocation)
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000237 except:
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000238 print("Unable to run clang-tidy.", file=sys.stderr)
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000239 sys.exit(1)
240
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000241 # Load the database and extract all files.
242 database = json.load(open(os.path.join(build_path, db_path)))
Gabor Horvath8de900a2017-11-06 10:36:02 +0000243 files = [make_absolute(entry['file'], entry['directory'])
244 for entry in database]
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000245
246 max_task = args.j
247 if max_task == 0:
248 max_task = multiprocessing.cpu_count()
249
250 tmpdir = None
Alexander Kornienko16300e12017-07-21 10:31:26 +0000251 if args.fix or args.export_fixes:
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000252 check_clang_apply_replacements_binary(args)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000253 tmpdir = tempfile.mkdtemp()
254
255 # Build up a big regexy filter from all command line arguments.
Alexander Kornienkoeaada5c2017-03-23 16:29:39 +0000256 file_name_re = re.compile('|'.join(args.files))
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000257
258 try:
259 # Spin up a bunch of tidy-launching threads.
Kevin Funkd331cb62017-09-05 12:36:33 +0000260 task_queue = queue.Queue(max_task)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000261 for _ in range(max_task):
262 t = threading.Thread(target=run_tidy,
Kevin Funkd331cb62017-09-05 12:36:33 +0000263 args=(args, tmpdir, build_path, task_queue))
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000264 t.daemon = True
265 t.start()
266
267 # Fill the queue with files.
268 for name in files:
269 if file_name_re.search(name):
Kevin Funkd331cb62017-09-05 12:36:33 +0000270 task_queue.put(name)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000271
272 # Wait for all threads to be done.
Kevin Funkd331cb62017-09-05 12:36:33 +0000273 task_queue.join()
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000274
275 except KeyboardInterrupt:
276 # This is a sad hack. Unfortunately subprocess goes
277 # bonkers with ctrl-c and we start forking merrily.
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000278 print('\nCtrl-C detected, goodbye.')
Alexander Kornienko16300e12017-07-21 10:31:26 +0000279 if tmpdir:
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000280 shutil.rmtree(tmpdir)
281 os.kill(0, 9)
282
Alexander Kornienko16300e12017-07-21 10:31:26 +0000283 return_code = 0
284 if args.export_fixes:
285 print('Writing fixes to ' + args.export_fixes + ' ...')
286 try:
287 merge_replacement_files(tmpdir, args.export_fixes)
288 except:
289 print('Error exporting fixes.\n', file=sys.stderr)
290 traceback.print_exc()
291 return_code=1
292
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000293 if args.fix:
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000294 print('Applying fixes ...')
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000295 try:
296 apply_fixes(args, tmpdir)
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000297 except:
298 print('Error applying fixes.\n', file=sys.stderr)
299 traceback.print_exc()
Alexander Kornienko16300e12017-07-21 10:31:26 +0000300 return_code=1
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000301
Alexander Kornienko16300e12017-07-21 10:31:26 +0000302 if tmpdir:
Jakub Kuderskia7410fd2017-04-25 22:38:39 +0000303 shutil.rmtree(tmpdir)
Alexander Kornienko16300e12017-07-21 10:31:26 +0000304 sys.exit(return_code)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000305
306if __name__ == '__main__':
307 main()