Search code examples
gitgitignore

Ignore all files in subfolders but specifc files


I am working in a project with the following structure

Data/
   folder1/
      file1
      file2
      important.txt
   folder2/
      file3
      file4
      important.txt
   folder3/
      file5
      file6
      important.txt
README.md
.gitignore
several other files and folders

I want to keep track of everything except for the files inside each folder in Data. I want to keep track of important.txt also. What I can't do is to ignore everything inside Data but the important files. I looked at some solutions that basically start with ignoring everything and later negating the specific files they want to track, but I don't want to do that because the project contains many files and negating one by one those is a quite annoying.

What my gitignore looks like now

#Ignore Data (and its contents)
Data
#but not subfolders
!Data/
#ignore everything inside subsubfolders
Data/*/*
#but not the important files
!Data/**/important.txt



Solution

  • You don't mention whether you can have, e.g.:

    Data/long/path/to/folder/trash
    Data/long/path/to/folder/important.txt
    

    and if so whether you need to keep important.txt as a committed file, but I'll assume that this occurs. Here's how I would do it:

    • At the top level, have no .gitignore;

    • in Data have a .gitignore that reads:

      *
      !.gitignore
      !important.txt
      !*/
      

    This tells Git that once it descends into Data/ to do a recursive add or check for untracked files, it should:

    • ignore everything; but
    • don't ignore (so do check for and/or en-masse add) .gitignore itself;
    • don't ignore important.txt either; and
    • do descend, recursively, into any sub-directory.

    Since none of these rules are anchored these same four rules apply, in that order, to every sub-directory.