|
| 1 | +#!/usr/bin/env python |
| 2 | +# |
| 3 | +#===- run-clang-tidy.py - Parallel clang-tidy runner ---------*- python -*--===# |
| 4 | +# |
| 5 | +# 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 |
| 8 | +# |
| 9 | +#===------------------------------------------------------------------------===# |
| 10 | +# FIXME: Integrate with clang-tidy-diff.py |
| 11 | + |
| 12 | +""" |
| 13 | +Parallel clang-tidy runner |
| 14 | +========================== |
| 15 | +
|
| 16 | +Runs clang-tidy over all files in a compilation database. Requires clang-tidy |
| 17 | +and clang-apply-replacements in $PATH. |
| 18 | +
|
| 19 | +Example 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 | +
|
| 32 | +Compilation database setup: |
| 33 | +http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html |
| 34 | +""" |
| 35 | + |
| 36 | +from __future__ import print_function |
| 37 | + |
| 38 | +import argparse |
| 39 | +import glob |
| 40 | +import json |
| 41 | +import multiprocessing |
| 42 | +import os |
| 43 | +import re |
| 44 | +import shutil |
| 45 | +import subprocess |
| 46 | +import sys |
| 47 | +import tempfile |
| 48 | +import threading |
| 49 | +import traceback |
| 50 | + |
| 51 | +try: |
| 52 | + import yaml |
| 53 | +except ImportError: |
| 54 | + yaml = None |
| 55 | + |
| 56 | +is_py2 = sys.version[0] == '2' |
| 57 | + |
| 58 | +if is_py2: |
| 59 | + import Queue as queue |
| 60 | +else: |
| 61 | + import queue as queue |
| 62 | + |
| 63 | + |
| 64 | +def find_compilation_database(path): |
| 65 | + """Adjusts the directory until a compilation database is found.""" |
| 66 | + result = './' |
| 67 | + while not os.path.isfile(os.path.join(result, path)): |
| 68 | + if os.path.realpath(result) == '/': |
| 69 | + print('Error: could not find compilation database.') |
| 70 | + sys.exit(1) |
| 71 | + result += '../' |
| 72 | + return os.path.realpath(result) |
| 73 | + |
| 74 | + |
| 75 | +def make_absolute(f, directory): |
| 76 | + if os.path.isabs(f): |
| 77 | + return f |
| 78 | + return os.path.normpath(os.path.join(directory, f)) |
| 79 | + |
| 80 | + |
| 81 | +def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path, |
| 82 | + header_filter, extra_arg, extra_arg_before, quiet, |
| 83 | + config): |
| 84 | + """Gets a command line for clang-tidy.""" |
| 85 | + start = [clang_tidy_binary] |
| 86 | + if header_filter is not None: |
| 87 | + start.append('-header-filter=' + header_filter) |
| 88 | + if checks: |
| 89 | + start.append('-checks=' + checks) |
| 90 | + if tmpdir is not None: |
| 91 | + start.append('-export-fixes') |
| 92 | + # Get a temporary file. We immediately close the handle so clang-tidy can |
| 93 | + # overwrite it. |
| 94 | + (handle, name) = tempfile.mkstemp(suffix='.yaml', dir=tmpdir) |
| 95 | + os.close(handle) |
| 96 | + start.append(name) |
| 97 | + for arg in extra_arg: |
| 98 | + start.append('-extra-arg=%s' % arg) |
| 99 | + for arg in extra_arg_before: |
| 100 | + start.append('-extra-arg-before=%s' % arg) |
| 101 | + start.append('-p=' + build_path) |
| 102 | + if quiet: |
| 103 | + start.append('-quiet') |
| 104 | + if config: |
| 105 | + start.append('-config=' + config) |
| 106 | + start.append(f) |
| 107 | + return start |
| 108 | + |
| 109 | + |
| 110 | +def merge_replacement_files(tmpdir, mergefile): |
| 111 | + """Merge all replacement files in a directory into a single file""" |
| 112 | + # The fixes suggested by clang-tidy >= 4.0.0 are given under |
| 113 | + # the top level key 'Diagnostics' in the output yaml files |
| 114 | + mergekey = "Diagnostics" |
| 115 | + merged = [] |
| 116 | + for replacefile in glob.iglob(os.path.join(tmpdir, '*.yaml')): |
| 117 | + content = yaml.safe_load(open(replacefile, 'r')) |
| 118 | + if not content: |
| 119 | + continue # Skip empty files. |
| 120 | + merged.extend(content.get(mergekey, [])) |
| 121 | + |
| 122 | + if merged: |
| 123 | + # MainSourceFile: The key is required by the definition inside |
| 124 | + # include/clang/Tooling/ReplacementsYaml.h, but the value |
| 125 | + # is actually never used inside clang-apply-replacements, |
| 126 | + # so we set it to '' here. |
| 127 | + output = {'MainSourceFile': '', mergekey: merged} |
| 128 | + with open(mergefile, 'w') as out: |
| 129 | + yaml.safe_dump(output, out) |
| 130 | + else: |
| 131 | + # Empty the file: |
| 132 | + open(mergefile, 'w').close() |
| 133 | + |
| 134 | + |
| 135 | +def check_clang_apply_replacements_binary(args): |
| 136 | + """Checks if invoking supplied clang-apply-replacements binary works.""" |
| 137 | + try: |
| 138 | + subprocess.check_call( |
| 139 | + [args.clang_apply_replacements_binary, '--version']) |
| 140 | + except: |
| 141 | + print('Unable to run clang-apply-replacements. Is clang-apply-replacements ' |
| 142 | + 'binary correctly specified?', file=sys.stderr) |
| 143 | + traceback.print_exc() |
| 144 | + sys.exit(1) |
| 145 | + |
| 146 | + |
| 147 | +def apply_fixes(args, tmpdir): |
| 148 | + """Calls clang-apply-fixes on a given directory.""" |
| 149 | + invocation = [args.clang_apply_replacements_binary] |
| 150 | + if args.format: |
| 151 | + invocation.append('-format') |
| 152 | + if args.style: |
| 153 | + invocation.append('-style=' + args.style) |
| 154 | + invocation.append(tmpdir) |
| 155 | + subprocess.call(invocation) |
| 156 | + |
| 157 | + |
| 158 | +def run_tidy(args, tmpdir, build_path, queue, lock, failed_files): |
| 159 | + """Takes filenames out of queue and runs clang-tidy on them.""" |
| 160 | + while True: |
| 161 | + name = queue.get() |
| 162 | + invocation = get_tidy_invocation(name, args.clang_tidy_binary, args.checks, |
| 163 | + tmpdir, build_path, args.header_filter, |
| 164 | + args.extra_arg, args.extra_arg_before, |
| 165 | + args.quiet, args.config) |
| 166 | + |
| 167 | + proc = subprocess.Popen( |
| 168 | + invocation, stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 169 | + output, err = proc.communicate() |
| 170 | + if proc.returncode != 0: |
| 171 | + failed_files.append(name) |
| 172 | + with lock: |
| 173 | + sys.stdout.write(' '.join(invocation) + |
| 174 | + '\n' + output.decode('utf-8')) |
| 175 | + if len(err) > 0: |
| 176 | + sys.stdout.flush() |
| 177 | + sys.stderr.write(err.decode('utf-8')) |
| 178 | + queue.task_done() |
| 179 | + |
| 180 | + |
| 181 | +def main(): |
| 182 | + parser = argparse.ArgumentParser(description='Runs clang-tidy over all files ' |
| 183 | + 'in a compilation database. Requires ' |
| 184 | + 'clang-tidy and clang-apply-replacements in ' |
| 185 | + '$PATH.') |
| 186 | + parser.add_argument('-clang-tidy-binary', metavar='PATH', |
| 187 | + default='clang-tidy', |
| 188 | + help='path to clang-tidy binary') |
| 189 | + parser.add_argument('-clang-apply-replacements-binary', metavar='PATH', |
| 190 | + default='clang-apply-replacements', |
| 191 | + help='path to clang-apply-replacements binary') |
| 192 | + parser.add_argument('-checks', default=None, |
| 193 | + help='checks filter, when not specified, use clang-tidy ' |
| 194 | + 'default') |
| 195 | + parser.add_argument('-config', default=None, |
| 196 | + help='Specifies a configuration in YAML/JSON format: ' |
| 197 | + ' -config="{Checks: \'*\', ' |
| 198 | + ' CheckOptions: [{key: x, ' |
| 199 | + ' value: y}]}" ' |
| 200 | + 'When the value is empty, clang-tidy will ' |
| 201 | + 'attempt to find a file named .clang-tidy for ' |
| 202 | + 'each source file in its parent directories.') |
| 203 | + parser.add_argument('-header-filter', default=None, |
| 204 | + help='regular expression matching the names of the ' |
| 205 | + 'headers to output diagnostics from. Diagnostics from ' |
| 206 | + 'the main file of each translation unit are always ' |
| 207 | + 'displayed.') |
| 208 | + if yaml: |
| 209 | + parser.add_argument('-export-fixes', metavar='filename', dest='export_fixes', |
| 210 | + help='Create a yaml file to store suggested fixes in, ' |
| 211 | + 'which can be applied with clang-apply-replacements.') |
| 212 | + parser.add_argument('-j', type=int, default=0, |
| 213 | + help='number of tidy instances to be run in parallel.') |
| 214 | + parser.add_argument('files', nargs='*', default=['.*'], |
| 215 | + help='files to be processed (regex on path)') |
| 216 | + parser.add_argument('-fix', action='store_true', help='apply fix-its') |
| 217 | + parser.add_argument('-format', action='store_true', help='Reformat code ' |
| 218 | + 'after applying fixes') |
| 219 | + parser.add_argument('-style', default='file', help='The style of reformat ' |
| 220 | + 'code after applying fixes') |
| 221 | + parser.add_argument('-p', dest='build_path', |
| 222 | + help='Path used to read a compile command database.') |
| 223 | + parser.add_argument('-extra-arg', dest='extra_arg', |
| 224 | + action='append', default=[], |
| 225 | + help='Additional argument to append to the compiler ' |
| 226 | + 'command line.') |
| 227 | + parser.add_argument('-extra-arg-before', dest='extra_arg_before', |
| 228 | + action='append', default=[], |
| 229 | + help='Additional argument to prepend to the compiler ' |
| 230 | + 'command line.') |
| 231 | + parser.add_argument('-quiet', action='store_true', |
| 232 | + help='Run clang-tidy in quiet mode') |
| 233 | + parser.add_argument('-ignore-files', default=None, |
| 234 | + help='regex describing files to be ignored') |
| 235 | + args = parser.parse_args() |
| 236 | + |
| 237 | + db_path = 'compile_commands.json' |
| 238 | + |
| 239 | + if args.build_path is not None: |
| 240 | + build_path = args.build_path |
| 241 | + else: |
| 242 | + # Find our database |
| 243 | + build_path = find_compilation_database(db_path) |
| 244 | + |
| 245 | + try: |
| 246 | + invocation = [args.clang_tidy_binary, '-list-checks'] |
| 247 | + invocation.append('-p=' + build_path) |
| 248 | + if args.checks: |
| 249 | + invocation.append('-checks=' + args.checks) |
| 250 | + invocation.append('-') |
| 251 | + if args.quiet: |
| 252 | + # Even with -quiet we still want to check if we can call clang-tidy. |
| 253 | + with open(os.devnull, 'w') as dev_null: |
| 254 | + subprocess.check_call(invocation, stdout=dev_null) |
| 255 | + else: |
| 256 | + subprocess.check_call(invocation) |
| 257 | + except: |
| 258 | + print("Unable to run clang-tidy.", file=sys.stderr) |
| 259 | + sys.exit(1) |
| 260 | + |
| 261 | + # Load the database and extract all files. |
| 262 | + database = json.load(open(os.path.join(build_path, db_path))) |
| 263 | + files = [make_absolute(entry['file'], entry['directory']) |
| 264 | + for entry in database] |
| 265 | + |
| 266 | + max_task = args.j |
| 267 | + if max_task == 0: |
| 268 | + max_task = multiprocessing.cpu_count() |
| 269 | + |
| 270 | + tmpdir = None |
| 271 | + if args.fix or (yaml and args.export_fixes): |
| 272 | + check_clang_apply_replacements_binary(args) |
| 273 | + tmpdir = tempfile.mkdtemp() |
| 274 | + |
| 275 | + # Build up a big regexy filter from all command line arguments. |
| 276 | + file_name_re = re.compile('|'.join(args.files)) |
| 277 | + |
| 278 | + return_code = 0 |
| 279 | + try: |
| 280 | + # Spin up a bunch of tidy-launching threads. |
| 281 | + task_queue = queue.Queue(max_task) |
| 282 | + # List of files with a non-zero return code. |
| 283 | + failed_files = [] |
| 284 | + lock = threading.Lock() |
| 285 | + for _ in range(max_task): |
| 286 | + t = threading.Thread(target=run_tidy, |
| 287 | + args=(args, tmpdir, build_path, task_queue, lock, failed_files)) |
| 288 | + t.daemon = True |
| 289 | + t.start() |
| 290 | + |
| 291 | + # Fill the queue with files. |
| 292 | + for name in files: |
| 293 | + if file_name_re.search(name): |
| 294 | + if args.ignore_files: |
| 295 | + ignore_file_re = re.compile(args.ignore_files) |
| 296 | + if ignore_file_re.search(name): |
| 297 | + continue |
| 298 | + task_queue.put(name) |
| 299 | + |
| 300 | + # Wait for all threads to be done. |
| 301 | + task_queue.join() |
| 302 | + if len(failed_files): |
| 303 | + return_code = 1 |
| 304 | + |
| 305 | + except KeyboardInterrupt: |
| 306 | + # This is a sad hack. Unfortunately subprocess goes |
| 307 | + # bonkers with ctrl-c and we start forking merrily. |
| 308 | + print('\nCtrl-C detected, goodbye.') |
| 309 | + if tmpdir: |
| 310 | + shutil.rmtree(tmpdir) |
| 311 | + os.kill(0, 9) |
| 312 | + |
| 313 | + if yaml and args.export_fixes: |
| 314 | + print('Writing fixes to ' + args.export_fixes + ' ...') |
| 315 | + try: |
| 316 | + merge_replacement_files(tmpdir, args.export_fixes) |
| 317 | + except: |
| 318 | + print('Error exporting fixes.\n', file=sys.stderr) |
| 319 | + traceback.print_exc() |
| 320 | + return_code = 1 |
| 321 | + |
| 322 | + if args.fix: |
| 323 | + print('Applying fixes ...') |
| 324 | + try: |
| 325 | + apply_fixes(args, tmpdir) |
| 326 | + except: |
| 327 | + print('Error applying fixes.\n', file=sys.stderr) |
| 328 | + traceback.print_exc() |
| 329 | + return_code = 1 |
| 330 | + |
| 331 | + if tmpdir: |
| 332 | + shutil.rmtree(tmpdir) |
| 333 | + sys.exit(return_code) |
| 334 | + |
| 335 | + |
| 336 | +if __name__ == '__main__': |
| 337 | + main() |
0 commit comments