tools/format-cpp: use a group of `echo` lines with a single `>& 2`
[babeltrace.git] / tools / format-cpp
CommitLineData
b61d5465
PP
1#!/bin/bash
2#
3# SPDX-License-Identifier: GPL-2.0-only
4#
9021ae77
PP
5# Copyright (C) 2020-2022 Philippe Proulx <pproulx@efficios.com>
6
1d323849 7expected_formatter_major_version=15
9021ae77
PP
8
9# Runs the formatter, making sure it's the expected version.
10format_cpp() {
b11f8a1d 11 local formatter=("$@")
9021ae77
PP
12 local version
13
b11f8a1d
PP
14 if ! version=$("${formatter[@]}" --version); then
15 echo "Cannot execute \`${formatter[*]} --version\`." >&2
9021ae77
PP
16 return 1
17 fi
18
19 if [[ "$version" != *"clang-format version $expected_formatter_major_version"* ]]; then
ed6ecded
PP
20 {
21 echo "Expecting clang-format $expected_formatter_major_version."
22 echo
23 echo Got:
24 echo
25 echo "$version"
26 } >& 2
27
9021ae77
PP
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).
9021ae77
PP
37 find "$root_dir" \( -name '*.cpp' -o -name '*.hpp' \) \
38 ! -wholename '*/cpp-common/optional.hpp' \
39 ! -wholename '*/cpp-common/string_view.hpp' \
d43d15c8 40 ! -wholename '*/cpp-common/nlohmann/json.hpp' \
0ea5233c 41 -print0 | xargs -P"$(nproc)" -n1 -t -0 "${formatter[@]}"
9021ae77
PP
42}
43
44if [[ -n "$FORMATTER" ]]; then
45 # Try using environment-provided formatter
b11f8a1d 46 read -ra formatter <<< "$FORMATTER"
9021ae77
PP
47elif command -v clang-format-$expected_formatter_major_version &> /dev/null; then
48 # Try using the expected version of clang-format
b11f8a1d 49 formatter=("clang-format-$expected_formatter_major_version" -i)
9021ae77
PP
50else
51 # Try using `clang-format` as is
b11f8a1d 52 formatter=(clang-format -i)
9021ae77
PP
53fi
54
55# Try to format files
b11f8a1d 56format_cpp "${formatter[@]}"
This page took 0.031027 seconds and 4 git commands to generate.