From b82b6e1a72b88b35c0f28ad2f03b2ec7efeb8ac5 Mon Sep 17 00:00:00 2001
From: "Peter W. Draper" <p.w.draper@durham.ac.uk>
Date: Thu, 23 Aug 2018 18:28:33 +0100
Subject: [PATCH] Handle pipe errors more explicitly, failing at first command
 in the pipe was OK for automation, but not very informative when ran
 interactively

It is SWIFT not Swift
---
 format.sh | 41 ++++++++++++++++++++++++++---------------
 1 file changed, 26 insertions(+), 15 deletions(-)

diff --git a/format.sh b/format.sh
index 1d947e386b..7dfb038d74 100755
--- a/format.sh
+++ b/format.sh
@@ -1,7 +1,8 @@
 #!/bin/bash
 
-# Clang software name
-clang="clang-format-5.0"
+# Clang format command, can be overridden using CLANG_FORMAT_CMD.
+# We currrently use version 5.0 so any overrides should provide that.
+clang=${CLANG_FORMAT_CMD:="clang-format-5.0"}
 
 # Formatting command
 cmd="$clang -style=file src/*.[ch] src/*/*.[ch] src/*/*/*.[ch] examples/main.c tests/*.[ch]"
@@ -10,18 +11,15 @@ cmd="$clang -style=file src/*.[ch] src/*/*.[ch] src/*/*/*.[ch] examples/main.c t
 command -v $clang > /dev/null
 if [[ $? -ne 0 ]]
 then
-    echo "Cannot find $clang"
+    echo "ERROR: cannot find $clang"
     exit 1
 fi
 
-set -e
-
-
 # Print the help
 function show_help {
-    echo -e "This script formats Swift according to Google style"
+    echo -e "This script formats SWIFT according to Google style"
     echo -e "  -h, --help \t Show this help"
-    echo -e "  -t, --test \t Test if Swift is well formatted"
+    echo -e "  -t, --test \t Test if SWIFT is well formatted"
 }
 
 # Parse arguments (based on https://stackoverflow.com/questions/192249)
@@ -53,17 +51,30 @@ done
 # Run the required commands
 if [[ $TEST -eq 1 ]]
 then
-    echo "Testing Swift formatting"
-    $cmd -output-replacements-xml | grep -c "<replacement " >/dev/null
-    res=$?
+    # Note trapping the exit status from both commands in the pipe. Also note
+    # do not use -q in grep as that closes the pipe on first match and we get
+    # a SIGPIPE error.
+    echo "Testing if SWIFT is correctly formatted"
+    $cmd -output-replacements-xml | grep "<replacement " > /dev/null
+    status=("${PIPESTATUS[@]}")
+
+    #  Trap if first command failed. Note 141 is SIGPIPE, that happens when no
+    #  output
+    if [[ ${status[0]} -ne 0 ]]
+    then
+       echo "ERROR: $clang command failed"
+       exit 1
+    fi
 
     # Check formatting
-    if [[ $res -ne 1 ]]
+    if [[ ${status[1]} -eq 0 ]]
     then
-	echo "Swift needs to be formatted"
-	exit 1
+ 	echo "ERROR: needs formatting"
+ 	exit 1
+    else
+        echo "...is correctly formatted"
     fi
 else
-    echo "Formatting Swift"
+    echo "Formatting SWIFT"
     $cmd -i
 fi
-- 
GitLab