| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright 2019 The Meson development team |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
import argparse |
| 7 |
import subprocess |
| 8 |
from pathlib import Path |
| 9 |
import tempfile |
| 10 |
import os |
| 11 |
import shutil |
| 12 |
import sys |
| 13 |
|
| 14 |
from .run_tool import run_with_buffered_output, run_clang_tool_on_sources |
| 15 |
from ..tooldetect import detect_clangtidy, detect_clangapply |
| 16 |
import typing as T |
| 17 |
|
| 18 |
async def run_clang_tidy(fname: Path, tidyexe: list, builddir: Path, fixesdir: T.Optional[Path]) -> int: |
| 19 |
args = [] |
| 20 |
if fixesdir is not None: |
| 21 |
handle, name = tempfile.mkstemp(prefix=fname.name + '.', suffix='.yaml', dir=fixesdir) |
| 22 |
os.close(handle) |
| 23 |
args.extend(['-export-fixes', name]) |
| 24 |
return await run_with_buffered_output(tidyexe + args + ['-quiet', '-p', str(builddir), str(fname)]) |
| 25 |
|
| 26 |
def run(args: T.List[str]) -> int: |
| 27 |
parser = argparse.ArgumentParser() |
| 28 |
parser.add_argument('--fix', action='store_true') |
| 29 |
parser.add_argument('--color', default='always') |
| 30 |
parser.add_argument('sourcedir') |
| 31 |
parser.add_argument('builddir') |
| 32 |
options = parser.parse_args(args) |
| 33 |
|
| 34 |
srcdir = Path(options.sourcedir) |
| 35 |
builddir = Path(options.builddir) |
| 36 |
|
| 37 |
tidyexe = detect_clangtidy() |
| 38 |
if not tidyexe: |
| 39 |
print(f'Could not execute clang-tidy "{" ".join(tidyexe)}"') |
| 40 |
return 1 |
| 41 |
|
| 42 |
if options.color == 'always' or options.color == 'auto' and sys.stdout.isatty(): |
| 43 |
tidyexe += ['--use-color'] |
| 44 |
|
| 45 |
fixesdir: T.Optional[Path] = None |
| 46 |
if options.fix: |
| 47 |
applyexe = detect_clangapply() |
| 48 |
if not applyexe: |
| 49 |
print(f'Could not execute clang-apply-replacements "{" ".join(applyexe)}"') |
| 50 |
return 1 |
| 51 |
|
| 52 |
fixesdir = builddir / 'meson-private' / 'clang-tidy-fix' |
| 53 |
if fixesdir.is_dir(): |
| 54 |
shutil.rmtree(fixesdir) |
| 55 |
elif fixesdir.exists(): |
| 56 |
fixesdir.unlink() |
| 57 |
fixesdir.mkdir(parents=True) |
| 58 |
|
| 59 |
tidyret = run_clang_tool_on_sources('clang-tidy', srcdir, builddir, run_clang_tidy, tidyexe, builddir, fixesdir) |
| 60 |
if fixesdir is not None: |
| 61 |
print('Applying fix-its...') |
| 62 |
applyret = subprocess.run(applyexe + ['-format', '-style=file', '-ignore-insert-conflict', fixesdir]).returncode |
| 63 |
|
| 64 |
if tidyret != 0: |
| 65 |
print('Errors encountered while running clang-tidy', file=sys.stderr) |
| 66 |
return tidyret |
| 67 |
if fixesdir is not None and applyret != 0: |
| 68 |
print('Errors encountered while running clang-apply-replacements', file=sys.stderr) |
| 69 |
return applyret |
| 70 |
return 0 |