Safe git rebase

时间:2016-08-13 13:32:27

标签: git rebase

Quite often, when working on one thing, I find some ugliness in unrelated code, fix it and commit separately. Usually, there are multiple such commits, as I find similar problems later.

Finally, I rebase (reorder and squash) so that the commits make more sense. Sometimes, I get merge conflicts and sometimes the resulting working tree differs from the one before rebasing.

  • Can such a difference occur even when there were no conflicts?
  • Is there a way to get a (huge blinking) warning when the difference occurs?

1 个答案:

答案 0 :(得分:3)

  

即使没有冲突,也会出现这种差异吗?

也许不是,但人为错误是我们应该经常考虑的因素。

  

当出现差异时,是否有办法获得(巨大的闪烁)警告?

这应该做:

git diff ORIG_HEAD HEAD

要自动执行此操作,请使用post-rewrite挂钩(请参阅Git Hooks):

  

重写后

     

这个钩子是由重写提交的命令调用的(git commit --amend,git-rebase;当前git-filter-branch不会调用它!)。它的第一个参数表示它被调用的命令:当前是修改或rebase之一。将来可能会传递更多与命令相关的参数。

然后在钩子脚本.git/hooks/post-rewrite中我们可以比较ORIG_HEADHEAD,如果不同则发出警告:

#!/bin/sh

diff_rebase() {
    # echo "Old HEAD: $(git rev-parse ORIG_HEAD)"
    # echo "New HEAD: $(git rev-parse HEAD)"
    if ! git diff --quiet ORIG_HEAD HEAD; then
        >&2 echo "NOTE: diff detected after rebase!"
    else
        echo "rebase well done"
    fi
}

# bypass git amend
[ "$1" = "rebase" ] && diff_rebase

要使钩子全局可用,请考虑配置core.hooksPath,例如:

git config --global core.hooksPath /usr/local/git-hooks/

然后将脚本保存为/usr/local/git-hooks/post-rewrite,并设置可执行权限。

注意:遗憾的是,当使用自定义挂钩目录时,似乎存在交互式rebase即git rebase -i没有触发挂钩的错误。 (我使用的是git 2.9.2)