Git Remove Specific commits

左心房为你撑大大i 提交于 2019-12-08 03:10:35

问题


Lets say i've commits 1,2,3,4,5. commit 2 and 5 is mine the rest is done by others. becuase of 3,4 commit there is some error! I've pushed the commits. commit 5 is the changes i want to apply on commit 2.

i want to rollback to commit 2 and apply my new changes commmit 5.

How should i remove specific commits 3 and 4 alone?


回答1:


Do a rebase:

git rebase -i HEAD~5

This will open an editor window; just delete the pick lines corresponding to commits 3 and 4. Quit the editor: the rebase will proceed.

Note: dangerous, and source of conflicts; if the rebase fails for some reason, either fix it (by hand; see the git rebase manpage) or abort it with git rebase --abort)

When the rebase is done, push with the -f option. But people working with you on this repo will not thank you!




回答2:


Here's another method just for variety.

What you should ideally do is to create new commits on top of 5 which will revert the code in commits 3 and 4.

If you have not pushed these commits, you can also do a cherry-pick. Say your repo's HEAD points at 5 and it is the branch master.

1 -> 2 -> 3 -> 4-> 5 (HEAD, master)


git co -b temp

1 -> 2 -> 3 -> 4 -> 5 (HEAD, master, temp)


git co master
git reset --hard HEAD~3

1 -> 2 (HEAD, master)-> 3 -> 4 -> 5 (temp)


git cherry-pick temp

1 -> 2 -> 3 -> 4 -> 5 (temp)
     |
     -> 5' (HEAD, master)


git branch -D temp

1 -> 2 -> 5' (master, HEAD)


I think this is what you want. Although you'll do better to create revert commits on top of 5.

Note: The method given by @fge is more succinct and best if you have done an interactive rebase before. If not, this one will give you a fighting chance since you can always just merge master back to temp and get to the point from where you started.



来源:https://stackoverflow.com/questions/21899440/git-remove-specific-commits

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!