我知道这是在改写历史,很糟糕。

但是如何从远程分支永久删除少数提交?


当前回答

 git reset --soft commit_id
 git stash save "message"
 git reset --hard commit_id
 git stash apply stash stash@{0}
 git push --force

其他回答

 git reset --soft commit_id
 git stash save "message"
 git reset --hard commit_id
 git stash apply stash stash@{0}
 git push --force

例如,如果你想删除最近3次提交,运行以下命令从文件系统(工作树)中删除更改,并在本地分支上提交历史(索引):

git reset --hard HEAD~3

然后运行以下命令(在您的本地机器上)强制远程分支重写其历史记录:

git push --force

恭喜你!全部完成!

一些注意事项:

您可以通过运行命令检索所需的提交id

git log

然后你可以像这样用<desired-commit-id>替换HEAD~N:

git reset --hard <desired-commit-id>

If you want to keep changes on file system and just modify index (commit history), use --soft flag like git reset --soft HEAD~3. Then you have chance to check your latest changes and keep or drop all or parts of them. In the latter case runnig git status shows the files changed since <desired-commit-id>. If you use --hard option, git status will tell you that your local branch is exactly the same as the remote one. If you don't use --hard nor --soft, the default mode is used that is --mixed. In this mode, git help reset says:

重置索引,但不重置工作树(也就是说,更改的文件是 保存但未标记为提交)并报告未保存的内容 更新。

只需要注意在恢复一个无效提交时使用last_working_commit_id

git reset --hard <last_working_commit_id>

所以我们不能重置为我们不想要的commit_id。

然后当然,我们必须推到远程分支:

git push --force

有时,修复这个问题最简单的方法是从您知道代码良好的地方创建一个新的分支。然后,您可以不去管错误的分支历史记录,以防稍后需要从中挑选其他提交。这也确保您不会丢失任何提交历史记录。

来自你当地的错误分支:

git log

复制你想要分支所在的提交哈希并退出git日志

git checkout theHashYouJustCopied
git checkout -b your_new_awesome_branch

现在你有了一个你想要的新分支。

如果你还需要从错误的分支中保留一个特定的提交,而它不在你的新分支上,你可以选择你需要的特定提交:

git checkout the_errant_branch
git log

复制你需要拉入好的分支的提交哈希并退出git日志。

git checkout your_new_awesome_branch
git cherry-pick theHashYouJustCopied

拍拍自己的背。

从pctroll的答案简化,类似的基于这篇博客文章。

# look up the commit id in git log or on github, e.g. 42480f3, then do
git checkout master
git checkout your_branch
git revert 42480f3
# a text editor will open, close it with ctrl+x (editor dependent)
git push origin your_branch
# or replace origin with your remote