Prevent pushes to git containing tabs in certain files (e.g. *.cpp, *.h, CMakeLists.txt)

前端 未结 3 906
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-02 11:47

I\'d like my remote repository to refuse any pushes that contains a file that contains a tab, but only if the file belongs in a certain class (based on the filename). Is that po

3条回答
  •  感动是毒
    2021-02-02 12:49

    Based on benprew's work, here's a pre-script hook that displays an error if any tab characters have been added, as well as the relevant line number. Save the following to .git/hooks/pre-commit.

    (Note: pre-commit is the filename. There shouldn't be any . extension)

    #!/bin/sh
    
    if git rev-parse --verify HEAD 2>/dev/null
    then
      git diff-index -p -M --cached HEAD
    else
        :
    fi |
    perl -e '
        my $found_bad = 0;
        my $filename;
        my $reported_filename = "";
        my $lineno;
        sub bad_line {
            my ($why, $line) = @_;
            if (!$found_bad) {
                print STDERR "*\n";
                print STDERR "* You have some suspicious patch lines:\n";
                print STDERR "*\n";
                $found_bad = 1;
            }
            if ($reported_filename ne $filename) {
                print STDERR "* In $filename\n";
                $reported_filename = $filename;
            }
            print STDERR "* $why (line $lineno)\n";
            print STDERR "$filename:$lineno:$line\n";
        }
        while (<>) {
            if (m|^diff --git a/(.*) b/\1$|) {
                $filename = $1;
                next;
            }
            if (/^@@ -\S+ \+(\d+)/) {
                $lineno = $1 - 1;
                next;
            }
            if (/^ /) {
                $lineno++;
                next;
            }
            if (s/^\+//) {
                $lineno++;
                chomp;
                if (/   /) {
                    bad_line("TAB character", $_);
                }
            }
        }
        exit($found_bad);
    '
    

    It's not exactly what you asked for since it doesn't do any filename checking, but hopefully it helps regardless.

提交回复
热议问题