aboutsummaryrefslogtreecommitdiffhomepage
path: root/dev/tools/pre-commit
blob: c5f6868d156323160853f67cf4cc291b764703d9 (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
53
54
55
56
57
#!/bin/sh

# configure automatically sets up a wrapper at .git/hooks/pre-commit
# which calls this script (if it exists).

set -e

if ! git diff --cached --name-only -z | xargs -0 dev/tools/check-eof-newline.sh ||
        ! git diff-index --check --cached HEAD >/dev/null 2>&1 ;
then
    1>&2 echo "Auto fixing whitespace issues..."

    # We fix whitespace in the index and in the working tree
    # separately to preserve non-added changes.
    index=$(mktemp "git-fix-ws-index.XXXXX")
    fixed_index=$(mktemp "git-fix-ws-index-fixed.XXXXX")
    tree=$(mktemp "git-fix-ws-tree.XXXXX")
    1>&2 echo "Patches are saved in '$index', '$fixed_index' and '$tree'."
    1>&2 echo "If an error destroys your changes you can recover using them."
    1>&2 echo "(The files are cleaned up on success.)"

    git diff-index -p --cached HEAD > "$index"
    git diff-index -p HEAD > "$tree"

    # reset work tree and index
    # NB: untracked files which were not added are untouched
    git apply --cached -R "$index"
    git apply -R "$tree"

    # Fix index
    # For end of file newlines we must go through the worktree
    git apply --cached --whitespace=fix "$index"
    git apply --whitespace=fix "$index"
    git diff --cached --name-only -z | xargs -0 dev/tools/check-eof-newline.sh --fix
    git add -u

    # reset work tree
    git diff-index -p --cached HEAD > "$fixed_index"
    git apply -R "$fixed_index"

    # Fix worktree
    git apply --whitespace=fix "$tree"
    git diff --name-only -z | xargs -0 dev/tools/check-eof-newline.sh --fix

    # Check that we did fix whitespace
    if ! git diff-index --check --cached HEAD;
    then
        1>&2 echo "Auto-fixing whitespace failed: errors remain."
        1>&2 echo "This may fix itself if you try again."
        1>&2 echo "(Consider whether the number of errors decreases after each run.)"
        exit 1
    fi
    1>&2 echo "Whitespace issues fixed!"

    # clean up temporary files
    rm "$index" "$tree" "$fixed_index"
fi