From: Philippe Proulx Date: Thu, 27 Jan 2022 16:00:30 +0000 (-0500) Subject: tools/format-cpp: enforce clang-format 13 X-Git-Url: http://git.efficios.com/?p=babeltrace.git;a=commitdiff_plain;h=9021ae77076ea1805eb09d0d93f8d1a4081b633c tools/format-cpp: enforce clang-format 13 This patch updates `tools/format-cpp` so that if the `FORMATTER` environment variable is not empty, the script tries to format with `$FORMATTER`; otherwise, it tries `clang-format-13 -i` or, if not available, `clang-format -i`. In all cases, the script checks the major version of the selected formatter with `--version`, failing before formatting if it's not 13. Using exactly clang-format 13 is important for formatting consistency across developers and CI systems because it's possible that a future version of clang-format, given the same configuration file, formats files dissimilarly. Signed-off-by: Philippe Proulx Change-Id: Ic81d8d09c35657b602de044f6123e8b11fc37c44 Reviewed-on: https://review.lttng.org/c/babeltrace/+/7151 --- diff --git a/tools/format-cpp b/tools/format-cpp index 48703c29..370baef9 100755 --- a/tools/format-cpp +++ b/tools/format-cpp @@ -2,11 +2,56 @@ # # SPDX-License-Identifier: GPL-2.0-only # -# Copyright (C) 2020 Philippe Proulx - -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 + +expected_formatter_major_version=13 + +# Runs the formatter, making sure it's the expected version. +format_cpp() { + local formatter=$1 + local version + + version=$($formatter --version) + + # shellcheck disable=SC2181 + if (($? != 0)); 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). + # + # shellcheck disable=SC2086 + find "$root_dir" \( -name '*.cpp' -o -name '*.hpp' \) \ + ! -wholename '*/cpp-common/optional.hpp' \ + ! -wholename '*/cpp-common/string_view.hpp' \ + -print0 | xargs -n1 -0 $formatter +} + +if [[ -n "$FORMATTER" ]]; then + # Try using environment-provided formatter + 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"