I tried all answers as given here above, but none worked for me. After reading the gitignore documentation (here) i found out that if you exclude a folder first that the filenames in the subfolder are not being indexed. So if you use the exclamation mark afterwards to include a file, it is not found in the index and thus not being included in your git client.
That was the way to finding the solution. I started with adding exceptions for all subfolders in my folder tree to get it working, which is a hell of a job. Afterwards i was able to compact the detailed configuration to the configuration below, which is a bit contrary to the documentation..
Working .gitignore:
# Ignore the 'Pro' folder, except for the '3rdparty' subfolder
/Pro/*
!Pro/3rdparty/
# Ignore the '3rdparty' folder, except for the 'domain' subfolder
/Pro/3rdparty/*
!Pro/3rdparty/domain/
# Ignore the 'domain' folder, except for the 'modulename' subfolder
Pro/3rdparty/domain/*
!Pro/3rdparty/domain/modulename/
As result i see in my git client that only the two files inside the Pro/3rdparty/domain/modulename/ folder are being staged for the next commit, and that was exactly what i was looking for.
And if you need to whitelist several subfolders of the same folder then group the exclamation mark lines below the exclude statement like this:
# Ignore the 'Pro' folder, except for the '3rdparty' subfolder
/Pro/*
!Pro/3rdparty/
# Ignore the '3rdparty' folder, except for the 'domain' & 'hosting' subfolders
/Pro/3rdparty/*
!Pro/3rdparty/domain/
!Pro/3rdparty/hosting/
# Ignore the 'domain' folder, except for the 'modulename' subfolder
Pro/3rdparty/domain/*
!Pro/3rdparty/domain/modulename/
# Ignore the 'hosting' folder, except for the 'modulename' subfolder
Pro/3rdparty/hosting/*
!Pro/3rdparty/hosting/modulename/
Else it wont work as expected.