370baef9553dabf2aefce9d08e5bd89cc56d4d87
[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=13
8
9 # Runs the formatter, making sure it's the expected version.
10 format_cpp() {
11 local formatter=$1
12 local version
13
14 version=$($formatter --version)
15
16 # shellcheck disable=SC2181
17 if (($? != 0)); then
18 echo "Cannot execute \`$formatter --version\`." >&2
19 return 1
20 fi
21
22 if [[ "$version" != *"clang-format version $expected_formatter_major_version"* ]]; then
23 echo "Expecting clang-format $expected_formatter_major_version." >&2
24 echo >&2
25 echo Got: >&2
26 echo >&2
27 echo "$version" >&2
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 #
38 # shellcheck disable=SC2086
39 find "$root_dir" \( -name '*.cpp' -o -name '*.hpp' \) \
40 ! -wholename '*/cpp-common/optional.hpp' \
41 ! -wholename '*/cpp-common/string_view.hpp' \
42 -print0 | xargs -n1 -0 $formatter
43 }
44
45 if [[ -n "$FORMATTER" ]]; then
46 # Try using environment-provided formatter
47 formatter=$FORMATTER
48 elif command -v clang-format-$expected_formatter_major_version &> /dev/null; then
49 # Try using the expected version of clang-format
50 formatter="clang-format-$expected_formatter_major_version -i"
51 else
52 # Try using `clang-format` as is
53 formatter='clang-format -i'
54 fi
55
56 # Try to format files
57 format_cpp "$formatter"
This page took 0.029833 seconds and 3 git commands to generate.