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?
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.
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.
master branch!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?
HEAD to point the new branch refindex (staging area) with the snapshot of that commitindex into your working directoryWhat does git reset [<commit>] really do?
HEAD is pointing to (Suppose you're currently on the master branch. Running git reset [<commit>] will make master point to [<commit>])index (staging area) with the contents of snapshot HEAD points toHEAD 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With