075eb3c1f4ca272f095c92dd1b99f3286924bff7
[git.git] / templates / hooks--pre-commit
1 #!/bin/sh
2 #
3 # An example hook script to verify what is about to be committed.
4 # Called by git-commit-script with no arguments.  The hook should
5 # exit with non-zero status after issuing an appropriate message if
6 # it wants to stop the commit.
7 #
8 # To enable this hook, make this file executable.
9
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 perl -e '
14     my $fh;
15     my $found_bad = 0;
16     my $filename;
17     my $reported_filename = "";
18     my $lineno;
19     sub bad_line {
20         my ($why, $line) = @_;
21         if (!$found_bad) {
22             print STDERR "*\n";
23             print STDERR "* You have some suspicious patch lines:\n";
24             print STDERR "*\n";
25             $found_bad = 1;
26         }
27         if ($reported_filename ne $filename) {
28             print STDERR "* In $filename\n";
29             $reported_filename = $filename;
30         }
31         print STDERR "* $why (line $lineno)\n";
32         print STDERR "$filename:$lineno:$line\n";
33     }
34     open $fh, "-|", qw(git-diff-cache -p -M --cached HEAD);
35     while (<$fh>) {
36         if (m|^diff --git a/(.*) b/\1$|) {
37             $filename = $1;
38             next;
39         }
40         if (/^@@ -\S+ \+(\d+)/) {
41             $lineno = $1 - 1;
42             next;
43         }
44         if (/^ /) {
45             $lineno++;
46             next;
47         }
48         if (s/^\+//) {
49             $lineno++;
50             chomp;
51             if (/\s$/) {
52                 bad_line("trailing whitespace", $_);
53             }
54             if (/^\s*   /) {
55                 bad_line("indent SP followed by a TAB", $_);
56             }
57         }
58     }
59     exit($found_bad);
60 '
61