在两个提交之间移除Git提交

10

我在项目中添加了一些功能,用了4个git提交记录,现在业务方面要求删除这些功能(已经过去一个多月)。因此,我需要从现有的27个提交记录中删除那些特定的git提交记录。


如果你感觉自己很熟悉,可以尝试使用 git rebase -i head~n 命令,其中 n 是你需要回退到那些多余提交的确切数量,然后只需将它们 drop 掉。 - R11G
2个回答

8
有四种方法可以这样做:
  • Clean way, reverting but keep in log the revert:

    git revert --strategy resolve <commit>
    
  • Harsh way, remove altogether only the last commit:

    git reset --soft "HEAD^"
    
  • Rebase (show the log of the last 5 commits and delete the lines you don't want, or reorder, or squash multiple commits in one, or do anything else you want, this is a very versatile tool):

    git rebase -i HEAD~5
    

如果犯了错误:

git rebase --abort
  • Quick rebase: remove only a specific commit using its id:

    git rebase --onto commit-id^ commit-id
    
  • Alternatives: you could also try:

    git cherry-pick commit-id
    
  • Yet another alternative:

    git revert --no-commit
    
  • As a last resort, if you need full freedom of history editing (eg, because git don't allow you to edit what you want to), you can use this very fast open source application: reposurgeon.

注意:所有这些更改都是本地完成的,您需要在之后使用git push将更改应用于远程。如果您的存储库不想删除提交(“不允许快进”,当您想要删除已经推送的提交时会发生),则可以使用git push -f 强制推送更改。
注意2:如果在分支上工作并且需要强制推送,则绝对应避免使用git push --force,因为这可能会覆盖其他分支(即使当前签出在另一个分支上,但如果对它们进行了更改)。最好指定强制推送的远程分支:git push --force origin your_branch

1
大多数这些方法都不适用,因为 OP 在分支内有提交记录。而且不应该建议重写共享公共分支的历史记录。 - Tim Biegeleisen
1
这个回答实际上是另一个用户对于类似问题的回答的复制粘贴:https://dev59.com/s3A85IYBdhLWcg3wHvo0#11992215 - Michael H.

6

由于你正在处理一个已发布的分支,也就是说可能有其他人在使用它,我建议你使用git revert撤销这两个提交。 在相关分支中输入:

git log

首先找到两个需要恢复的提交的SHA-1哈希值,然后使用以下命令进行还原:

git revert abcd1234..foobar12

其中abcd1234是两个提交中第一个(最旧的)提交的哈希值,而foobar12则是两个提交中比较新的那个。

使用git revert将添加提交,有效地撤消了嵌入您分支中的这两个提交。另一种方法是使用rebase或filter branch。但是,这两种方法都涉及重写您分支的历史记录。这可能会给使用您分支的任何其他人带来麻烦,因为他们将无法再拉取或推送。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接