Recently we had the need to exclude an entire folder structure from Git but we wanted to include a single config file that was located in a subdirectory inside this excluded folder.
This seems easy, right? Well after a lot of searching and trying different .gitignore patterns it wasn't as straightforward as it seemed.
The reason is that when a folder is excluded in .gitgnore, Git skips over it for performance reasons so any subsequent attempts to exclude a file from the ignore rule in that folder are ignored.
From the Git documentation:
"It is not possible to re-include a file if a parent directory of that file is excluded"
However, we got there in the end and this is the pattern we used:
/folder_to_exclude/*
!/folder_to_exclude/config/
/folder_to_exclude/config/*
!/folder_to_exclude/config/config.ini
A step-by-step explanation:
Line 1: Ignore the entire folder structure
Line 2: Re-include the subfolder which contains the file we want to track (The exclamation mark negates the previous pattern and re-includes the /config subfolder)
Line 3: Exclude all files and subfolders in the re-included folder
Line 4: Negate the previous rule for the file we want to track (in this case config.ini)
We can't guarantee this will work for you, but it worked for us!