rj487
rj487

Reputation: 4634

.gitignore work wrongly, file disappear when checkout branch

I felt a little bit confused about .gitignore. Here's the thing, I developed in Rails, and I don't want the secrets.yml and database.yml to be uploaded into Github.

I thought that I only need to edit these two file on the AWS EC2, so I add them into .gitignore.

Then I run

git rm --cached secrets.yml database.yml

to clean my git track file status.

Therefore, these two file are still in the folder, but they can't be added into git track list.

However, I found out when I checkout other branch and then come back. These two files will disappeared, what happened?

Upvotes: 2

Views: 1384

Answers (2)

das_j
das_j

Reputation: 4794

Git stores these files for each branch individually. So you could have the same files with different contents on many branches. You can also have the files on one branch and have them removed from another branch (which is probably what you currently have).

In case you already pushed your files to Github, the secrets are already public and should be changed ASAP. Do not just remove the files, you can never be sure nobody copied them!

As mentioned in the comments, you can filter-branch the files out and force-push the repository, but this would break some things if there are other people who have checked out the repository. I'd rather remove the file from all branches using git rm --cached and push the branches to keep a stable history and change the secrets.

You can remove the files automatically from all branches:

for branch in $(git for-each-ref --format='%(refname)' refs/heads/); do
    git checkout "$branch"
    git rm --cached config/secrets.yml config/database.yml
    git commit -m 'Remove secrets.yml'
done
echo "Remember to git push"

If you haven't pushed the branches yet, you can filter the files out (taken from this answer):

git filter-branch --index-filter 'git rm --cached --ignore-unmatch config/secrets.yml config/database.yml' --all

Upvotes: 2

Luke Exton
Luke Exton

Reputation: 3676

Filter branch works well but is pretty non intuitive and slow at scale. I.e a lot of commits.

GitHub recommends: https://rtyley.github.io/bfg-repo-cleaner/

Upvotes: 0

Related Questions