Gitignore all except one folder and all its content - regardless of the nesting level

1.5k views Asked by At

I know that this question has been asked many times, but honestly - in spite of many accepted answers, I've not found a neat solution to this problem. I stress the work neat here.

I want to ignore everything except one folder and its entire contents.

This will not achieve it:

*
!dest
!dest/*

that would preserve the dest folder and all files that are in dest, but not other folders within in as well as files in these sub-folders.

Somebody wrote in comments! to one of similar questions that you cannot achieve this without specifying full paths to what you don't want to ignore if you start your .gitignore with *.

I am now convinced that he was right. Or is there a neat way to ignore everything except one folder and its entire content

1

There are 1 answers

0
VonC On BEST ANSWER

I just tested (with a recent Git, even on Windows)

*
!dest/
!dest/**

As usual, you just have to follow the rule:

It is not possible to re-include a file if a parent directory of that file is excluded. (*)
(*: unless certain conditions are met in git 2.?+, see below)

Once the dest folder is white-listed (!dest/), you can exclude its content (on multiple levels) easily (!dest/**).

From there, any git check-ignore -v dest/x/y/z/aFile would return nothing, which means aFile be added.

I mentioned a similar principle (slightly different solution) in "Gitignore exclude certain files in all subdirectories".


Note that with git 2.9.x/2.10 (mid 2016?), it might be possible to re-include a file if a parent directory of that file is excluded if there is no wildcard in the path re-included.

Nguyễn Thái Ngọc Duy (pclouds) is trying to add this feature:

Here, this should work with git 2.9+:

*
!dest