Search code examples
gitgithubgit-branchgit-merge-conflict

safe way to revert git branch to last commit?


I have checked out to one of the branches local, I committed the changes made and I did git pull origin master there was a conflict in one of my files named app.scss , I started solving the conflicts in this file by mistake I deleted my changes I accepted incoming changes, that was wrong I need my changes back

Here is the git log

PS C:\makumba> git log 
commit d4c3dd49cba1931fce44aa8a7078842d0c1cece0 (HEAD -> features/Email_footer)
Author: <authorname>
Date:   Tue Jun 1 13:30:28 2021 +0200

    video footer
........

Question How do I get my changes back? do I need to revert to the last commit like this below?

git reset --hard HEAD

Solution

  • I don't think you're going to get your changes back if they were never staged or committed. Accepting incoming changes applies those changes to your working copy, which is the most volatile place and means unless your operating system has some form of restore functionality or you made a copy of the entire repo and working copy before you started, you're out of luck, sorry.

    To avoid this happening again, I recommend getting to grips with git reset, as you rightly suggested it would be the answer if you hadn't already lost your working copy changes (also you could have committed to a branch first before pulling in the remote changes):

    • git reset --soft [ref] will change the branch that HEAD is pointing to, to whatever [ref] is. [ref] could be HEAD~1, which would mean "the revision before HEAD". Note this changes the branch, not just the HEAD pointer. So if HEAD is pointing to MAIN, then it's MAIN that'll move and you'll have dangling commits (you can find them again using git reflog as long as you don't make too many changes or wait too long before looking for them).
    • git reset --mixed [ref] will do the same as git reset --soft, but will also update the index to match (i.e. will leave your working copy with your changes alone).
    • git reset --hard [ref] will so the same as git reset --mixed, but will also update the working copy to match the index. This is the dangerous one as you could lose your unstaged, uncommitted changes.

    See https://git-scm.com/book/en/v2/Git-Tools-Reset-Demystified for more details. Sorry for your loss.