Skip to content

Commit 03e2b63

Browse files
committed
Update sample pre-commit hook to use "diff --check"
Now "diff --check" can detect not just whitespace errors but also notices leftover conflict marker lines, we can use it in the sample pre-commit hook script. These days the object layer knows about the empty tree object without actually having one in the repository, so we can run the test even for the initial commit. Signed-off-by: Junio C Hamano <gitster@pobox.com>
1 parent 0495404 commit 03e2b63

File tree

1 file changed

+6
-58
lines changed

1 file changed

+6
-58
lines changed

templates/hooks--pre-commit.sample

Lines changed: 6 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -7,64 +7,12 @@
77
#
88
# To enable this hook, rename this file to "pre-commit".
99

10-
# This is slightly modified from Andrew Morton's Perfect Patch.
11-
# Lines you introduce should not have trailing whitespace.
12-
# Also check for an indentation that has SP before a TAB.
13-
1410
if git-rev-parse --verify HEAD 2>/dev/null
1511
then
16-
git-diff-index -p -M --cached HEAD --
12+
against=HEAD
1713
else
18-
# NEEDSWORK: we should produce a diff with an empty tree here
19-
# if we want to do the same verification for the initial import.
20-
:
21-
fi |
22-
perl -e '
23-
my $found_bad = 0;
24-
my $filename;
25-
my $reported_filename = "";
26-
my $lineno;
27-
sub bad_line {
28-
my ($why, $line) = @_;
29-
if (!$found_bad) {
30-
print STDERR "*\n";
31-
print STDERR "* You have some suspicious patch lines:\n";
32-
print STDERR "*\n";
33-
$found_bad = 1;
34-
}
35-
if ($reported_filename ne $filename) {
36-
print STDERR "* In $filename\n";
37-
$reported_filename = $filename;
38-
}
39-
print STDERR "* $why (line $lineno)\n";
40-
print STDERR "$filename:$lineno:$line\n";
41-
}
42-
while (<>) {
43-
if (m|^diff --git a/(.*) b/\1$|) {
44-
$filename = $1;
45-
next;
46-
}
47-
if (/^@@ -\S+ \+(\d+)/) {
48-
$lineno = $1 - 1;
49-
next;
50-
}
51-
if (/^ /) {
52-
$lineno++;
53-
next;
54-
}
55-
if (s/^\+//) {
56-
$lineno++;
57-
chomp;
58-
if (/\s$/) {
59-
bad_line("trailing whitespace", $_);
60-
}
61-
if (/^\s* \t/) {
62-
bad_line("indent SP followed by a TAB", $_);
63-
}
64-
if (/^([<>])\1{6} |^={7}$/) {
65-
bad_line("unresolved merge conflict", $_);
66-
}
67-
}
68-
}
69-
exit($found_bad);
70-
'
14+
# Initial commit: diff against an empty tree object
15+
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
16+
fi
17+
18+
exec git diff-index --check --cached $against --

0 commit comments

Comments
 (0)