-
Notifications
You must be signed in to change notification settings - Fork 17
/
hook.sh
executable file
·88 lines (70 loc) · 2.01 KB
/
hook.sh
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
#!/usr/bin/env bash
# If we have a STDIN, use it, otherwise get one
if tty >/dev/null 2>&1; then
TTY=$(tty)
else
TTY=/dev/tty
fi
IFS=$'\n'
# http://djm.me/ask
ask() {
while true; do
if [ "${2:-}" = "Y" ]; then
prompt="Y/n"
default=Y
elif [ "${2:-}" = "N" ]; then
prompt="y/N"
default=N
else
prompt="y/n"
default=
fi
# Ask the question (not using "read -p" as it uses stderr not stdout)
echo -n "$1 [$prompt] "
# Read the answer
read REPLY < "$TTY"
# Default?
if [ -z "$REPLY" ]; then
REPLY=$default
fi
# Check if the reply is valid
case "$REPLY" in
Y*|y*) return 0 ;;
N*|n*) return 1 ;;
esac
done
}
check_file() {
local file=$1
local match_pattern=$2
local file_changes_with_context=$(git diff -U999999999 -p --cached --color=always -- $file)
# From the diff, get the green lines starting with '+' and including '$match_pattern'
local matched_additions=$(echo "$file_changes_with_context" | grep -C4 $'^\e\\[32m\+.*'"$match_pattern")
if [ -n "$matched_additions" ]; then
echo -e "\n$file additions match '$match_pattern':\n"
for matched_line in $matched_additions
do
echo "$matched_line"
done
if ask "Include this in your commit?"; then
echo 'Including'
else
echo "Not committing, because $file matches $match_pattern"
exit 1
fi
fi
}
# Actual hook logic:
MATCH=$(git config --get-all hooks.confirm.match)
if [ -z "$MATCH" ]; then
echo "Git-Confirm: hooks.confirm.match not set, defaulting to 'TODO'"
echo 'Add matches with `git config --add hooks.confirm.match "string-to-match"`'
MATCH='TODO'
fi
for file in `git diff --cached -p --name-status | cut -c3-`; do
for match_pattern in $MATCH
do
check_file $file $match_pattern
done
done
exit