1

I have a file called VersionUtil and set it into the gitignore. In the gitignore file, I have

# Git info
app/src/main/java/com/test/util/VersionUtil.java

Before I run the project in android studio, there's a line of code in VersionUtil.java:

public static final String COMMIT_INFO = "info".

I ran git status and it returned

Your branch is up-to-date with 'origin/develop'.

However, after I run the project, VersionUtil.java was changed. That line is:

public static final String COMMIT_INFO = "6a604 XXXXX ".

The git status returned

modified:   app/src/main/java/com/test/util/VersionUtil.java

Do you guys have any idea? Why the file in gitignore is still being tracked? Any help would be appreciated.

Nick Volynkin
  • 14,023
  • 6
  • 43
  • 67
Shumin Gao
  • 677
  • 2
  • 8
  • 15
  • Welcome to StackOverflow! I took the liberty of removing the `github-api` tag and adding the `git` tag, since this question does not have any connection to GitHub or its API. – helmbert Apr 20 '15 at 22:03

1 Answers1

6

A .gitignore file affects only untracked files. Files that are already tracked are not affected in any way by a .gitignore file. This means that if a file is already under version control and then added to the .gitignore later, Git will not start ignoring the already-tracked file then.

To quote the man page (emphasis mine):

A gitignore file specifies intentionally untracked files that Git should ignore. Files already tracked by Git are not affected [...].

[...]

  • The purpose of gitignore files is to ensure that certain files not tracked by Git remain untracked.

  • To ignore uncommitted changes in a file that is already tracked, use git update-index --assume-unchanged.

  • To stop tracking a file that is currently tracked, use git rm --cached.

The second suggested alternative might be the way to go for you:

git update-index --assume-unchanged app/src/main/java/com/test/util/VersionUtil.java

Alternatively, you can remove the file (either physically, or from version control only). After that, the .gitignore file should be effective:

git rm --cached app/src/main/java/com/test/util/VersionUtil.java
git commit -m'Remove VersionUtil.java from version control'
Nick Volynkin
  • 14,023
  • 6
  • 43
  • 67
helmbert
  • 35,797
  • 13
  • 82
  • 95
  • Hi Helmbert, Thanks for your answer. Does that mean if a file is already pushed to github, the gitignore will not affect it at all? – Shumin Gao Apr 20 '15 at 22:08
  • Basically correct. Having been pushed (to Github, or whereever) is not the crucial point however. A file is *tracked* as soon as it has been added to a commit (remember, commits are local in Git!). If you feel like reading up on the different states a file can have in a Git repository, I can recommend [this chapter](http://git-scm.com/book/en/v2/Git-Basics-Recording-Changes-to-the-Repository) from the *Pro Git* book. – helmbert Apr 20 '15 at 22:13