Advertisement
Guest User

clang-tidy-improved

a guest
Mar 19th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.47 KB | None | 0 0
  1. #!/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. """
  14. Parallel clang-tidy runner
  15. ==========================
  16.  
  17. Runs clang-tidy over all files in a compilation database. Requires clang-tidy
  18. and clang-apply-replacements in $PATH.
  19.  
  20. Example 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.  
  33. Compilation database setup:
  34. http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
  35. """
  36.  
  37. from __future__ import print_function
  38.  
  39. import argparse
  40. import glob
  41. import json
  42. import multiprocessing
  43. import os
  44. import re
  45. import shutil
  46. import subprocess
  47. import sys
  48. import tempfile
  49. import threading
  50. import traceback
  51. import yaml
  52.  
  53. is_py2 = sys.version[0] == '2'
  54.  
  55. if is_py2:
  56.     import Queue as queue
  57. else:
  58.     import queue as queue
  59.  
  60. def 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) == '/':
  65.       print('Error: could not find compilation database.')
  66.       sys.exit(1)
  67.     result += '../'
  68.   return os.path.realpath(result)
  69.  
  70.  
  71. def 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.  
  77. def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path,
  78.                         header_filter, extra_arg, extra_arg_before, quiet):
  79.   """Gets a command line for clang-tidy."""
  80.   start = [clang_tidy_binary]
  81.   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:
  87.     start.append('-checks=' + checks)
  88.   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)
  93.     os.close(handle)
  94.     start.append(name)
  95.   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)
  99.   start.append('-p=' + build_path)
  100.   if quiet:
  101.       start.append('-quiet')
  102.   start.append(f)
  103.   return start
  104.  
  105.  
  106. def merge_replacement_files(tmpdir, mergefile):
  107.   """Merge all replacement files in a directory into a single file"""
  108.   # The fixes suggested by clang-tidy >= 4.0.0 are given under
  109.   # the top level key 'Diagnostics' in the output yaml files
  110.   mergekey="Diagnostics"
  111.   merged=[]
  112.   for replacefile in glob.iglob(os.path.join(tmpdir, '*.yaml')):
  113.     content = yaml.safe_load(open(replacefile, 'r'))
  114.     if not content:
  115.       continue # Skip empty files.
  116.     merged.extend(content.get(mergekey, []))
  117.  
  118.   if merged:
  119.     # MainSourceFile: The key is required by the definition inside
  120.     # include/clang/Tooling/ReplacementsYaml.h, but the value
  121.     # is actually never used inside clang-apply-replacements,
  122.     # so we set it to '' here.
  123.     output = { 'MainSourceFile': '', mergekey: merged }
  124.  
  125.     # Eliminate duplicates
  126.     diagnostics = output['Diagnostics']
  127.     cleaned = {}
  128.     for x in diagnostics:
  129.         cleaned[(x['FilePath'], x['FileOffset'], x['DiagnosticName'])] = x
  130.     output['Diagnostics']=[x for x in cleaned.values()]
  131.  
  132.     with open(mergefile, 'w') as out:
  133.       yaml.safe_dump(output, out)
  134.   else:
  135.     # Empty the file:
  136.     open(mergefile, 'w').close()
  137.  
  138.  
  139. def check_clang_apply_replacements_binary(args):
  140.   """Checks if invoking supplied clang-apply-replacements binary works."""
  141.   try:
  142.     subprocess.check_call([args.clang_apply_replacements_binary, '--version'])
  143.   except:
  144.     print('Unable to run clang-apply-replacements. Is clang-apply-replacements '
  145.           'binary correctly specified?', file=sys.stderr)
  146.     traceback.print_exc()
  147.     sys.exit(1)
  148.  
  149.  
  150. def apply_fixes(args, tmpdir):
  151.   """Calls clang-apply-fixes on a given directory."""
  152.   invocation = [args.clang_apply_replacements_binary]
  153.   if args.format:
  154.     invocation.append('-format')
  155.   if args.style:
  156.     invocation.append('-style=' + args.style)
  157.   invocation.append(tmpdir)
  158.   subprocess.call(invocation)
  159.  
  160.  
  161. def run_tidy(args, tmpdir, build_path, queue):
  162.   """Takes filenames out of queue and runs clang-tidy on them."""
  163.   while True:
  164.     name = queue.get()
  165.     invocation = get_tidy_invocation(name, args.clang_tidy_binary, args.checks,
  166.                                      tmpdir, build_path, args.header_filter,
  167.                                      args.extra_arg, args.extra_arg_before,
  168.                                      args.quiet)
  169.     #sys.stdout.write(' '.join(invocation) + '\n')
  170.     sys.stdout.write("%s ...\n" % ( name ))
  171.     subprocess.call(invocation)
  172.     sys.stdout.write("%s done\n" % ( name ))
  173.     queue.task_done()
  174.  
  175.  
  176. def main():
  177.   parser = argparse.ArgumentParser(description='Runs clang-tidy over all files '
  178.                                    'in a compilation database. Requires '
  179.                                    'clang-tidy and clang-apply-replacements in '
  180.                                    '$PATH.')
  181.   parser.add_argument('-clang-tidy-binary', metavar='PATH',
  182.                       default='clang-tidy',
  183.                       help='path to clang-tidy binary')
  184.   parser.add_argument('-clang-apply-replacements-binary', metavar='PATH',
  185.                       default='clang-apply-replacements',
  186.                       help='path to clang-apply-replacements binary')
  187.   parser.add_argument('-checks', default=None,
  188.                       help='checks filter, when not specified, use clang-tidy '
  189.                       'default')
  190.   parser.add_argument('-header-filter', default=None,
  191.                       help='regular expression matching the names of the '
  192.                       'headers to output diagnostics from. Diagnostics from '
  193.                       'the main file of each translation unit are always '
  194.                       'displayed.')
  195.   parser.add_argument('-target-filter', default=None,
  196.                       help='regular expression matching the names of the '
  197.                       'cmake targets to output diagnostics from.')
  198.   parser.add_argument('-export-fixes', metavar='filename', dest='export_fixes',
  199.                       help='Create a yaml file to store suggested fixes in, '
  200.                       'which can be applied with clang-apply-replacements.')
  201.   parser.add_argument('-j', type=int, default=0,
  202.                       help='number of tidy instances to be run in parallel.')
  203.   parser.add_argument('files', nargs='*', default=['.*'],
  204.                       help='files to be processed (regex on path)')
  205.   parser.add_argument('-fix', action='store_true', help='apply fix-its')
  206.   parser.add_argument('-format', action='store_true', help='Reformat code '
  207.                       'after applying fixes')
  208.   parser.add_argument('-style', default='file', help='The style of reformat '
  209.                       'code after applying fixes')
  210.   parser.add_argument('-p', dest='build_path',
  211.                       help='Path used to read a compile command database.')
  212.   parser.add_argument('-extra-arg', dest='extra_arg',
  213.                       action='append', default=[],
  214.                       help='Additional argument to append to the compiler '
  215.                       'command line.')
  216.   parser.add_argument('-extra-arg-before', dest='extra_arg_before',
  217.                       action='append', default=[],
  218.                       help='Additional argument to prepend to the compiler '
  219.                       'command line.')
  220.   parser.add_argument('-quiet', action='store_true',
  221.                       help='Run clang-tidy in quiet mode')
  222.   args = parser.parse_args()
  223.  
  224.   db_path = 'compile_commands.json'
  225.  
  226.   if args.build_path is not None:
  227.     build_path = args.build_path
  228.   else:
  229.     # Find our database
  230.     build_path = find_compilation_database(db_path)
  231.  
  232.   try:
  233.     invocation = [args.clang_tidy_binary, '-list-checks']
  234.     invocation.append('-p=' + build_path)
  235.     if args.checks:
  236.       invocation.append('-checks=' + args.checks)
  237.     invocation.append('-')
  238.     subprocess.check_call(invocation)
  239.   except:
  240.     print("Unable to run clang-tidy.", file=sys.stderr)
  241.     sys.exit(1)
  242.  
  243.   # Load the database and extract all files.
  244.   database = json.load(open(os.path.join(build_path, db_path)))
  245.   if args.target_filter is not None:
  246.     fullFilter = '-o CMakeFiles.(' + args.target_filter + ').dir'
  247.     print("Filter: %s" % (fullFilter))
  248.     target_filter_re = re.compile(fullFilter)
  249.     database2 = [entry for entry in database if target_filter_re.search(entry['command'])]
  250.     print("After -target-filter %s, there are %i targets to be processed" % (args.target_filter, len(database2)))
  251.   # Filter out -fconcepts
  252.   for x in range(0, len(database2)):
  253.     database2[x]['command'] = database2[x]['command'].replace('-fconcepts', '')
  254.     #print(database2[x])
  255.   #if database != database2:
  256.   #  json.dump(database2, open(os.path.join(build_path, db_path), 'wt'))
  257.  
  258.   database = database2
  259.   files = [make_absolute(entry['file'], entry['directory'])
  260.            for entry in database]
  261.  
  262.   max_task = args.j
  263.   if max_task == 0:
  264.     max_task = multiprocessing.cpu_count()
  265.  
  266.   tmpdir = None
  267.   if args.fix or args.export_fixes:
  268.     tmpdir = tempfile.mkdtemp()
  269.   if args.fix:
  270.     check_clang_apply_replacements_binary(args)
  271.  
  272.   # Build up a big regexy filter from all command line arguments.
  273.   file_name_re = re.compile('|'.join(args.files))
  274.  
  275.   try:
  276.     # Spin up a bunch of tidy-launching threads.
  277.     task_queue = queue.Queue(max_task)
  278.     for _ in range(max_task):
  279.       t = threading.Thread(target=run_tidy,
  280.                            args=(args, tmpdir, build_path, task_queue))
  281.       t.daemon = True
  282.       t.start()
  283.  
  284.     # Fill the queue with files.
  285.     for name in files:
  286.       if file_name_re.search(name):
  287.         task_queue.put(name)
  288.  
  289.     # Wait for all threads to be done.
  290.     task_queue.join()
  291.  
  292.   except KeyboardInterrupt:
  293.     # This is a sad hack. Unfortunately subprocess goes
  294.     # bonkers with ctrl-c and we start forking merrily.
  295.     print('\nCtrl-C detected, goodbye.')
  296.     if tmpdir:
  297.       shutil.rmtree(tmpdir)
  298.     os.kill(0, 9)
  299.  
  300.   return_code = 0
  301.   if args.export_fixes:
  302.     print('Writing fixes to ' + args.export_fixes + ' ...')
  303.     try:
  304.       merge_replacement_files(tmpdir, args.export_fixes)
  305.     except:
  306.       print('Error exporting fixes.\n', file=sys.stderr)
  307.       traceback.print_exc()
  308.       return_code=1
  309.  
  310.   if args.fix:
  311.     print('Applying fixes ...')
  312.     try:
  313.       apply_fixes(args, tmpdir)
  314.     except:
  315.       print('Error applying fixes.\n', file=sys.stderr)
  316.       traceback.print_exc()
  317.       return_code=1
  318.  
  319.   if tmpdir:
  320.     shutil.rmtree(tmpdir)
  321.   sys.exit(return_code)
  322.  
  323. if __name__ == '__main__':
  324.   main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement