In most cases checking out a previous commit is safe. But since .gitignore
is version controlled as well, checking out an old commit with an older version of .gitignore
can have serious side effects.
Imagine that our latest commit includes the following files:
.gitignore
ignores config.properties
config.properties
our main configuration fileSince git ignores config.properties
reverting to an older commit will keep config.properties
as is.
But since older commit doesn't ignore config.properties it now appears as an added file.
In order to checkout the latest commit again, one can either:
Each of which isn't ideal. Each comes with a side effect.
Committing files or ignoring files (updating .gitignore) creates a new head. Removing files, or stashing them will remove those files our of version control. Meaning that when returning to our latest commit those files will be missing.
What is the safest approach to checkout a previous commit?
If you are worried about any changes to your working directory, just use git worktree
git worktree add ../<new dir> <sha or branch>
Edit: sorry misremembered the syntax best to check the docs