"""Invoke clang-tidy tool.
Usage: clang_tidy.py file.cc [clang-tidy-args...]
Just a proof of concept!
We use an embedded clang-tidy whose version doesn't match clang++.
"""
import argparse
import os
import shutil
import subprocess
import sys
import tempfile
from presubmit_checks_lib.build_helpers import (GetClangTidyPath,
GetCompilationCommand)
CHECKER_OPTION = '-checks=*'
def Process(filepath, args):
out_dir = tempfile.mkdtemp('clang_tidy')
try:
gn_args = []
command = GetCompilationCommand(filepath, gn_args, out_dir)
command = [
arg for arg in command
if not (arg.startswith('-W') or arg.startswith('-f'))
]
rel_path = os.path.relpath(os.path.abspath(filepath), out_dir)
command[0:1] = [GetClangTidyPath(), CHECKER_OPTION, rel_path
] + args + ['--']
print("Running: %s" % ' '.join(command))
p = subprocess.Popen(command,
cwd=out_dir,
stdout=sys.stdout,
stderr=sys.stderr)
p.communicate()
return p.returncode
finally:
shutil.rmtree(out_dir, ignore_errors=True)
def ValidateCC(filepath):
"""We can only analyze .cc files. Provide explicit message about that."""
if filepath.endswith('.cc'):
return filepath
msg = ('%s not supported.\n'
'For now, we can only analyze translation units (.cc files).' %
filepath)
raise argparse.ArgumentTypeError(msg)
def Main():
description = (
"Run clang-tidy on single cc file.\n"
"Use flags, defines and include paths as in default debug build.\n"
"WARNING, this is a POC version with rough edges.")
parser = argparse.ArgumentParser(description=description)
parser.add_argument('filepath',
help='Specifies the path of the .cc file to analyze.',
type=ValidateCC)
parser.add_argument('args',
nargs=argparse.REMAINDER,
help='Arguments passed to clang-tidy')
parsed_args = parser.parse_args()
return Process(parsed_args.filepath, parsed_args.args)
if __name__ == '__main__':
sys.exit(Main())