1# Copyright 2019 The Meson development team
2
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6
7#     http://www.apache.org/licenses/LICENSE-2.0
8
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import pathlib
16import subprocess
17import shutil
18from concurrent.futures import ThreadPoolExecutor
19
20from ..compilers import lang_suffixes
21
22def manual_clangformat(srcdir_name, builddir_name):
23    srcdir = pathlib.Path(srcdir_name)
24    suffixes = set(lang_suffixes['c']).union(set(lang_suffixes['cpp']))
25    suffixes.add('h')
26    futures = []
27    returncode = 0
28    with ThreadPoolExecutor() as e:
29        for f in (x for suff in suffixes for x in srcdir.glob('**/*.' + suff)):
30            strf = str(f)
31            if strf.startswith(builddir_name):
32                continue
33            futures.append(e.submit(subprocess.run, ['clang-tidy', '-p', builddir_name, strf]))
34        [max(returncode, x.result().returncode) for x in futures]
35    return returncode
36
37def clangformat(srcdir_name, builddir_name):
38    run_clang_tidy = None
39    for rct in ('run-clang-tidy', 'run-clang-tidy.py'):
40        if shutil.which(rct):
41            run_clang_tidy = rct
42            break
43    if run_clang_tidy:
44        return subprocess.run([run_clang_tidy, '-p', builddir_name]).returncode
45    else:
46        print('Could not find run-clang-tidy, running checks manually.')
47        manual_clangformat(srcdir_name, builddir_name)
48
49def run(args):
50    srcdir_name = args[0]
51    builddir_name = args[1]
52    return clangformat(srcdir_name, builddir_name)
53