2

I'm trying to get git to ignore the entire packages directory except for .targets files inside it, wherever they may be. I'm trying this in .gitignore but git still ignores the entire packages dir despite the presence of .targets files:

/packages/*
!/packages/**/*.targets

I've also tried following advice from another SO question and un-blacklisting directories first but it still didn't work (this time, it just included all of the packages dir again):

/packages/*
!/packages/**/
!/packages/**/*.targets

How can I get this to work?

Jez
  • 27,951
  • 32
  • 136
  • 233

2 Answers2

1

OK I figured it out - the key is understanding that Git can ignore both directories and files, but if it ignores a directory it won't then search that directory's sub-structure for the remainder of the .gitignore.

So first you ignore everything in the /packages contents, then you only whitelist the directories (which will still add nothing because an empty directory in Git, or one with all its files ignored, doesn't get added), then you whitelist the .targets files which will now work because the directories have been whitelisted, so Git will look in their sub-structure to find the files to whitelist:

# Ignore the NuGet packages folder contents in the root of the repository...
/packages/**/*
# (whitelist directories to allow file exclusions later)
!/packages/**/
# ...except target files which may be required for msbuild.
!/packages/**/*.targets
Jez
  • 27,951
  • 32
  • 136
  • 233
0

Use this file:

/packages/**/*
!/packages/**/
!/packages/**/*.targets

Explanation

When you ignore a folder, git won't check that folder at all, so you can't exclude any file inside it from ignorance later.

Since you want to keep some specific files tracked, instead of ignoring a folder itself, you should ignore all files inside the folder first, then exclude specific files you want to track.

Wray Zheng
  • 967
  • 10
  • 17