防止合并冲突的文件在git中被提交

use*_*664 20 git github merge-conflict-resolution

有没有办法阻止合并冲突的文件在git中提交?没有人会故意提交有冲突的文件.但有没有办法防止文件在git中提交?

是否有git的任何设置或配置值的任何地方,在那里它可以防止文件被寻找<<<<<<<,=======还是>>>>>>>符号?

sle*_*ske 6

VonC的答案已经说明了您可能要检查合并提交的各种挂钩。

如果您只是想要一个简单的解决方案来避免提交冲突,则默认预提交挂钩示例中的git中已经包含了该解决方案。只需将钩子重命名.git/hooks/pre-commit.sample为即可.git/hooks/pre-commit。如果然后尝试进行冲突:

$ git commit -am "Fix crash in frobnicate"
src/foo.c:239: leftover conflict marker
Run Code Online (Sandbox Code Playgroud)

注意:

该脚本在git diff --check内部使用,它还会检查各种空白问题-因此您也可能会遇到空白错误。您也可以git diff --check在致力于发现问题之前运行。有关git diff详细信息和配置选项,请参见的手册页。

这对git V2.0有效;不知道何时引入。

  • 啊,发现它仅在我的航站楼外*叹气*;无论如何,即使启用了该钩子,我也可以愉快地提交合并标记:(所以,是的,应该是一个新问题。 (3认同)
  • 我得到的预提交钩子样本是关于提交文件名中的非 ASCII 字符。你能给出无冲突样本的内容吗? (2认同)

Von*_*onC 5

你可以使用一个pre-commit 钩子,但要注意a git commit --no-verify会有效地忽略它.

我通常会设置一个pre-receive钩子来控制(更多)中心点被推动的东西.

但是a pre-commmit允许更及时的检测(在开发周期的早期).

这是另一个例子(除了jthill评论),在perl中.
它使用git diff-index -p -M --cached HEAD,git diff-index而不是git diff.
我已经通过此挂钩完成了一些其他控件,只是为了展示您可以在这样的脚本中执行的检查.

#!/usr/bin/perl

use Modern::Perl;
use File::Basename;

my $nb_errors = 0;
my $filepath;
for my $l ( split '\n', `git diff-index -p -M --cached HEAD` ) {
    if ( $l =~ /^diff --git a\/([^ ]*) .*$/ ) {
        $filepath = $1;
    }
    given ( $l ) {
        # if there is a file called *.log, stop
        when ( /\.log/ ) {
            say "$filepath contains console.log ($l)";
            $nb_errors++;
        }
        # check if there is a warn, that could be unconditionnal, but just warn, don't stop
        when ( /^[^(\#|\-)]+warn/ ) {
            # stay silent if we're in a template, a "warn" here is fair, it's usually a message or a css class
            unless ($filepath =~ /\.tt$/) {
            say "$filepath contains warn ($l)";
            }
        }
        # check if there is a ` introduced, that is a mysqlism in databases. Can be valid so don't stop, just warn
        when (/^\+.*`.*/) {
            say "$filepath contains a ` ($l)";
        }
        # check if there is a merge conflict marker and just warn (we probably could stop if there is one)
        when ( m/^<<<<<</ or m/^>>>>>>/ or m/^======/ ) {
            say "$filepath contains $& ($l)";
        }
    }
}

if ( $nb_errors ) {
    say "\nAre you sure you want to commit ?";
    say "You can commit with the --no-verify argument";
    exit 1;
}
exit 0;
Run Code Online (Sandbox Code Playgroud)