Home > Mobile >  Revert all commits from branch after merging into master
Revert all commits from branch after merging into master

Time:10-19

Few months ago I did lots of changes in my code and pushed it into master.

Now I need to remove all the changes I made, and pushing the initial state of the branch back to master.

I'm confused with all the commands and don't wanna mess my git, How can I reset a branch to his initial state?

CodePudding user response:

In the new days, you can get the working tree just like a previous revision (or actually, any revision... even from other branches) using restore:

git restore --staged --worktree --source=<the-revision> -- .

Then, you can commit with whatever you think makes sense:

git add . # maybe this is not needed because I used --staged, but I am not that familiar with the UI so....
git commit -m "Taking it back to how it was back then"

The old way would take a few steps, but it works just as easily, no hassle:

git checkout the-commit-with-content-I-want
git reset --soft the-branch-where-i-want-it
git commit -m "Taking it back to blahblah"
# now you have a revision past the-branch-i-want
# check that you like what you see in history with git log and stuff.... also check files contents and so on
# when you are confident, move the branch pointer:
git branch -f the-branch-where-i-want-it
git checkout the-branch-where-i-want-it

And you are done

CodePudding user response:

Another way to "reset" a branch back to some earlier state and not modify any of the existing history is to use git apply being fed the output from a diff:

git checkout master
git status # Should report "nothing to commit, working tree clean"
git diff HEAD initial-state-of-the-branch-commit | git apply -
git commit -m "Reset back to initial state of the branch" -m "Using command: git diff HEAD initial-state-of-the-branch-commit | git apply -"
  • Related