Welcome to the next pikoTutorial!
The error we’re handling today is a Git error:
fatal: reference is not a tree
which occurs when trying to copy file from another branch using command:
git checkout <commit-hash> -- /path/to/file
What does it mean?
It means that the commit hash you provided was not recognized by Git as a valid object which could be used to copy the file.
How to fix it?
Incorrect commit hash
The simplest reason is that you just entered an invalid commit hash. Make sure that the hash you’re using actually exists by calling:
git rev-parse <commit-hash>
If this command does not return the hash, it means that it does not exist.
Shallow clone of the repository
If your repository is a shallow clone (e.g. it has limited history), although the commit hash is available on the origin, it might now be available in your local copy of the repository. Clone the entire repository or call:
git fetch --unshallow
Non-commit hash
Make sure that the hash you used is actually a hash representing a commit and not some other type of object (e.g. tag or blob).
File does not exist in the given commit
It may happen that the state of the repository represented by the hash you provided just doesn’t contain the file you want. You can check this by using:
git ls-tree -r <commit-hash> /path/to/file
Switch -r
allows in this case to search recursively through all directories. If your file exists in the commit represented by the hash you provided, this command will list that file.
Use branch name instead of commit hash
If the exact commit does not matter and all you want is to align one of the files with the state from another branch (e.g. to revert changes back to the state on master branch), just use the name of the branch instead of the exact commit hash:
git checkout master -- /path/to/file