How do I completely nuke a file from a git repo?
Asked Answered
E

2

5

I've accidentally pushed a file that I don't have rights to to a publicly accessible repo.

What can I do to selectively nuke that single file from the repo completely, so that its data is completely gone?

Epeirogeny answered 14/5, 2012 at 14:41 Comment(4)
help.github.com/remove-sensitive-dataUnconditioned
possible duplicate of How do I remove sensitive files from git's historyAgalloch
Please, give more information, Do you want to completely delete all information of this file from your history or just HEAD? Did the file filter into one commit or more? Do you want to keep the commit and delete just a file or the delete the whole commit?, is it in multiple branches?Handmaiden
possible duplicate of Completely remove file from all Git repository commit historyHyalite
C
6

Git Filter-Branch is your friend in this case, well documented by the lovely Github

Christlike answered 14/5, 2012 at 14:46 Comment(0)
T
2

Assuming the commit where you added the file is the most recent one:

git reset --hard HEAD^
git push --force

If you have more commits in the repository, you can use the interactive rebase to obliterate that commit. Use git rebase -i xxx with xxx being a commit before the one you want to nuke. Then in the editor, delete the line containing the "bad" commit. As soon as you save and exit the editor, that commit will be gone forever. If you cannot delete the whole commit, you can replace pick with edit in the file and modify the commit (e.g. remove the file from the staging area) and then run git rebase --continue

However, everyone who pulled from your repo will need to perform the same rebase manually. But then that file is already public anyway and you shouldn't rewrite history to undo your mistake.

Instead of all the rebasing you can also use git-filter-branch to remove the file, a described in the GitHub help:

git filter-branch --index-filter 'git rm --cached --ignore-unmatch NAME_OF_THE_FILE' --prune-empty -- --all

Of course you need to git push --force after this operation, too, since it also rewrites history (with all the caveats if someone pulled from that repository and started working on it). If your repo is on github, also don't forget to contact them to clear the cache of your repository.

Teevens answered 14/5, 2012 at 14:43 Comment(2)
Sadly, it's not. There's a bunch of commits after the fact.Epeirogeny
Does this result in cloned repos losing the file from their history as well when pulling?Freedom

© 2022 - 2024 — McMap. All rights reserved.