Restoring a directory from history is a straightforward process in Git, similar to reverting or resetting a single file. But what if you need to retrieve an entire directory from the repository’s history?
The solution is simple:
git checkout -- /path/to/dir
This command restores the directory from the specified “treeish” for the given /path/to/dir. Let’s walk through an example:
First, let’s delete a directory and then merge in numerous changes. For instance, let’s assume we’re working on a refactoring branch of Jekyll, the static blog engine powering this site.
Here’s what the history might look like:
Hopefully, this history isn’t too convoluted. Essentially, the commit we just made is quite far down in history, which is often the case when you need to restore a directory. First, we need to determine the reference to the commit containing the directory we want to retrieve. In this scenario, let’s say the last commit was the merge, and the commit before that involved deleting the directory. Therefore, the commit we wish to reference is the third commit in history, or HEAD2. Alternatively, you could reference it by the branch name (test2) or even go back one step from the SHA of the deletion (f46666d^).
If you attempt to check out a directory from a revision where it doesn’t exist, you’ll receive a helpful message:
$ git checkout test~1 -- bin/
error: pathspec 'bin' did not match any file(s) known to git.
So, let’s check out the correct revision and finally restore our directory to its rightful place:
Excellent! We’ve successfully restored the directory. Now you can proceed to add or commit the file as necessary.
If you find yourself in this situation, you may also consider reverting the commit, which could potentially restore the deleted files as well. However, this approach isn’t always feasible and may not be the most suitable method for retrieving the missing directory from history.