Search code examples
gitgit-reset

What should RESETING detached HEAD to BRANCH do?


If I understand right, when you have a detached head(HEAD->commit), then the git CHECKOUT branch solves the issue(HEAD->branch[->someCommit])

But what does resetting to a branch do? It was supposed to set the pointer of an object(often a branch) to which HEAD points to another branch. But since we dont have this middle-man (branch) - what does it do then? And why?


Solution

  • It simply moves HEAD: as I mentioned in "Practical uses of git reset --soft?":

    git reset is all about moving HEAD.

    If you move HEAD to another commit, then HEAD remains detached.

    After a discussion about the difference between git reset and git checkout vs the detached or attached nature of the symbolic reference HEAD, here what we found together:

    • if HEAD points on branch, git reset would move branch as well to <something>: resetting it doesn't make it un-detached, it changes branch HEAD
    • if HEAD points on a commit (was already detached), then it would remain detached: As the OP puts it:

    so when detached and I call git reset <branch> it finds the commit behind the branch and change the commit in .git/HEAD for the commit that <branch> refers to.

    Let's consider a HEAD which is attached to branch1 (cat .git/HEAD would return branch1):

    • git checkout branch2 will change HEAD to branch2 and leave branch1 untouched
    • git reset branch2 will reset branch1 HEAD to branch2: cat .git/refs/heads/branch1 would contains the same SHA1 as branch2.

    That's the difference:

    • reset moves HEAD (as I told at the beginning: it is all about moving HEAD)
    • checkout switches branches (or detaches HEAD)

    Regarding the attached/detached nature of HEAD:

    • reset doesn't change the nature of HEAD (if it was attached, it remains attached)
    • checkout can change the nature of HEAD (if it was attached and you checkout a commit instead of a branch, HEAD becomes detached)