How to tell git to ignore individual lines, i.e. gitignore for specific lines of code

Kache picture Kache · Apr 26, 2013 · Viewed 60.3k times · Source

.gitignore can ignore whole files, but is there a way to ignore specific lines of code while coding?

I frequently and repeatedly add the same debug lines in a project, only to have to remember to remove them before committing. I'd like to just keep the lines in the code and have git disregard them.

Answer

Kache picture Kache · Apr 26, 2013

This is how you can kind of do it with git filters:

  1. Create/Open gitattributes file:
    • <project root>/.gitattributes (will be committed into repo)
      OR
    • <project root>/.git/info/attributes (won't be committed into repo)
  2. Add a line defining the files to be filtered:
    • *.rb filter=gitignore, i.e. run filter named gitignore on all *.rb files
  3. Define the gitignore filter in your gitconfig:
    • $ git config --global filter.gitignore.clean "sed '/#gitignore$/d'", i.e. delete these lines
    • $ git config --global filter.gitignore.smudge cat, i.e. do nothing when pulling file from repo

Notes:
Of course, this is for ruby files, applied when a line ends with #gitignore, applied globally in ~/.gitconfig. Modify this however you need for your purposes.

Warning!!
This leaves your working file different from the repo (of course). Any checking out or rebasing will mean these lines will be lost! This trick may seem useless since these lines are repeatedly lost on check out, rebase, or pull, but I've a specific use case in order to make use of it.

Just git stash save "proj1-debug" while the filter is inactive (just temporarily disable it in gitconfig or something). This way, my debug code can always be git stash apply'd to my code at any time without fear of these lines ever being accidentally committed.

I have a possible idea for dealing with these problems, but I'll try implementing it some other time.

Thanks to Rudi and jw013 for mentioning git filters and gitattributes.