Search code examples
gitgitignore

git ignore everything except files and folders under those folder matching a pattern


I want git ignore to ignore everything except those files and folders which are subfolders of all folders matching a given name pattern.

example file structure:

 - .temp
 - stuff/
 - readme.txt
 - crap/pattern/more/stuff
 - crap/pattern/.temp
 - crap/pattern_test/
 - crap/more/pattern_test/

What I want to achieve is now something like:

/*
/*/
!.gitignore
!*/pattern*/*

So from the top example I would like git to not ignore:

 - crap/pattern/*
 - crap/pattern/more/*
 - crap/pattern/more/stuff/*
 - crap/pattern_test/*
 - crap/more/pattern_test/*

Is that possible? I tried a lot of patterns without any success:

!/pattern*/*
!/pattern*/
!*/pattern*/*
!*/pattern/*
...

Solution

  • You could set up your .gitignore file like this:

    # Ignore everything by default
    *
    # Whitelist the .gitignore file
    !.gitignore
    # Whitelist folders at any level
    !**/*/
    # Whitelist every file under folders that match the pattern at any level
    !/**/pattern*/**/*