.git-pre-commit 2.07 KB
Newer Older
1 2 3 4 5 6 7
#!/bin/bash

# This hook purpose is to keep coding style consistent between all developers
# It is automatically installed in .git/hooks folder by cmake on first run.

# From https://github.com/tatsuhiro-t/nghttp2/blob/master/pre-commit

8 9 10 11
git_clang_format_path="$(which git-clang-format)"
clang_format_path=$(find /usr/bin /usr/local/bin/ -name 'clang-format-diff*' -type f -maxdepth 1 | tail -n1)


12
function git-clang-format-diffing {
13
    options="--style=file"
14 15

    #only diffing commited files, ignored staged one
16
    $git_clang_format_path $options --diff $(git --no-pager diff --cached --name-status | grep -v '^D' | cut -f2) > diff-format.patch
17

18 19
    if grep -q -E '(no modified files to format|clang-format did not modify any files)' diff-format.patch; then
        rm diff-format.patch
20 21 22 23
    fi
}

function clang-format-diff-diffing {
24
    options="-style file"
25

26 27 28
    git diff-index --cached --diff-filter=ACMR -p HEAD -- | $clang_format_path $options -p1 > file-format.patch
    if [ ! -s file-format.patch ]; then
        rm file-format.patch
29 30 31
    fi
}

32
set -e
33 34

if [ -z "$git_clang_format_path$clang_format_path" ]; then
35 36
    echo "$0: Please install clang-format (coding style checker) - could not find git-clang-format nor clang-format-diff in PATH. Skipping code verification..."
    exit 0
37
fi
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

if [ ! -z "$git_clang_format_path" ]; then
    git-clang-format-diffing
fi

if [ ! -z "$clang_format_path" ]; then
    # Warning! We need at least version 1.6...
    clang-format-diff-diffing
fi

if [ -f diff-format.patch ] || [ -f file-format.patch ]; then
    [ -f diff-format.patch ] && cat diff-format.patch
    echo "**********************************************************************"
    echo "$0: Invalid coding style detected. Please correct it using one of the following:"
    echo "* Reformat these lines manually."
    [ -f diff-format.patch ] && printf "* Apply diff patch using:\n\tcd $(git rev-parse --show-toplevel) && git apply diff-format.patch\n"
    [ -f file-format.patch ] && printf "* Apply diff patch using:\n\tpatch -p0 < file-format.patch\n"
    echo "*** Aborting commit.***"
    exit 1
fi