Restore deleted file with history in git
It is possible, with help of Git copy file preserving history you need to copy the file before it was deleted.
I will write here a complete example. First I will prepare some test repository:
git init
echo "test content" > file.txt
git add file.txt
git commit -m "start"
echo "test content 2" >> file.txt
git commit -am "next commit"
rm file.txt
git commit -am "Delete file, lose history"
Now we have a test repository without the file. To restore the file with its commit history the process is following: create a branch where the file did exist. Then make two copies of this file, each with history. Then merge back to master and only one of the two copies will get deleted during the merge.
Be sure to use your commit hash instead of 190112b
in example below.
git checkout 190112b -b before-deletion
git mv file.txt file1.txt
git commit -m "Move file (1)"
SAVED=`git rev-parse HEAD`
git reset --hard "HEAD^"
git mv file.txt file2.txt
git commit -m "Move file (2)"
git merge $SAVED
git commit -a -n
OK, so now in this branch we have two copies of this file. Each copy preserves history. Now when we merge this back into master, one file will disappear (or will have wrong history), the other one will keep the history.
git checkout master
git merge before-deletion
git commit -a -n
git rm file1.txt
git mv file2.txt file.txt
git commit -m "recovery finished"
And that's it.
Just encountered a similr scenario, paste the possible solution here.
A file gets deleted earlier, now I need to restore.
Two steps: 1. Locate the commit which deletes the file 2. Restore the file from that commit.
git log --all --stat --diff-filter=D -- test.log
(Say the file name is test.log)git restore --source aec723390^ test.log
(Say the output of the step 1 is "aec723390", note the^
)
Sure, just check it out from a commit where it existed. If the commit that deleted the file is the tip of whatever you have currently checked out, that’s HEAD^
(the commit before last):
git checkout HEAD^ -- path/to/file
Then you can commit and push it.