'Why does extracting a specific git tag to a /tmp directory mess up the working tree?

Because I wanted to look at the files in the last release, tagged v2.1, to run it in isolation from my working directory, I created a tmp directory

mkdir /tmp/lastRelease

and extracted the last release in that directory

git --work-tree=/tmp/lastRelease checkout tags/v2.1 -- .

The files are indeed extracted just fine to /tmp/lastRelease.

But now when I run git status in the working directory I find that very many files (all the files modified since tag v2.1?) appear as staged for commit, and another long list of files (that are in HEAD) appears as not staged for commit.

Was this last command the right way to extract a specific tag? How do I reset to HEAD? (The obvious git checkout HEAD doesn't modify what git status says, even though the files are there.)

git


Solution 1:[1]

This is only a partial answer. I don't know why the working directory gets messed up when extracting to an unrelated directory, but it's possible to return to a sane state—the one where the repo was just before the git --work-tree... command—by running:

git reset --hard HEAD

Solution 2:[2]

What you wanted to do was either

git archive v2.1 | tar Cx /path/to/tmp/tree

or

git worktree add /path/to/tmp/tree v2.1

or

git clone -sb v2.3 . /path/to/tmp/tree

or even

scratch=`mktemp -d`
GIT_INDEX_FILE=$PWD/.git/scratch-index git --work-tree=$scratch read-tree -um v2.1

because as @torek points out git checkout is a convenience command, built for "standard" workflows where your work trees are for content you're actively tracking; the index is Git's manifest for what you last checked out or added there, and HEAD is its ancestor commit.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Calaf
Solution 2 jthill