gitgit-checkoutgit-resetgit-index

How does Git restore index and wokring directory internally (upon reset/checkout)?


I understand that when I checkout or reset --hard to a specific commit/branch then I get the relevant contents in my working directory and the index file.

But how does Git internally re-build the index and working directory contents upon checkout or reset --hard.

Is the index restoration done by reading the tree pointed to by the the commit we have checked-out/reset to ?

Is the working directory also restored the same way ?

Does that mean that after reset --hard or checkout <some_branch> the index and working directory will always match the tree of that commit because they were rebuilt from it ?


Editing: What I'm basically asking: is the restoration of the index/WD content done using the tree pointed by the commit we have arrived at ? Because as I see it there is no other way for git to fetch that content rather than from the commit history


Solution

  • Does that mean that after reset --hard or checkout the index and working directory will always match the tree of that commit because they were rebuilt from it ?

    Short answer: YES

    Long answer:

    git checkout:

    Updates files in the working tree to match the version in the index or the specified tree.

    https://git-scm.com/docs/git-checkout

    git-reset --hard:

    Resets the index and working tree. Any changes to tracked files in the working tree since are discarded.

    https://git-scm.com/docs/git-reset

    Both of these commands move HEAD, which then inspects whatever commit its been moved to, and alters the index and/or WD accordingly. If it doesn't alter one or both, it still acts as the keeper of the state of your files at the time of that commit and allows you to run commands to compare your WD and index to the state of your files at that moment in time.

    I hope that is helpful, I was unsure as to exactly what you are looking for with your question.