为什么git reset --hard导致派生分支在重新定位时也会重置?

时间:2017-03-24 01:03:19

标签: git

有时我想将我在分支机构的最新工作分成一个新分支。

# Create a new branch tracking the old branch
git branch -t new-branch

# Reset the old branch to a prior commit
git reset --hard HEAD~3

git checkout new-branch

我希望git rebase现在什么也不做,因为文档说:

All changes made by commits in the current branch but that are not in <upstream>
are saved to a temporary area. This is the same set of commits that would be shown
by git log <upstream>..HEAD; or by git log 'fork_point'..HEAD, if --fork-point is
active (see the description on --fork-point below)....

因此new-branch重置为old-branch,并应用所有已保存的更改。这些已保存的更改是否不包括new-branch无法再访问的提交old-branch

相反,new-branch会重置为old-branch,并且提交会消失。

1 个答案:

答案 0 :(得分:0)

更仔细地阅读文档,我发现:

   If <upstream> is not specified, the upstream configured in branch.<name>.remote
   and branch.<name>.merge options will be used (see git-config(1) for details) and
   the --fork-point option is assumed.

因此,不是使用<upstream>..HEAD的提交,而是使用fork_point..HEAD。以下是fork_point的内容:

git merge-base --fork-point <upstream> <branch>

merge-base很复杂,但在这种情况下,它会检查reflog并实现&#34; new&#34;提交以前存在于我们分支的分支中,并返回与new-branch相同的提交,也是HEAD,因此git log fork_point..HEAD不返回任何内容。然后,rebase最终不会保存并应用新的提交。

This is explained in more detail, along with a better way to achieve the new branch, in John Mellor's answer.