I was experimenting with my app, made a few commits (about 5) and my app was working fine 5 commits before. I was editing multiple files during my experimenting. How can I revert my all changes I did and go back to the state of the code that was 5 commits before. For example, if I do hard reset to the commit I want to be at, it works fine, but if I push the changes, I need to merge or rebase which does a same thing for me as I don’t know the difference between them. They merge the changes from the remote branch to my local branch and all the changes go back to the latest state of the remote branch. So, I want to make the commit with a message Reverting the state as 5 commits before
that removes all the changes I did during 5 last commits and before that commit should be a commit with all the changes I did during 5 commits. How can I do it? I use Android Studio with Bitbucket.
Question posted in Android Studio
The official documentation can be found here.
The official documentation can be found here.
2
Answers
To create a single commit that reverts the previous five commits:
(NOTE: user michid’s approach to the "reverting" portion of your question is quite a bit more succinct and streamlined than my own solution; I’d recommend reviewing it as a better alternative).
git diff <the_hash_for_that_specific_commit>
)git diff <the_hash_for_that_specific_commit> > mypatch.patch
git apply -R mypatch.patch
rm mypatch.patch
to get it out of your working directory, then add all changes and commitThere are other ways to do this as well, but I think this is a relatively quick approach. However, others may provide easier or faster alternatives.
You also stated that you might want to combine the previous five commits into their own single commit first before you do the above approach. There are two ways you could go about that I can think of:
To combine five commits into a single commit
First approach–
git reset
git reset --soft HEAD~5
.Second approach–
git rebase -i
git rebase -i <the_branch_you_are_already_branched_off_of>
would work, but there might be a cleaner way to identify a specific commit.pick
tosquash
You might want to add a rescue tag or create a new branch to experiment with this, so you don’t accidentally bork your branch or lose any work.
Also, keep in mind that if you first combine the five commits you want to revert into a single commit, you’d want to make sure you targeted the new single commit for a revert. That said, if you combine them all into a single commit first, then it would probably be easier to just do
git revert <the_new_single_combined_commit>
to revert it.You can revert the last 5 commits first
and then commit all the changes
all together.