git:更好的 git revert 方法,无需额外的还原提交

标签 git revert

我在远程+本地分支中有一个提交,我想将该提交从历史记录中删除并将其中一些放入自己的分支中。

基本上,现在我有:

           D---E---F---G master

我想要:

             E---G topic
            /
           D master

这应该在我的本地和(只有一个,称为 origin)远程存储库中。

哪种方法最干净?

此外,还有其他人已经克隆了那个 repo 并检查了 master 分支。如果我在远程仓库中进行这样的更改,“git pull”是否可以让他们也达到相同的状态?

最佳答案

如果您已经发布,那么您不想重写 master 的历史是对的。您想要的是将提交发布到 master,使其恢复到 D 时的状态,同时保留其当前历史记录,以便其他用户可以轻松地 merge 或重新设置他们的工作。

如果您计划在将来某个时候将 topic merge 到 master 中,那么您可能还想做的是在 之间建立一个新的公共(public)基础mastertopic,这样当您随后 merge topic 时,您不会丢失在 master 中还原的提交.最简单的方法是在“撤消”提交之上进行“重做”提交,将 master 重置回其原始状态并基于新的 topic 分支最重要的是。

# checkout master branch (currently at G)
git checkout master

# Reset the index to how we want master to look like
git reset D

# Move the branch pointer back to where it should be, leaving the index
# looking like D
git reset --soft HEAD@{1}

# Make a commit (D') for the head of the master branch
git commit -m "Temporarily revert E, F and G"

# Create the new topic branch based on master.
# We're going to make it on top of master and the 'undo'
# commit to ensure that subsequent merges of master->topic
# or topic->master don't merge in the undo.
git checkout -b topic

# Revert the undo commit, making a redo commit (G').
git revert HEAD

作为替代方案,您可以提交 E'、F' 和 G',分别重做每个部分,但由于 E、F 和 G 已经在您发布的历史记录中,如果您只引用“撤消”提交和说该提交正在撤消。无论如何,这就是 git revert 所做的。

基本上你所知道的就是这个。

D -- E -- F -- G -- D'      <-- master
                     \
                      \
                        G'  <-- topic

重要的是你没有重写历史,主题是基于 master 的,所以 merge 不会意外地应用任何“撤消”提交。您现在可以安全地将 mastertopic 推送到您的远程存储库。

关于git:更好的 git revert 方法,无需额外的还原提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1526670/

相关文章:

Git 子树。为什么我不能从子树而不是根分支?

Windows 的 Git bash 不提示输入密码

git - 如何将单个文件恢复到以前的版本?

intellij-idea - Intellij IDEA 无法撤消

eclipse - 从命令行恢复到以前的配置?

git - 反向将提交应用于工作副本

git - 即使在添加 ssh key 后也无法克隆任何 git repo

git - 使用 ssh-keygen 创建 SSH key 不会创建 .ssh 文件夹

c# - 如何在 VS Code 中禁用 pop GitHub

svn - 颠覆: Can trunk be reset to previous revision after branching/tagging?