Skip to content

Commit 76cba32

Browse files
phillipwoodgitster
authored andcommitted
templates: detect commit messages containing diffs
If a commit message contains a diff that is not indented then "git am" will treat that diff as part of the patch rather than as part of the commit message. This allows it to apply email messages that were created by adding a commit message in front of a regular diff without adding the "---" separator used by "git format-patch". This often surprises users [1-4] so add a check to the sample "commit-msg" hook to reject messages that would confuse "git am". Detecting if the message contains a diff is complicated by the hook being passed the message before it is cleaned up so we need to ignore any diffs below the scissors line. There are also two possible config keys to check to find the comment character at the start of the scissors line. [1] https://lore.kernel.org/git/bcqvh7ahjjgzpgxwnr4kh3hfkksfruf54refyry3ha7qk7dldf@fij5calmscvm [2] https://lore.kernel.org/git/ca13705ae4817ffba16f97530637411b59c9eb19.camel@scientia.org/ [3] https://lore.kernel.org/git/d0b577825124ac684ab304d3a1395f3d2d0708e8.1662333027.git.matheus.bernardino@usp.br/ [4] https://lore.kernel.org/git/CAFOYHZC6Qd9wkoWPcTJDxAs9u=FGpHQTkjE-guhwkya0DRVA6g@mail.gmail.com/ Signed-off-by: Phillip Wood <phillip.wood@dunelm.org.uk> Signed-off-by: Junio C Hamano <gitster@pobox.com>
1 parent f04b3d4 commit 76cba32

1 file changed

Lines changed: 29 additions & 2 deletions

File tree

templates/hooks/commit-msg.sample

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,37 @@
1515
# SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
1616
# grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1"
1717

18-
# This example catches duplicate Signed-off-by lines.
18+
# This example catches duplicate Signed-off-by lines and messages that
19+
# would confuse 'git am'.
20+
21+
ret=0
1922

2023
test "" = "$(grep '^Signed-off-by: ' "$1" |
2124
sort | uniq -c | sed -e '/^[ ]*1[ ]/d')" || {
2225
echo >&2 Duplicate Signed-off-by lines.
23-
exit 1
26+
ret=1
2427
}
28+
29+
comment_re="$(
30+
{
31+
git config --get-regexp "^core\.comment(char|string)\$" ||
32+
echo '#'
33+
} | sed -n -e '
34+
${
35+
s/^[^ ]* //
36+
s|[][*./\]|\\&|g
37+
s/^auto$/[#;@!$%^&|:]/
38+
p
39+
}'
40+
)"
41+
line="$(sed -n -e "/^${comment_re} -\{8,\} >8 -\{8,\}\$/q
42+
/^diff -/{p;q;}
43+
/^Index: /{p;q;}" "$1")"
44+
if test -n "$line"
45+
then
46+
echo >&2 "Message contains a diff that will confuse 'git am'."
47+
echo >&2 "To fix this indent the diff."
48+
ret=1
49+
fi
50+
51+
exit $ret

0 commit comments

Comments
 (0)