Can git ignore a specific line?

Iolo picture Iolo · Jul 2, 2011 · Viewed 34.8k times · Source

I'm using git to sync to phonegap while testing on the phone's native browser. As such I have the following line:

var isPhoneGap = false;

Obviously I change this when building, but is there any way I can set up git to ignore this one line or do I have to go and put it in its own file and ignore it that way?

I'm using Gitx and the terminal on OSX 10.6.

Answer

VonC picture VonC · Mar 4, 2014

If your file is of a specific type, you can declare a content filter driver, that you can declare in a .gitattributes file (as presented in the "Keyword expansion" of "Git Attributes"):

http://git-scm.com/figures/18333fig0702-tn.png

*.yourType filter=yourFilterName

(you can even set that filter for a specific file, if you want)

Implement:

  • yourFilterName.smudge (triggered on git checkout) and

      git config --global filter.yourFilterName.smudge 'sed "s/isPhoneGap = .*/isPhoneGap = true/"'
    
  • yourFilterName.clean (triggered on git add)

      git config --global filter.yourFilterName.clean 'sed "s/isPhoneGap = .*/isPhoneGap = false/"'
    

Your file would appear unchanged on git status, yet its checked out version would have the right value for isPhoneGap.


Note: in the comments, ohaal and Roald suggest to isolate the sed calls in a separate helper.sh script:

sed "s/isPhoneGap = .*/isPhoneGap = true/" "$@"