Martin Vegter
Martin Vegter

Reputation: 527

excluding everything from git except

I have the following file structure and I would like to track .ddd/zzz and .aaa and their subfolders with git, and exclude everything else.

.aaa/
.aaa/file.txt
.bbb/
.bbb/www
.bbb/www/www
.bbb/www/www/file.txt
.ccc/
.ddd/
.ddd/zzz
.ddd/zzz/file.txt
.eee/

I have this in my .gitignore file:

*
!.aaa/
!.ddd/zzz/
.gitignore

yet when I initialize the repository, I get nothing to commit.

How can I exclude everything but these two directories and their content?

Upvotes: 1

Views: 59

Answers (1)

Ulysse BN
Ulysse BN

Reputation: 11396

After trying some configurations, I came across with the solution. Having my repo with:

# tree -a
.
├── .git/*
├── .gitignore
├── a
│   └── should-be-taken.txt
├── b
│   └── should-be-ignored.txt
└── recursive
    ├── folder
    │   └── should-be-taken.txt
    └── no.txt

I got a solution with:

# cat .gitignore
*
!/a
!/a/**
!/recursive
!/recursive/folder
!/recursive/folder/**
!.gitignore

The key is to explicitly negate the whole folder path you want to not be ignored within your .gitignore file. And then ** matches everything inside, cf Git documentation:

A trailing "/**" matches everything inside. For example, "abc/**" matches all files inside directory "abc", relative to the location of the .gitignore file, with infinite depth.


EDIT: Even though my solution still works, there is another way shown in the gitignore Documentation Examples:

Example to exclude everything except a specific directory foo/bar (note the /* - without the slash, the wildcard would also exclude everything within foo/bar):

# exclude everything except directory foo/bar
/*
!/foo
/foo/*
!/foo/bar

Upvotes: 1

Related Questions