Search code examples
gitgithubresethead

GIT: Detached Head -> make current head


I committed by mistake a big docker image tar file and then pushed it. When I noticed the push was taking too long I aborted it. Then, I removed the tar and did a new commit (instead of amending the previous).

I decided to go back, doing a git reset -soft, remove the file on the commit it was added, and amending that commit. (I think I checked out a commit sometime in this timeline) Then I push with ---force-with-lease

but now I get this with git status:

HEAD detached from adc7f05
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)

(the unstaged changes is only a minor new posterior change - does not apply to the problem)

What I should do to make the current situation the head?

git reflog:

dc82def (HEAD) HEAD@{0}: commit (amend): Fix conversion on all converters
adc7f05 HEAD@{1}: checkout: moving from master to HEAD@{3}
ffe3448 (remote-github/main, origin/master, master) HEAD@{2}: reset: moving to HEAD~2
adc7f05 HEAD@{3}: reset: moving to HEAD~1
7b5dbfb HEAD@{4}: commit: Remove tar
adc7f05 HEAD@{5}: commit: Fix conversion on all converters
588e4d5 HEAD@{6}: commit: Add multiline
ffe3448 (remote-github/main, origin/master, master) HEAD@{7}: commit: Add bulk page
84017af HEAD@{8}: commit: Add export possibility to all models

note: (I push to two repositories, hence what appears on ffe3448)

Thanks


Solution

  • Well, you asked to go to a revision in the reflog:

    checkout: moving from master to HEAD@{3}
    

    Which means that you ran something like:

    git checkout HEAD@{3}
    

    That will automagically get you into detached HEAD because you are no longer working with a branch. Now, why did you do that? I don't know..... but here's what you can do to get back on track:

    git checkout 7b5dbfb
    git reset --soft adc7f05
    git commit --amend --no-edit
    # now you have what you would like to have in master, right?
    git branch -f master
    git checkout master
    # now you have to force-push in the other 2 repos (because you rewrote history)
    

    If you can't force-push into the repos, you need to trick them with a revision following master:

    git checkout 7b5dbfb
    git reset --soft master
    git commit -m "Correcting all the mess I did"
    # this is a revision _after_ master that gets the content of the tree to what it was in 7b5dbfb
    # if you like it:
    git branch -f master
    git checkout master
    git push remote-github master:main
    git push origin master