0

I'm trying to restore a folder I deleted in a local branch but I am having trouble doing it. I have created a new branch from main and deleted one of the folders, while I worked on the branch and did 10 commits later.

Now, I want to have the deleted folder in the working directory along with the git indexing.

I have tried -

git checkout HEAD~10 -- ./gt/foo/

referring to this question but I keep getting -

error: pathspec './gt/foo/' did not match any file(s) known to git

I have also tried -

git restore -s main -SW -- gt/foo

to pull the folder from main working branch but got the same error.

What can I do to restore this folder?

SKG
  • 332
  • 3
  • 23

1 Answers1

1

First, use git log to get a list of all the commits that modified the folder. The most recent one will be the one where it was deleted. Here is an example repo, where I created and then deleted a folder called hello/world:

$ git log -p -- hello/world

enter image description here

Then, we can take the commit before the one it was deleted by using ~1:

git restore --source=27f1f1adf~1 -- hello/world

This will restore the folder to the current directory without staging it, but you can stage it with git add:

enter image description here

Make sure that git log shows the name of the removed folder. If git log doesn't find it, you're searching in the wrong directory (are you at the root of the project? Did you get the path right?)

Once you've verified that the name and path are correct, you can actually combine both these steps in bash or zsh (replace with the name of your folder):

git restore --source="$(git log --pretty=format:"%H" -n 1 -- hello/world)"~1 -- hello/world

This will find the last commit that modified the folder (AKA, the one where it was deleted), and then it will restore the deleted folder:

enter image description here

Alecto Irene Perez
  • 10,321
  • 23
  • 46