Exclude/include folders without contents using gitignore

Viewed 94

I am currently trying to exclude all contents of those 3 folders but keep the folders themselfs:

enter image description here

  • files/*
  • files/private/*
  • files/tmp/*

But for now just the files directory gets included. This is what my .gitignore looks like:

default-export/files/*
default-export/files/private/*
default-export/files/tmp/*

!default-export/files/.gitkeep
!default-export/files/private/.gitkeep
!default-export/files/tmp/.gitkeep
2 Answers

You are missing the explicit un-excludes of the directories private and tmp. Without them, Git does not further process the directory structure at all.

This should work according to your described requirements:

default-export/files/*
!default-export/files/.gitkeep
!default-export/files/private/
!default-export/files/tmp/

default-export/files/private/*
!default-export/files/private/.gitkeep

default-export/files/tmp/*
!default-export/files/tmp/.gitkeep

Description

I shall like to clarify that the Folders don't hold great significance for Git. Simply speaking, they are just considered as "Links" to the files inside it.

Hence, an empty directory can't be staged.

In some cases, in order to preserve the directory structure, the directory needs to be added. The same can be achieved by placing a dummy file inside it.

Over the years, the dummy file has received the name .gitkeep (You can name it anything you want to. . is for hiding the same in a LINUX/UNIX System).

Solution to your Problem

You need to create the .gitkeep file and then, add the following lines to your .gitignore.

theEmptyDirectory/*

!.gitkeep

Here is the directory structure I used to test the same enter image description here

thisIsAPrivateFile represents the content I want to keep private while maintaining the directory structure.

And the git status (After staging) result. enter image description here

As you can clearly see, thisIsAPrivateFile has not been staged.

UPDATE

After Matt's comment, I shall like to inform a certain limitation of git. enter image description here

Basically, if the parent directory has been excluded, no matter what, any files inside the same can't be included. Since, in the above example, I have excluded everything (even nested directories) using * then, everything inside those nested directories won't be included.

We can bypass this limitation by specifying the types of files we want to exclude.

Here is the new directory structure

enter image description here

Updated .gitignore

theEmptyDirectory/**/*.js
theEmptyDirectory/**/*.jsx
theEmptyDirectory/**/*.ts

!.gitkeep

And the git status result (After Staging) enter image description here

Clearly, the directory structured has been preserved but, the private files have been exluded.

References

Related