Mikko Kortelainen

Remove Unwanted Files From Git History

Here's an example of how to remove every *.pyc file from every commit in Git history. It is adapted from this Git help page.

Rewrite history

Run git filter-branch, forcing (--force) Git to process—but not check out (--index-filter)—the entire history of every branch and tag (--tag-name-filter cat -- --all), removing the specified files ('git rm --cached --ignore-unmatch *.pyc') and any empty commits generated as a result (--prune-empty).

Be careful! This will overwrite your existing tags.

$ git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch *.pyc' \
--prune-empty --tag-name-filter cat -- --all

Ref 'refs/heads/master' was rewritten
Ref 'refs/remotes/origin/master' was rewritten
WARNING: Ref 'refs/remotes/origin/master' is unchanged

Add a .gitignore entry

This is to prevent you from committing the files again.

$ echo '*.pyc' >>.gitignore
$ git add .gitignore
$ git commit -m 'Ignore .pyc files'

Force-push to remote

If you have a remote repository, the push must be forced so that all remote branches and tags and rewritten.

$ git push origin --force --all
$ git push origin --force --tags

Fix every copy of the repository

You can delete and re-clone every copy of the repository, or rebase, or delete every affected branch and re-create them.

For example to rebase:

$ git fetch --all
$ git rebase <lastest-commit-id>