Setting up a whitelist for .gitignore can help you keep your codebase clean and organized. Here’s how to do it:
- Open your .gitignore file in a text editor.
- Add a line at the top of the file that says “*.pyc” and save it. This will ignore all Python files in your project.
- Add a line at the bottom of the file that says “*.pyo” and save it. This will ignore all Python objects in your project, including modules and classes.
- Add lines for any other files or folders you want to ignore, one per line. For example, if you want to ignore all images in your project, you would add the line “*.jpg” to your .gitignore file. ..
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:
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: