Git Ignore Specific Parts of a File With Attributes and Custom Filters

03 Aug, 2019

log

Photo by Yancy Min

A .gitignore tells git not to track a list of files in the repository. The ignore patterns can only specify an entire file but not individual parts. Git Attributes with custom filters make it possible to ignore specific parts of a file

Why

.npmrc in user’s home directory is a typical candidate for dotfiles repository. But, when a user authenticates the npm client it writes the authToken to .npmrc in plain text. The goal is to avoid authToken from getting committed to dotfiles repository

How

Write .npmrc filter=ignorenpmtoken to .gitattributes file at the root of dotfiles repository. Or to keep it out of source control, write to .git/info/attributes

.gitattributes syntax explained

applies ignorenpmtoken filter to .npmrc file

Define smudge & clean actions for the ignorenpmtoken filter

# The smudge filter is run on checkout
git config --global filter.ignorenpmtoken.smudge cat

# The clean filter is run when files are staged
git config --global filter.ignorenpmtoken.clean  sed '/\\/\\/registry/'d

And Voila, git now ignores the authToken line from .npmrc

Smudge & Clean

smudge filter on checkout

smudge gets the file as it is

smudge filter on checkout

clean finds the line starting with //registry & deletes it

Others

Git Attributes is a powerful feature that can do much more than what’s shown here. Like

  • Prevent leaking secrets into git (authToken)
  • Preferred context with no accidental commits (Toggle dev flags)
  • Customization with no after effects (Custom IDE settings)