首页 > 解决方案 > Git:如何重新定位到过去的特定提交?

问题描述

我想重新定位到一个特定的提交,它不是另一个分支的 HEAD,而是倒退:

A --- B --- C          master
            \
             \-- D --- E   topic

A --- B --- C          master
      \
       \-- D --- E   topic

我如何以优雅和通用的方式实现这一目标?

一般来说,我的意思是目标提交 (B) 可能不一定是 HEAD 的直接祖先(我不妨变基为 A 或以前的提交),并且主题分支上可能不仅仅是两个提交。我可能还想从 B 变基到 A。

标签: gitversion-controlgit-rebase

解决方案


使用 git 樱桃挑选

git rebasegit cherry-pick类固醇。

如果您只有几个提交要移动:您可以使用git cherry-pick它们一一挑选

# move back to B
git checkout B

# start a branch here, and use it as the active branch
git checkout -b wip

# cherry-pick the commits you want to have
git cherry-pick D
git cherry-pick E

# if all went well : move the 'topic' branch to the current branch :
git checkout topic
git reset --hard wip

# delete the temporary 'wip' branch
git branch -d wip

使用 git rebase

正如评论中提到的:git rebase可以采取额外的选项来仅移动一系列提交。

您可以使用以下命令执行与上述cherry-pick序列相同的操作:

git rebase --onto B master topic

额外说明: git rebase -i

git rebase还有一个--interactive|-i标志:

git rebase -i --onto B master topic

使用-iflag : 在执行任何操作之前,git 会为您打开一个文本编辑器,其中将列出所有重新定位的提交。

此步骤的明显好处是向您展示将应用的内容(在实际应用之前),并且还可以描述更多的操作,而不仅仅是“选择那个提交”。

你可以在网上搜索更完整的教程git rebase -i,这里有一个:
Git Interactive Rebase, Squash, Amend and Other Ways of Rewriting History (thoughtbot.com)


推荐阅读