Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git checkout delete files in gitignore

Tags:

git

I accidentally tracked workspace configuration files in a git repo. Trying to fix the problem, I git rm --cached those files and added them to .gitignore file.

Now every time I checkout a branch from the repo, those get deleted. Is there any way to avoid this?

like image 290
aitkiar Avatar asked Aug 27 '13 11:08

aitkiar


People also ask

Does git checkout delete local files?

git checkout does not affect untracked files. Git only manages tracked files, and it works fairly hard to avoid letting you lose data (which is critical).

Does git clean remove ignored files?

The git clean command also allows removing ignored files and directories.


1 Answers

The problem is the git rm commit being present in some branches but not all, which means that when you switch from one branch still containing the files to one where you git rm'ed git will correctly remove the files. What you actually want to do is remove the files from git's history as if they have never been there, following this question. You should however be aware that this means rewriting the repository history, so for one thing you will have to git push --force afterwards, and for another thing, you will upset others who also work with this repo.

edit Should rewriting history not be viable, make sure you commit the git rm --cached action on every branch existing. You will however still encounter unpleasant re-deletion should you checkout revisions before that deletion.

Summary:

  • commit a .gitignore + git rm --cached to each branch if history cannot be rewritten, but remember that checking out any previous revision (e.g. via a tag) will a) yield an error about the existing untracked files git wants to checkout and b) cause another deletion of these files on switching back to HEAD
  • rewrite history if you are likely to checkout previous revisions often (or some of the files accidentally committed contain sensitive data) to avoid this, but be aware that this will screw up everyone else's clone

In fact, there is a third possibility: For each branch, create a new branch in which you rewrite history, while to the original version add one commit removing all files (except the to be ignored ones!1) adding a highly visible file explaining the mess-up and asking users to switch to the rewritten branch from now on and remove their local copy of the unrewritten one.


1The reason for this is you don't want to delete other users' version of these files that shouldn't have been versioned from the very start, and since one is not expected to ever switch back to the old version this will never yield said "file already exists" error

like image 115
Tobias Kienzler Avatar answered Sep 18 '22 20:09

Tobias Kienzler