Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore files committed to git and also remove them from history

I forgot to add certain files to my .gitignore when I began my project and consequently committed files I shouldn't have. I ignored the files afterwards as described here. The damage has already happened though since the files still exist in the history of my repository and now my repository is 10gb in size!

I have not pushed the files for the aforementioned reason, so rewriting history should be okay. In short, what I need to do is to rewrite history so that afterwards none of the files in the current .gitignore exist in any commit in the repository.

Edit: There are lots of small files contributing to the large size, so the suggested duplicate about how to remove all files above a certain size threshold does not solve this problem.

like image 294
Steve Avatar asked Aug 17 '17 10:08

Steve


People also ask

How can I ignore files that have already been committed to the repo?

Git can only ignore files that are untracked - files that haven't been committed to the repository, yet. That's why, when you create a new repository, you should also create a . gitignore file with all the file patterns you want to ignore.

How do I ignore an already committed file in git?

If you want to ignore a file that you've committed in the past, you'll need to delete the file from your repository and then add a . gitignore rule for it. Using the --cached option with git rm means that the file will be deleted from your repository, but will remain in your working directory as an ignored file.

How do I remove files from my entire git history?

The easiest way to delete a file in your Git repository is to execute the “git rm” command and to specify the file to be deleted. Note that by using the “git rm” command, the file will also be deleted from the filesystem.


1 Answers

To reset the commit histories as original, you can use git reset --hard origin/branchname.

To ignore files and remove them from history, you can follow below two aspects:

1. Ignore files which already committed to git

  • Create a .gitignore file (if you don’t have) by touch .gitignore.
  • Add files and folders you want to ignore in .gitignore. The wildcard is allowed. Then commit the changes.
  • Ignore the files from committed history:

git rm filename -r --cached git commit

2. Remove file from commit history totally

git filter-branch --index-filter 'git rm --ignore-unmatch -r --cached filename' --prune-empty -f -- --all

To tidy your local repository (you can also skip this step):

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

To push the rewrite history to remote:

git push -f --all
like image 200
Marina Liu Avatar answered Sep 23 '22 19:09

Marina Liu