Git: 移动一个分支使其指向另一个

Git: move a branch to make it point to another

我遇到过以下情况:

-----O
     |
   master
   branch1

然后我不得不对 master 做一些修改:

 -----O-----O-----O
      |           |
   branch1      master

现在我希望 branch1 位于 master 的同一点(因此包含我所做的提交):

-----O-----O-----O
                 |
               master
               branch1

我不知道合并是否是实现此目的的正确方法。 我应该采取什么步骤?

编辑:还考虑到我有未提交的更改,应该在 branch1 与 master 保持同步后在 branch1 上提交。所以我需要保持当前更改不变,以便稍后在 branch1

上提交

在这种简单的情况下,您可以采用简单的方法:

git branch -f branch1 master

来自git help branch

git branch [--set-upstream | --track | --no-track] [-l] [-f] <branchname> [<start-point>]

编辑:保留未提交的更改:

git stash
git checkout master
git branch -f branch1 master
git checkout branch1
git stash pop

未提交的更改现在将再次未提交(或未添加,具体取决于它们之前的内容)。

这看起来是 rebase 的工作,所以我将执行以下操作:

git commit -m 'your work on branch 1'    # from branch1
git rebase master                        # also from branch1

这会将来自 master 的新提交拉入 branch1,然后在来自 master.

的提交之上重播您的提交

从功能上讲,将 master 合并到 branch1 中也应该没问题,但您可能无法维持两次提交的分辨率,而是以一次合并提交结束。

由于 branch1 引用的提交是 master 祖先 ,合并操作不会导致合并提交;相反,Git 只会向前移动 branch1 引用,以便它引用与 master 相同的提交。这称为 fast-forward 合并。

来自documentation:

When you try to merge one commit with a commit that can be reached by following the first commit’s history, Git simplifies things by moving the pointer forward because there is no divergent work to merge together – this is called a “fast-forward.”

所以,在你的情况下,你可以简单地说:

git checkout branch1
git merge master

这将使 branch1 指向与 master 相同的提交。

更新:注意你需要有一个clean working directory before doing the merge. If you have uncommitted changes in branch1 (i.e. you have a dirty working directory), you should first store them away in the stash by using the git-stash命令:

git stash save --include-untracked -m "Work in progress"

保存更改并清理工作目录后,您可以继续合并。之后,您可以通过以下命令从存储中恢复文件:

git stash pop

这会将这些文件放回工作目录并将它们从存储中删除。届时,您可以选择在任意数量的提交中提交它们。

如果您的工作目录是干净的(否则执行 'stash'),那么您处于一种特殊情况,其中 'rebase'、'merge' 和 'reset --hard' 完全按照您的要求执行想做...