From: Thomas Otto Date: Thu, 13 Feb 2020 20:54:19 +0000 (+0100) Subject: Added 'make check_format' to makefile rules (#525) X-Git-Tag: v4.0~627 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=db6706ad3b5a30c586cdf60a55c04f5df38ac5c7;p=thirdparty%2Fccache.git Added 'make check_format' to makefile rules (#525) 'make format' formats all source files with clang-format, and 'make check_format' only checks and on failure prints a diff, then exits with the appropriate status. Because quick interactive formatting is one use case, xargs is used for parallelism. Proper make-parallelism would require -k and -j arguments to work. --- diff --git a/dev.mk.in b/dev.mk.in index 8032083ef..ddc2b49c0 100644 --- a/dev.mk.in +++ b/dev.mk.in @@ -199,7 +199,18 @@ shellcheck: test/suites/*.bash .PHONY: format format: - $(CLANG_FORMAT) -i $(non_third_party_headers) $(non_third_party_sources) $(test_sources) + @echo $(non_third_party_headers) $(non_third_party_sources) $(test_sources) | xargs -n1 -P8 \ + misc/clang-format.sh + +# Not using parallel execution because target is most likely being run on non-interactive CI system, +# so no user is waiting for immediate results, and it avoids possibly interleaved output. +.PHONY: check_format +check_format: + @[ -t 1 ] && export cf_diff_color="--color=always"; \ + echo $(non_third_party_headers) $(non_third_party_sources) $(test_sources) | xargs -n1 -P1 \ + misc/clang-format.sh --check || \ + { echo; echo "Error: Sources are not formatted with clang-format."; \ + echo 'Run "make format" or apply the above diff.'; } # pip install compiledb compile_commands.json: diff --git a/misc/clang-format.sh b/misc/clang-format.sh new file mode 100755 index 000000000..843e213ff --- /dev/null +++ b/misc/clang-format.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +# Reformat the given C++ file if required, or if --check +# is specified, only print the diff. +# Exits with 0 if the file was already formatted correctly. + +set -eu + +clang_format="${CLANG_FORMAT:-clang-format}" +cf_diff_color="${cf_diff_color:-}" + +if [[ "${1:-}" == "--check" ]]; then + shift + check=true +else + check=false +fi + +if [[ $# -ne 1 ]]; then + echo "Usage: $0 [--check] file.cpp" + exit 1 +fi + +file="$1" + +if [[ ! -e "$file" ]]; then + echo "No such file: $file" + exit 1 +fi + +tmp_file="$file.$$.clang-format.tmp" +trap "rm -f \"$tmp_file\"" EXIT + +"$clang_format" "$file" >"$tmp_file" + +if ! cmp -s "$file" "$tmp_file"; then + if $check; then + git diff $cf_diff_color --no-index "$file" "$tmp_file" | + sed -r -e "s!^---.*!--- a/$file!" -e "s!^\+\+\+.*!+++ b/$file!" \ + -e "/diff --/d" -e "/index /d" -e "s/.[0-9]*.clang-format.tmp//" + else + echo "Reformatted $file" + mv "$tmp_file" "$file" && trap '' EXIT + fi + exit 1 +fi