Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverting a commit only a specific branch, while keeping the "merged data"

Tags:

git

git-revert

Say I have two branches A and master. A feature has accidentally been added, and completed, to branch A (which is also working on a different feature that is in a working state/merged to master but needs to be continued on later).

Now I wish to remove the commit(s) that produced the new feature from A while keeping the master state in the current HEAD. Ideally something like:

git checkout A
git revert HEAD~2..HEAD

However wouldn't this also revert the HEAD of master branch?

like image 963
paul23 Avatar asked Oct 30 '25 17:10

paul23


2 Answers

Solution with rewriting history:

git checkout A
git reset HEAD~2
git push origin A --force

An important thing is that after git reset command all your changes from the two latest commits will be available in the working directory. It gives you an opportunity to create another branch and continue working on it or stash if needed.

Solution without rewriting history:

git checkout A
# automatically commits
git revert HEAD~2..HEAD
git push origin A

or

git checkout A

# doesn't commit automatically 
git revert --no-commit HEAD~2..HEAD

git commit -m 'Revert two last commits'
git push origin A

It will add a new commit to reverse the effect of two latest commits.

All the above solutions doesn't change master branch!

Theory:

HEAD is the pointer to the current branch reference, which is in turn a pointer to the last commit made on that branch.

What does git checkout [<branch>] really do?

  • changes HEAD to point the new branch ref
  • populates your index (staging area) with the snapshot of that commit
  • copies the contents of the index into your working directory

What does git reset [<commit>] really do?

  • moves the branch that HEAD is pointing to (Suppose you're currently on the master branch. Running git reset [<commit>] will make master point to [<commit>])
  • update the index (staging area) with the contents of snapshot HEAD points to

HEAD is a pointer to the current active branch.

After running git checkout A, acting on HEAD will modify A and not master,
after running git checkout master, acting on HEAD will modify master and not A.


an extra note :

If your intention is to "cancel the last two commits from branch A", you can run :

git checkout A
git reset --hard HEAD~2

# if branch A was pushed,
# you will also need to push the corrected A :
git push origin --force-with-lease A
like image 22
LeGEC Avatar answered Nov 02 '25 07:11

LeGEC