Remove a directory permanently from git

Viewed 45811

In my personal git repo, I have a directory that contains thousands of small images that are no longer needed. Is there a way to delete them from the entire git history? I have tried

git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch imgs" HEAD

and

git filter-branch --tree-filter 'rm -fr imgs' HEAD

but the size of the git repo remains unchanged. Any ideas?

Thanks

7 Answers

The ProGit book has an interesting section on Removing Object.

It does end with this:

Your history no longer contains a reference to that file.
However, your reflog and a new set of refs that Git added when you did the filter-branch under .git/refs/original still do, so you have to remove them and then repack the database. You need to get rid of anything that has a pointer to those old commits before you repack:

$ rm -Rf .git/refs/original
$ rm -Rf .git/logs/
$ git gc
$ git prune --expire 

(git prune --expire is not mandatory but can remove the directory content from the loose objects)
Backup everything before doing those commands, just in case ;)

git-filter-branch by default saves old refs in refs/original/* namespace.

You need to delete them, and then do git gc --prune=now

Answer for the year 2021

This surprisingly turns out to be hard task. Google turns up pages that are way back dated to 2009 and StackOverflow discussions almost a decade old. Lot of those things don't work any more!

Here's what works (also recommended way according to git docs):

First install git-filter-repo:

pip install git-filter-repo

Next, delete folders from git history. This will rewrite entire Git history except for the excluded folder!

git filter-repo --force --invert-paths --path to/folder1 --path to/folder

Next, add back the remotes:

git remote add origin https://...

Next, force push upstream:

git push --force --set-upstream origin master

So that's the bunch of commands but I haven't found a shorter better way.

Related