Debian Codegraph @

mesonbuild/scripts/clangformat.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2018 The Meson development team
3
4 from __future__ import annotations
5
6 import argparse
7 from pathlib import Path
8 import sys
9
10 from .run_tool import run_clang_tool, run_with_buffered_output
11 from ..tooldetect import detect_clangformat
12 from ..mesonlib import version_compare
13 from ..programs import ExternalProgram
14 import typing as T
15
16 async def run_clang_format(fname: Path, exelist: T.List[str], options: argparse.Namespace, cformat_ver: T.Optional[str]) -> int:
17 clangformat_10 = False
18 if options.check and cformat_ver:
19 if version_compare(cformat_ver, '>=10'):
20 clangformat_10 = True
21 exelist = exelist + ['--dry-run', '--Werror']
22 # The option is not documented but it exists in version 10
23 if options.color == 'always' or options.color == 'auto' and sys.stdout.isatty():
24 exelist += ['--color=1']
25 else:
26 original = fname.read_bytes()
27 before = fname.stat().st_mtime
28 ret = await run_with_buffered_output(exelist + ['-style=file', '-i', str(fname)])
29 after = fname.stat().st_mtime
30 if before != after:
31 print('File reformatted: ', fname)
32 if options.check and not clangformat_10:
33 # Restore the original if only checking.
34 fname.write_bytes(original)
35 return 1
36 return ret
37
38 def run(args: T.List[str]) -> int:
39 parser = argparse.ArgumentParser()
40 parser.add_argument('--check', action='store_true')
41 parser.add_argument('--color', default='always')
42 parser.add_argument('sourcedir')
43 parser.add_argument('builddir')
44 options = parser.parse_args(args)
45
46 srcdir = Path(options.sourcedir)
47 builddir = Path(options.builddir)
48
49 exelist = detect_clangformat()
50 if not exelist:
51 print('Could not execute clang-format "%s"' % ' '.join(exelist))
52 return 1
53
54 if options.check:
55 cformat_ver = ExternalProgram('clang-format', exelist, silent=True).get_version()
56 else:
57 cformat_ver = None
58
59 return run_clang_tool('clang-format', srcdir, builddir, run_clang_format, exelist, options, cformat_ver)