Search code examples
gitgit-resetgit-detached-head

How can I reset my branch to a commit I created while in detached-HEAD mode?


I've got no idea what the Git graph looks like in this instance, so before I accidentally lose any code, I figure I'll ask for help.

I committed some code that broke things, so I checked out a previous commit to look at what went wrong.

commit 87dfs7f6d6fs8 (latest commit on master) 
commit 7fe7f86we6f8d6 <-- checked out this guy

However, I forgot to recheckout master to fix the problem, and instead fixed it in the detached-HEAD state.

So, now, my Git history looks something like this... (I guess)

commit 87dfs7f6d6fs8 (latest commit on master) 

  |--- commit 6f5dsf5d65f <-- New commit (currently checked out)
commit 7fe7f86we6f8d6 <-- checked out this guy

What I'd like to do is completely get rid of the topmost commit and keep the changes that I made. I think to do this I need to reset --hard to the commit hash I'm currently on, right?

So, it'd be:

git reset --hard 6f5dsf5d65f

Where commit 6f5dsf5d65f is the commit I did in the detached-HEAD state. Is this right..?


Solution

  • What I'd like to do is completely get rid of the topmost commit [87dfs7f6d6fs8] and keep the changes that I made.

    If I understand your problem correctly, you basically need to

    1. stash uncommitted changes (if any),
    2. make the master branch point to commit 6f5dsf5d65f instead of 87dfs7f6d6fs8,
    3. pop the stash (if necessary).

    Check whether you need to create a stash by running git status. If it tells you that you have a clean working state, run

    git checkout master            # important!
    git reset --hard 6f5dsf5d65f
    

    Otherwise, run

    git stash save 
    git checkout master            # important!
    git reset --hard 6f5dsf5d65f
    git stash pop
    

    Note that, in either case, you need to check out master before you can reset it; running git reset while in detached-HEAD state would only move HEAD.