blob: b45d714e3fd89880bb9dee35d58ab4de4646e4e1 [file] [log] [blame]
Ed Tanous7d3dba42017-04-05 13:04:39 -07001#!/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
61def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path,
62 header_filter, extra_arg, extra_arg_before, quiet):
63 """Gets a command line for clang-tidy."""
64 start = [clang_tidy_binary]
65 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:
71 start.append('-checks=' + checks)
72 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)
77 os.close(handle)
78 start.append(name)
79 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)
83 start.append('-p=' + build_path)
84 if quiet:
85 start.append('-quiet')
86 start.append(f)
87 return start
88
89
90def apply_fixes(args, tmpdir):
91 """Calls clang-apply-fixes on a given directory. Deletes the dir when done."""
92 invocation = [args.clang_apply_replacements_binary]
93 if args.format:
94 invocation.append('-format')
95 invocation.append(tmpdir)
96 subprocess.call(invocation)
97 shutil.rmtree(tmpdir)
98
99
100def run_tidy(args, tmpdir, build_path, queue):
101 """Takes filenames out of queue and runs clang-tidy on them."""
102 while True:
103 name = queue.get()
104 invocation = get_tidy_invocation(name, args.clang_tidy_binary, args.checks,
105 tmpdir, build_path, args.header_filter,
106 args.extra_arg, args.extra_arg_before,
107 args.quiet)
108 sys.stdout.write(' '.join(invocation) + '\n')
109 subprocess.call(invocation)
110 queue.task_done()
111
112
113def main():
114 parser = argparse.ArgumentParser(description='Runs clang-tidy over all files '
115 'in a compilation database. Requires '
116 'clang-tidy and clang-apply-replacements in '
117 '$PATH.')
118 parser.add_argument('-clang-tidy-binary', metavar='PATH',
119 default='clang-tidy',
120 help='path to clang-tidy binary')
121 parser.add_argument('-clang-apply-replacements-binary', metavar='PATH',
122 default='clang-apply-replacements',
123 help='path to clang-apply-replacements binary')
124 parser.add_argument('-checks', default=None,
125 help='checks filter, when not specified, use clang-tidy '
126 'default')
127 parser.add_argument('-header-filter', default=None,
128 help='regular expression matching the names of the '
129 'headers to output diagnostics from. Diagnostics from '
130 'the main file of each translation unit are always '
131 'displayed.')
132 parser.add_argument('-j', type=int, default=0,
133 help='number of tidy instances to be run in parallel.')
134 parser.add_argument('files', nargs='*', default=['.*'],
135 help='files to be processed (regex on path)')
136 parser.add_argument('-fix', action='store_true', help='apply fix-its')
137 parser.add_argument('-format', action='store_true', help='Reformat code '
138 'after applying fixes')
139 parser.add_argument('-p', dest='build_path',
140 help='Path used to read a compile command database.')
141 parser.add_argument('-extra-arg', dest='extra_arg',
142 action='append', default=[],
143 help='Additional argument to append to the compiler '
144 'command line.')
145 parser.add_argument('-extra-arg-before', dest='extra_arg_before',
146 action='append', default=[],
147 help='Additional argument to prepend to the compiler '
148 'command line.')
149 parser.add_argument('-quiet', action='store_true',
150 help='Run clang-tidy in quiet mode')
151 args = parser.parse_args()
152
153 db_path = 'compile_commands.json'
154
155 if args.build_path is not None:
156 build_path = args.build_path
157 else:
158 # Find our database
159 build_path = find_compilation_database(db_path)
160
161 try:
162 invocation = [args.clang_tidy_binary, '-list-checks']
163 invocation.append('-p=' + build_path)
164 if args.checks:
165 invocation.append('-checks=' + args.checks)
166 invocation.append('-')
167 print subprocess.check_output(invocation)
168 except:
169 print >>sys.stderr, "Unable to run clang-tidy."
170 sys.exit(1)
171
172 # Load the database and extract all files.
173 database = json.load(open(os.path.join(build_path, db_path)))
174 files = [entry['file'] for entry in database]
175
176 max_task = args.j
177 if max_task == 0:
178 max_task = multiprocessing.cpu_count()
179
180 tmpdir = None
181 if args.fix:
182 tmpdir = tempfile.mkdtemp()
183
184 # Build up a big regexy filter from all command line arguments.
185 file_name_re = re.compile('|'.join(args.files))
186
187 try:
188 # Spin up a bunch of tidy-launching threads.
189 queue = Queue.Queue(max_task)
190 for _ in range(max_task):
191 t = threading.Thread(target=run_tidy,
192 args=(args, tmpdir, build_path, queue))
193 t.daemon = True
194 t.start()
195
196 # Fill the queue with files.
197 for name in files:
198 if file_name_re.search(name):
199 queue.put(name)
200
201 # Wait for all threads to be done.
202 queue.join()
203
204 except KeyboardInterrupt:
205 # This is a sad hack. Unfortunately subprocess goes
206 # bonkers with ctrl-c and we start forking merrily.
207 print '\nCtrl-C detected, goodbye.'
208 if args.fix:
209 shutil.rmtree(tmpdir)
210 os.kill(0, 9)
211
212 if args.fix:
213 print 'Applying fixes ...'
214 apply_fixes(args, tmpdir)
215
216if __name__ == '__main__':
217 main()