Git Ignore Specific Parts of a File With Attributes and Custom Filters
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
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
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)