Git: revert on older commit

无人久伴 提交于 2021-01-28 23:23:40

问题


I did some changes on my git repo and did some commits. Here is what I want to do, say my git history looks as HEAD --> c1 --> c2 --> c3 --> c4. Questions 1) Now if I revert c1, does it revert all c2, c3, c4 as well ? My understanding it reverts only c1 and leave c2, c3, c4 as is. 2) Now I want to revert all c1, c2, c3 and c4 and move back to HEAD. What is the best way to do this.


回答1:


Revert will create a commit that will undo the changes of the revision you want to revert.

So if you do:

git revert c1

You will end with:

revertC1 -> (previous HEAD) -> c1 -> c2 -> c3 -> c4 ...

And It will only revert that commit changes.

So, for your scenario where you want to remove four commits previos to the HEAD:

HEAD -> c1 -> c2 -> c3 -> c4

which is the same as:

HEAD -> HEAD~1 -> HEAD~2 -> HEAD~3 -> HEAD~4

If you want to remove the four commits before the current one. you can do

git revert HEAD~5..HEAD~1

You will be prompted to create the commit messages for each revert, and perhaps to solve conflicts.

In case you HAVE NOT PUSHED your changes, what I would do to keep the history log clean would be:

Undo the current commit and keep the code changes

git reset --soft HEAD~1

Store the code changes

git stash

Undo the last four commits and erase code changes

git reset --hard HEAD~4

Make sure I delete any created files and directories

git clean -di

Re apply the changes from the top commit which is the one I wanted to keep

git stash pop

*Fix conflicts in case there will be When there are no conflicts. Commit my changes

git commit -am "My new changes"

If ready to push, push.

git push

This, only if you HAVEN'T PUSHED your changes.




回答2:


If you revert c1 it back source to c1 state, but it will create new commit(c5) with all changes from c4 to c1.

[HEAD]--> c1 --> c2 --> c3 --> c4 --> c5 (c1 state)
           |__________________________/\
                     revert


来源:https://stackoverflow.com/questions/35879142/git-revert-on-older-commit

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