Ignored folders getting removed from git after clearing cache

Viewed 36

I had uploaded all my source files to bitbucket and after that I changed my .gitignore file in git. When I cloned the repository and changed my files my git status not ignoring the folders specified in the .gitignore file.

git status --ignored

When I run the above command it is not showing the ignored folders. After a ton of search I found that git rm -r --cached . can clear local git cache and after that when i check status all my ignored folders are showing now. But the problem is after a I push my changes to repository the files and folders specified in the gitignore file is getting removed from repository. Is there any way i can prevent files from removing from repository.

2 Answers

Ignored files means "not tracked by Git".

It makes sense pushing your new repository state (one with the ignored files deleted from Git latest HEAD, and ignored), they are in turn deleted from the remote repository HEAD.

If you need them somehow on the remote side, you should keep them/duplicate them under a different subfolder inside the repository, and push that.
While keeping them ignored in their original place.

But that is awkward, and depends on your specific use-case: ignoring files means they should not be visible in the remote, and are generally regenerated on the local side (like a build/ or target/ folder)

If the "untracked" files were committed in a previous commit, you will necessarily have a commit which deletes them.

If you want to avoid that you will have to rewrite your complete history to remove these untracked files from all previous commits in your repo.


If you are ok with changing the history of your repo, you can use git filter-repo :

git filter-repo --invert-paths --path files/to/be/ignored

or the older git filter-branch :

git filter-branch --index-filter 'git rm --cached ignored/file || true'

git filter-branch --index-filter 'git rm --cached -r ignored/dir/ || true'

After that you will have to push --force to your remote.

Related