]> git.ipfire.org Git - thirdparty/ccache.git/commitdiff
Added 'make check_format' to makefile rules (#525)
authorThomas Otto <thomas.otto@pdv-fs.de>
Thu, 13 Feb 2020 20:54:19 +0000 (21:54 +0100)
committerGitHub <noreply@github.com>
Thu, 13 Feb 2020 20:54:19 +0000 (21:54 +0100)
'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.

dev.mk.in
misc/clang-format.sh [new file with mode: 0755]

index 8032083ef5e204a4d39be1e1d2b41cf3df634716..ddc2b49c0aee0f379255b647678ff23c6c586020 100644 (file)
--- 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 (executable)
index 0000000..843e213
--- /dev/null
@@ -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