blob: 698948d197c38b26543b8140047810e967be44fc [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
37import argparse
38import json
39import multiprocessing
40import os
41import Queue
42import re
43import shutil
44import subprocess
45import sys
46import tempfile
47import threading
48
49
50def find_compilation_database(path):
51 """Adjusts the directory until a compilation database is found."""
52 result = './'
53 while not os.path.isfile(os.path.join(result, path)):
54 if os.path.realpath(result) == '/':
55 print 'Error: could not find compilation database.'
56 sys.exit(1)
57 result += '../'
58 return os.path.realpath(result)
59
60
Benjamin Kramer815dbad2014-09-08 14:56:40 +000061def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path,
Ehsan Akhgari221ab772017-01-18 17:49:35 +000062 header_filter, extra_arg, extra_arg_before):
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000063 """Gets a command line for clang-tidy."""
Benjamin Kramer815dbad2014-09-08 14:56:40 +000064 start = [clang_tidy_binary]
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000065 if header_filter is not None:
66 start.append('-header-filter=' + header_filter)
67 else:
68 # Show warnings in all in-project headers by default.
69 start.append('-header-filter=^' + build_path + '/.*')
70 if checks:
Alexander Kornienko3f115382015-09-08 10:31:36 +000071 start.append('-checks=' + checks)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000072 if tmpdir is not None:
73 start.append('-export-fixes')
74 # Get a temporary file. We immediately close the handle so clang-tidy can
75 # overwrite it.
76 (handle, name) = tempfile.mkstemp(suffix='.yaml', dir=tmpdir)
Benjamin Kramer815dbad2014-09-08 14:56:40 +000077 os.close(handle)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000078 start.append(name)
Ehsan Akhgari221ab772017-01-18 17:49:35 +000079 for arg in extra_arg:
80 start.append('-extra-arg=%s' % arg)
81 for arg in extra_arg_before:
82 start.append('-extra-arg-before=%s' % arg)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000083 start.append('-p=' + build_path)
84 start.append(f)
85 return start
86
87
Benjamin Kramer815dbad2014-09-08 14:56:40 +000088def apply_fixes(args, tmpdir):
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000089 """Calls clang-apply-fixes on a given directory. Deletes the dir when done."""
Benjamin Kramer815dbad2014-09-08 14:56:40 +000090 invocation = [args.clang_apply_replacements_binary]
91 if args.format:
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +000092 invocation.append('-format')
93 invocation.append(tmpdir)
94 subprocess.call(invocation)
95 shutil.rmtree(tmpdir)
96
97
98def run_tidy(args, tmpdir, build_path, queue):
99 """Takes filenames out of queue and runs clang-tidy on them."""
100 while True:
101 name = queue.get()
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000102 invocation = get_tidy_invocation(name, args.clang_tidy_binary, args.checks,
Ehsan Akhgari221ab772017-01-18 17:49:35 +0000103 tmpdir, build_path, args.header_filter,
104 args.extra_arg, args.extra_arg_before)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000105 sys.stdout.write(' '.join(invocation) + '\n')
106 subprocess.call(invocation)
107 queue.task_done()
108
109
110def main():
111 parser = argparse.ArgumentParser(description='Runs clang-tidy over all files '
112 'in a compilation database. Requires '
113 'clang-tidy and clang-apply-replacements in '
114 '$PATH.')
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000115 parser.add_argument('-clang-tidy-binary', metavar='PATH',
116 default='clang-tidy',
117 help='path to clang-tidy binary')
118 parser.add_argument('-clang-apply-replacements-binary', metavar='PATH',
119 default='clang-apply-replacements',
120 help='path to clang-apply-replacements binary')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000121 parser.add_argument('-checks', default=None,
122 help='checks filter, when not specified, use clang-tidy '
123 'default')
124 parser.add_argument('-header-filter', default=None,
125 help='regular expression matching the names of the '
126 'headers to output diagnostics from. Diagnostics from '
127 'the main file of each translation unit are always '
128 'displayed.')
129 parser.add_argument('-j', type=int, default=0,
130 help='number of tidy instances to be run in parallel.')
131 parser.add_argument('files', nargs='*', default=['.*'],
132 help='files to be processed (regex on path)')
133 parser.add_argument('-fix', action='store_true', help='apply fix-its')
134 parser.add_argument('-format', action='store_true', help='Reformat code '
135 'after applying fixes')
Guillaume Papin68b59102015-09-28 17:53:04 +0000136 parser.add_argument('-p', dest='build_path',
137 help='Path used to read a compile command database.')
Ehsan Akhgari221ab772017-01-18 17:49:35 +0000138 parser.add_argument('-extra-arg', dest='extra_arg',
139 action='append', default=[],
140 help='Additional argument to append to the compiler '
141 'command line.')
142 parser.add_argument('-extra-arg-before', dest='extra_arg_before',
143 action='append', default=[],
144 help='Additional argument to prepend to the compiler '
145 'command line.')
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000146 args = parser.parse_args()
147
Guillaume Papin68b59102015-09-28 17:53:04 +0000148 db_path = 'compile_commands.json'
149
150 if args.build_path is not None:
151 build_path = args.build_path
152 else:
153 # Find our database
154 build_path = find_compilation_database(db_path)
155
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000156 try:
Alexander Kornienkof73fe3a2014-09-22 00:07:07 +0000157 invocation = [args.clang_tidy_binary, '-list-checks']
Guillaume Papin68b59102015-09-28 17:53:04 +0000158 invocation.append('-p=' + build_path)
Alexander Kornienkof73fe3a2014-09-22 00:07:07 +0000159 if args.checks:
Alexander Kornienko3f115382015-09-08 10:31:36 +0000160 invocation.append('-checks=' + args.checks)
Alexander Kornienkof73fe3a2014-09-22 00:07:07 +0000161 invocation.append('-')
162 print subprocess.check_output(invocation)
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000163 except:
164 print >>sys.stderr, "Unable to run clang-tidy."
165 sys.exit(1)
166
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000167 # Load the database and extract all files.
168 database = json.load(open(os.path.join(build_path, db_path)))
169 files = [entry['file'] for entry in database]
170
171 max_task = args.j
172 if max_task == 0:
173 max_task = multiprocessing.cpu_count()
174
175 tmpdir = None
176 if args.fix:
177 tmpdir = tempfile.mkdtemp()
178
179 # Build up a big regexy filter from all command line arguments.
180 file_name_re = re.compile('(' + ')|('.join(args.files) + ')')
181
182 try:
183 # Spin up a bunch of tidy-launching threads.
184 queue = Queue.Queue(max_task)
185 for _ in range(max_task):
186 t = threading.Thread(target=run_tidy,
187 args=(args, tmpdir, build_path, queue))
188 t.daemon = True
189 t.start()
190
191 # Fill the queue with files.
192 for name in files:
193 if file_name_re.search(name):
194 queue.put(name)
195
196 # Wait for all threads to be done.
197 queue.join()
198
199 except KeyboardInterrupt:
200 # This is a sad hack. Unfortunately subprocess goes
201 # bonkers with ctrl-c and we start forking merrily.
202 print '\nCtrl-C detected, goodbye.'
203 if args.fix:
204 shutil.rmtree(tmpdir)
205 os.kill(0, 9)
206
207 if args.fix:
208 print 'Applying fixes ...'
Benjamin Kramer815dbad2014-09-08 14:56:40 +0000209 apply_fixes(args, tmpdir)
Benjamin Kramera9d9a4d2014-09-08 14:01:31 +0000210
211if __name__ == '__main__':
212 main()