How can I make an older commit HEAD in Git?
I'm still trying to learn the (basic?) finer points of Git and have managed to get myself into trouble. I realized that I made some mistakes on HEAD, checked out an older commit and started coding from there. When I attempt a push I'm told that my current commit is behind and I need to merge with HEAD. Git recommends "git pull". However, HEAD has the code I want to ignore. How do I solve this problem? Thanks so much for the help.
Flowchart:
-------- HEAD (bad) ---------------------- + (behind conflict, requires
\ / merge with HEAD, which is
\------- Current commit (good) ----/ bad and needs to be ignored)
Solution 1:
Here is what you can do:
git checkout <branch-to-modify-head>
git reset --hard <commit-hash-id-to-put-as-head>
git push -f
If you don't force the push, git will throw this error: Updates were rejected because the tip of your current branch is behind.
Note that this will tamper your git history, so another way of doing this is revert each commit you don't want. That way you retain your history:
git revert commit-id
Cheers
Solution 2:
If your repository isn't being used by other people, you can safely do git push -f
to overwrite the remote branch.
Solution 3:
The way I do it is:
git reset --hard <commit-SHA>
git push origin HEAD:<name-of-remote-branch>
It's the way git recommends and doing git push -f
might be a little problematic for everyone else in the development team
Solution 4:
The only thing that worked for me:
git checkout <OLD_COMMIT>
git branch temp
git checkout temp
git branch -f master temp
git checkout master
git branch -d temp