tools/format-cpp: make shellcheck happy again
[babeltrace.git] / tools / format-cpp
index 48703c29bbd643fb55dedd0589ee4c1c33bcc8f5..a2c6a3aefee8c3ccbce0cb7d62f390136211a538 100755 (executable)
@@ -2,11 +2,52 @@
 #
 # SPDX-License-Identifier: GPL-2.0-only
 #
-# Copyright (C) 2020 Philippe Proulx <pproulx@efficios.com>
-
-FORMATTER="${FORMATTER:-clang-format -i}"
-root_dir="$(dirname "${BASH_SOURCE[0]}")/.."
-find "$root_dir" \( -name '*.cpp' -o -name '*.hpp' \) \
-       ! -wholename '*/cpp-common/optional.hpp' \
-       ! -wholename '*/cpp-common/string_view.hpp' \
-       -exec $FORMATTER '{}' ';'
+# Copyright (C) 2020-2022 Philippe Proulx <pproulx@efficios.com>
+
+expected_formatter_major_version=15
+
+# Runs the formatter, making sure it's the expected version.
+format_cpp() {
+       local formatter=("$@")
+       local version
+
+       if ! version=$("${formatter[@]}" --version); then
+               echo "Cannot execute \`${formatter[*]} --version\`." >&2
+               return 1
+       fi
+
+       if [[ "$version" != *"clang-format version $expected_formatter_major_version"* ]]; then
+               echo "Expecting clang-format $expected_formatter_major_version." >&2
+               echo >&2
+               echo Got: >&2
+               echo >&2
+               echo "$version" >&2
+               return 1
+       fi
+
+       local root_dir
+
+       root_dir="$(dirname "${BASH_SOURCE[0]}")/.."
+
+       # Using xargs to fail as soon as the formatter fails (`-exec`
+       # won't stop if its subprocess fails).
+       find "$root_dir" \( -name '*.cpp' -o -name '*.hpp' \) \
+               ! -wholename '*/cpp-common/optional.hpp' \
+               ! -wholename '*/cpp-common/string_view.hpp' \
+               ! -wholename '*/cpp-common/nlohmann/json.hpp' \
+               -print0 | xargs -P"$(nproc)" -n1 -0 "${formatter[@]}"
+}
+
+if [[ -n "$FORMATTER" ]]; then
+       # Try using environment-provided formatter
+       read -ra formatter <<< "$FORMATTER"
+elif command -v clang-format-$expected_formatter_major_version &> /dev/null; then
+       # Try using the expected version of clang-format
+       formatter=("clang-format-$expected_formatter_major_version" -i)
+else
+       # Try using `clang-format` as is
+       formatter=(clang-format -i)
+fi
+
+# Try to format files
+format_cpp "${formatter[@]}"
This page took 0.024759 seconds and 4 git commands to generate.