summaryrefslogtreecommitdiff
path: root/misc/hooks/pre-commit-black
blob: bbad6a690a92f3c88a5b437abc1819afbf992780 (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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
#!/usr/bin/env bash

# git pre-commit hook that runs a black stylecheck.
# Based on pre-commit-clang-format.

##################################################################
# SETTINGS
# Set path to black binary.
BLACK=`which black 2>/dev/null`
BLACK_OPTIONS="-l 120"

# Remove any older patches from previous commits. Set to true or false.
DELETE_OLD_PATCHES=false

# File types to parse.
FILE_NAMES="SConstruct SCsub"
FILE_EXTS=".py"

# Use pygmentize instead of cat to parse diff with highlighting.
# Install it with `pip install pygments` (Linux) or `easy_install Pygments` (Mac)
PYGMENTIZE=`which pygmentize 2>/dev/null`
if [ ! -z "$PYGMENTIZE" ]; then
  READER="pygmentize -l diff"
else
  READER=cat
fi

# Path to zenity
ZENITY=`which zenity 2>/dev/null`

# Path to xmessage
XMSG=`which xmessage 2>/dev/null`

# Path to powershell (Windows only)
PWSH=`which powershell 2>/dev/null`

# Path to osascript (macOS only)
OSA=`which osascript 2>/dev/null`

##################################################################
# There should be no need to change anything below this line.

. "$(dirname -- "$0")/canonicalize_filename.sh"

# exit on error
set -e

# check whether the given file matches any of the set extensions
matches_name_or_extension() {
    local filename=$(basename "$1")
    local extension=".${filename##*.}"

    for name in $FILE_NAMES; do [[ "$name" == "$filename" ]] && return 0; done
    for ext in $FILE_EXTS; do [[ "$ext" == "$extension" ]] && return 0; done

    return 1
}

# necessary check for initial commit
if git rev-parse --verify HEAD >/dev/null 2>&1 ; then
    against=HEAD
else
    # Initial commit: diff against an empty tree object
    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

if [ ! -x "$BLACK" ] ; then
    if [ ! -t 1 ] ; then
        if [ -x "$ZENITY" ] ; then
            $ZENITY --error --title="Error" --text="Error: black executable not found."
            exit 1
        elif [ -x "$XMSG" ] ; then
            $XMSG -center -title "Error" "Error: black executable not found."
            exit 1
        elif [ -x "$OSA" ] ; then
            asmessage="$(canonicalize_filename "$(dirname -- "$0")/asmessage.applescript")"
            $OSA "$asmessage" -center -title "Error" --text "Error: black executable not found."
            exit 1
        elif [ \( \( "$OSTYPE" = "msys" \) -o \( "$OSTYPE" = "win32" \) \) -a \( -x "$PWSH" \) ]; then
            winmessage="$(canonicalize_filename "$(dirname -- "$0")/winmessage.ps1")"
            $PWSH -noprofile -executionpolicy bypass -file "$winmessage" -center -title "Error" --text "Error: black executable not found."
            exit 1
        fi
    fi
    printf "Error: black executable not found.\n"
    printf "Set the correct path in $(canonicalize_filename "$0").\n"
    exit 1
fi

# create a random filename to store our generated patch
prefix="pre-commit-black"
suffix="$(date +%s)"
patch="/tmp/$prefix-$suffix.patch"

# clean up any older black patches
$DELETE_OLD_PATCHES && rm -f /tmp/$prefix*.patch

# create one patch containing all changes to the files
git diff-index --cached --diff-filter=ACMR --name-only $against -- | while read file;
do
    # ignore thirdparty files
    if grep -q "thirdparty" <<< $file; then
        continue;
    fi

    # ignore file if not one of the names or extensions we handle
    if ! matches_name_or_extension "$file"; then
        continue;
    fi

    # format our file with black, create a patch with diff and append it to our $patch
    # The sed call is necessary to transform the patch from
    #    --- $file timestamp
    #    +++ $file timestamp
    # to both lines working on the same file and having a/ and b/ prefix.
    # Else it can not be applied with 'git apply'.
    "$BLACK" "$BLACK_OPTIONS" --diff "$file" | \
        sed -e "1s|--- |--- a/|" -e "2s|+++ |+++ b/|" >> "$patch"
done

# if no patch has been generated all is ok, clean up the file stub and exit
if [ ! -s "$patch" ] ; then
    printf "Files in this commit comply with the black formatter rules.\n"
    rm -f "$patch"
    exit 0
fi

# a patch has been created, notify the user and exit
printf "\nThe following differences were found between the code to commit "
printf "and the black formatter rules:\n\n"

if [ -t 1 ] ; then
    $READER "$patch"
    printf "\n"
    # Allows us to read user input below, assigns stdin to keyboard
    exec < /dev/tty
    terminal="1"
else
    cat "$patch"
    printf "\n"
    # Allows non zero zenity/powershell output
    set +e
    terminal="0"
fi

while true; do
    if [ $terminal = "0" ] ; then
        if [ -x "$ZENITY" ] ; then
            choice=$($ZENITY --text-info --filename="$patch" --width=800 --height=600 --title="Do you want to apply that patch?" --ok-label="Apply" --cancel-label="Do not apply" --extra-button="Apply and stage")
            if [ "$?" = "0" ] ; then
                yn="Y"
            else
                if [ "$choice" = "Apply and stage" ] ; then
                    yn="S"
                else
                    yn="N"
                fi
            fi
        elif [ -x "$XMSG" ] ; then
            $XMSG -file "$patch" -buttons "Apply":100,"Apply and stage":200,"Do not apply":0 -center -default "Do not apply" -geometry 800x600 -title "Do you want to apply that patch?"
            choice=$?
            if [ "$choice" = "100" ] ; then
                yn="Y"
            elif [ "$choice" = "200" ] ; then
                yn="S"
            else
                yn="N"
            fi
        elif [ -x "$OSA" ] ; then
            asmessage="$(canonicalize_filename "$(dirname -- "$0")/asmessage.applescript")"
            choice=`$OSA "$asmessage" -file "$patch" -buttons "Apply":100,"Apply and stage":200,"Do not apply":0 -center -default "Do not apply" -geometry 800x600 -title "Do you want to apply that patch?"`
            if [ "$choice" = "100" ] ; then
                yn="Y"
            elif [ "$choice" = "200" ] ; then
                yn="S"
            else
                yn="N"
            fi
        elif [ \( \( "$OSTYPE" = "msys" \) -o \( "$OSTYPE" = "win32" \) \) -a \( -x "$PWSH" \) ]; then
            winmessage="$(canonicalize_filename "$(dirname -- "$0")/winmessage.ps1")"
            $PWSH -noprofile -executionpolicy bypass -file "$winmessage" -file "$patch" -buttons "Apply":100,"Apply and stage":200,"Do not apply":0 -center -default "Do not apply" -geometry 800x600 -title "Do you want to apply that patch?"
            choice=$?
            if [ "$choice" = "100" ] ; then
                yn="Y"
            elif [ "$choice" = "200" ] ; then
                yn="S"
            else
                yn="N"
            fi
        else
            printf "Error: zenity, xmessage, osascript, or powershell executable not found.\n"
            exit 1
        fi
    else
        read -p "Do you want to apply that patch (Y - Apply, N - Do not apply, S - Apply and stage files)? [Y/N/S] " yn
    fi
    case $yn in
        [Yy] ) git apply $patch;
        printf "The patch was applied. You can now stage the changes and commit again.\n\n";
        break
        ;;
        [Nn] ) printf "\nYou can apply these changes with:\n  git apply $patch\n";
        printf "(may need to be called from the root directory of your repository)\n";
        printf "Aborting commit. Apply changes and commit again or skip checking with";
        printf " --no-verify (not recommended).\n\n";
        break
        ;;
        [Ss] ) git apply $patch;
        git diff-index --cached --diff-filter=ACMR --name-only $against -- | while read file;
        do git add $file;
        done
        printf "The patch was applied and the changed files staged. You can now commit.\n\n";
        break
        ;;
        * ) echo "Please answer yes or no."
        ;;
    esac
done
exit 1 # we don't commit in any case