aboutsummaryrefslogtreecommitdiff
path: root/git-hooks/hooks/pre-commit
blob: 5666e9371654137c0ae19349efaf252904afe6eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
#!/bin/sh

set -e

gitdir="$(git rev-parse --git-dir)"

changed_files() {
    git diff --name-status --cached HEAD | tr '\011' '\012' | awk '
        /^[ADMTUXB]/ { n = 1; next }
        /^[CR]/ { n = 2; next }
        n > 0 {
            print $0
            n--
        }
    '
}

staged_file_hash() {
    git ls-files -s "$1" | cut -d' ' -f2
}

lint_php() {
    php -l >/dev/null
}

lint_php_cs_fixer() {
    php-cs-fixer fix --config="$gitdir/../.php_cs.dist" -v --dry-run --using-cache=no --show-progress=none - >&2
}

lint_changes() {
    linter_name="$1"
    grep_pattern="$2"
    linter_func="$3"

    failcount="$(changed_files | grep "$grep_pattern" | while read -r f; do
        hash="$(staged_file_hash "$f")"
        if [ -n "$hash" ]; then
            if ! git cat-file blob "$hash" | "$linter_func"; then
                echo >&2
                echo "Linter $linter_name reported error for: $f" >&2
                echo >&2

                echo failed
            fi
        fi
    done | wc -l)"

    [ "$failcount" -eq 0 ] || return 1
}

lint_changes "php -l" '\.php$' lint_php || exit 1
lint_changes "php_cs_fixer" '\.php$' lint_php_cs_fixer || exit 1