format.sh 1.78 KB
Newer Older
Matthieu Schaller's avatar
Matthieu Schaller committed
1 2
#!/bin/bash

3
# Clang format command, can be overridden using CLANG_FORMAT_CMD.
4 5
# We currrently use version 10.0 so any overrides should provide that.
clang=${CLANG_FORMAT_CMD:="clang-format-10"}
Loic Hausammann's avatar
Loic Hausammann committed
6 7

# Formatting command
8
cmd="$clang -style=file $(git ls-files | grep '\.[ch]$')"
Loic Hausammann's avatar
Loic Hausammann committed
9

10
# Test if `clang-format-10` works
Loic Hausammann's avatar
Loic Hausammann committed
11 12 13
command -v $clang > /dev/null
if [[ $? -ne 0 ]]
then
14
    echo "ERROR: cannot find $clang"
Loic Hausammann's avatar
Loic Hausammann committed
15 16 17 18 19
    exit 1
fi

# Print the help
function show_help {
20
    echo -e "This script formats SWIFT according to Google style"
Loic Hausammann's avatar
Loic Hausammann committed
21
    echo -e "  -h, --help \t Show this help"
22
    echo -e "  -t, --test \t Test if SWIFT is well formatted"
Loic Hausammann's avatar
Loic Hausammann committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
}

# Parse arguments (based on https://stackoverflow.com/questions/192249)
TEST=0
while [[ $# -gt 0 ]]
do
    key="$1"

    case $key in
	# print the help and exit
	-h|--help)
	    show_help
	    exit
	    ;;
	# check if the code is well formatted
	-t|--test)
	    TEST=1
	    shift
	    ;;
	# unknown option
	*)
	    echo "Argument '$1' not implemented"
	    show_help
	    exit
	    ;;
    esac
done

# Run the required commands
if [[ $TEST -eq 1 ]]
then
54 55 56 57 58 59 60 61 62 63 64 65 66 67
    # 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
Loic Hausammann's avatar
Loic Hausammann committed
68 69

    # Check formatting
70
    if [[ ${status[1]} -eq 0 ]]
Loic Hausammann's avatar
Loic Hausammann committed
71
    then
72 73 74 75
 	echo "ERROR: needs formatting"
 	exit 1
    else
        echo "...is correctly formatted"
Loic Hausammann's avatar
Loic Hausammann committed
76 77
    fi
else
78
    echo "Formatting SWIFT"
Loic Hausammann's avatar
Loic Hausammann committed
79 80
    $cmd -i
fi