How to set up .gitignore as a whitelist – CloudSavvy IT

The .Gitignore file is a crucial part of any Git archive; it prevents unwanted files from being tracked and shared in source control. Usually you will ignore certain files and folders, but sometimes it is easier to do the opposite.

Using .gitignore as a whitelist

Regular .gitignore usage is simple – give it a filename or matching wildcard and that file will be blocked. However, when you use it as a whitelist, it gets a little more complicated.

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

*
!*/

The second line is necessary because whitelisting is not as simple as blocking. Because of the way Git handles these files, it will not even if it sees that a library is blocked sample to check something in the library to see if it was unblocked later. It simply skips it and ignores all the rules inside the folder.

So the second line here tells Git about specifically checking subfolders. Exclamation mark ! used to turn the rule into a whitelist. It matches all folders, but since it does not match anything inside these libraries, Git will not track any files yet with just these two lines alone.

This allows setups as follows:

*
!*/

# track this file
!.gitignore

# whitelist everything in ./config/
!config/

That .gitignore the file itself is in the main folder, so it can just be whitelisted normally. Whitelisting directories simply requires a subsequent slash, and Git returns to the normal in that directory, overriding the previous wildcard that everyone is blocking.

To explicitly whitelist a library and all its contents, use the double wildcard, !config/**. A single wildcard would not spread to subfolders recursively. This will override all other blocking rules.

Debugging .gitignore

If you have problems with your configuration, you can troubleshoot it with check-ignore Git command:

git check-ignore -v testfile.json

Leave a Comment