2

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..?

jub0bs
  • 60,866
  • 25
  • 183
  • 186
user3308774
  • 1,354
  • 4
  • 16
  • 20
  • What does git status say ? – Andrew_Lvov Jan 11 '15 at 19:32
  • Save all the commit hashes before you make any changes. This way, you'll be able to recover the good commit (I believe, 6f5dsf) – Andrew_Lvov Jan 11 '15 at 19:33
  • @Andrew_Lvov `HEAD detached from 7fe7f86we6f` – user3308774 Jan 11 '15 at 19:35
  • @user3308774 What does `git branch` say? Also, how come the currently checked out commit is `7fe7f86we6f8d6` and not `6f5dsf5d65f`? Did you run `git checkout 7fe7f86we6f8d6` after creating commit `6f5dsf5d65f`? – jub0bs Jan 11 '15 at 19:39
  • @Jubobs Copy paste error. When I wrote the question, I just typed random junk as a commit ids rather than copying and pasting from my shell. So in my comment, I replaced the actual commit id, with the one I created when I made my question -- I just copied the wrong one. It should have read: `HEAD detached from 6f5dsf5d65f` as you expected. – user3308774 Jan 11 '15 at 20:08

1 Answers1

3

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.

jub0bs
  • 60,866
  • 25
  • 183
  • 186