Coda Chang Coda Chang - 1 month ago 16
Git Question

.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?

Answer

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 --chached 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