Press "Enter" to skip to content

How to Set Up .gitignore As a Whitelist

The .gitignore file is a crucial part of any Git repository; it prevents unwanted files from being tracked and shared in source control. Usually, you want to ignore certain files and folders, but sometimes it’s easier to do it the other way around.

Using .gitignore as a Whitelist

Regular .gitignore usage is simple—give it a filename or matching wildcard, and that file will be blocked. When you use it as a whitelist though, it becomes a bit more complicated.

First, you’ll need the two following directives at the top of the file, which block everything by default with an all-encompassing wildcard *:

*
!*/

The second line is needed because whitelisting isn’t as simple as blocking. Because of the way Git handles these files, if it sees a directory is blocked, it won’t even try to check anything in the directory to see if it was unblocked later. It simply skips it and ignores all rules inside that directory.

So, the second line here tells Git to specifically check subfolders. The exclamation point ! is used to turn the rule into a whitelist. It matches all directories, but since it doesn’t match anything inside those directories, Git will not track any files just yet with just these two lines alone.

This allows setups like the following:

*
!*/

# track this file
!.gitignore

# whitelist everything in ./config/
!config/
Advertisement

The .gitignore file itself is in the main directory, so it can just be whitelisted normally. Whitelisting directories simply requires a trailing slash, and Git will return to normal in that directory, overriding the previous all-blocking wildcard.

If you want to explicitely whitelist a directory and all its contents, you must use the double wildcard, !config/**. A single wildcard would not propagate into subdirectories recursively. This will override all other blocking rules.

Debugging .gitignore

If you’re having issues with your configuration, you can debug it with the check-ignore Git command:

git check-ignore -v testfile.json

This post was originally published on this site

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *