dfc4bbd5061a74e3dd5f179e5e53069312a2cfe3
[babeltrace.git] / tools / format-cpp
1 #!/bin/bash
2 #
3 # SPDX-License-Identifier: GPL-2.0-only
4 #
5 # Copyright (C) 2020-2022 Philippe Proulx <pproulx@efficios.com>
6
7 expected_formatter_major_version=15
8
9 # Runs the formatter, making sure it's the expected version.
10 format_cpp() {
11 local formatter=("$@")
12 local version
13
14 if ! version=$("${formatter[@]}" --version); then
15 echo "Cannot execute \`${formatter[*]} --version\`." >&2
16 return 1
17 fi
18
19 if [[ "$version" != *"clang-format version $expected_formatter_major_version"* ]]; then
20 {
21 echo "Expecting clang-format $expected_formatter_major_version."
22 echo
23 echo Got:
24 echo
25 echo "$version"
26 } >& 2
27
28 return 1
29 fi
30
31 local root_dir
32
33 root_dir="$(dirname "${BASH_SOURCE[0]}")/.."
34
35 # Using xargs to fail as soon as the formatter fails (`-exec`
36 # won't stop if its subprocess fails).
37 find "$root_dir" \( -name '*.cpp' -o -name '*.hpp' \) \
38 ! -wholename '*/cpp-common/optional.hpp' \
39 ! -wholename '*/cpp-common/string_view.hpp' \
40 ! -wholename '*/cpp-common/nlohmann/json.hpp' \
41 -print0 | xargs -P"$(nproc)" -n1 -t -0 "${formatter[@]}"
42 }
43
44 if [[ -n "$FORMATTER" ]]; then
45 # Try using environment-provided formatter
46 read -ra formatter <<< "$FORMATTER"
47 elif command -v clang-format-$expected_formatter_major_version &> /dev/null; then
48 # Try using the expected version of clang-format
49 formatter=("clang-format-$expected_formatter_major_version" -i)
50 else
51 # Try using `clang-format` as is
52 formatter=(clang-format -i)
53 fi
54
55 # Try to format files
56 format_cpp "${formatter[@]}"
This page took 0.030288 seconds and 3 git commands to generate.