Dec 15 2009

How to add empty directory to Git repo

Posted by German Rumm in work

I keep all my Symfony projects in a Git repositories. Makes my life a lot easier – I can upload only changed files on update, which makes updating faster and more reliable.

But, apart from the code files logs and cache files are always changing, and I don’t really need and want to keep them in repo. I used .gitignore to filter out log and cache directories, but everytime I “checkout” repo I need to create them by hand. What I needed is to “git add” directories but ignore directory contents.

The problem is that if you ignore directory contents, directory appears empty to Git, and Git ignores empty directories automatically, so

cache/*

prevents me from adding cache directory at all.

Finally I found a solution to my problem in the Git Cheat Sheet at GitHub. http://github.com/guides/git-cheat-sheet

First, in root .gitignore file you ignore all the directories as usual, and add an exception for the .gitignore file

log/*
cache/*
!.gitignore

And then just add empty .gitignore files into log/ and cache/ firectories.

$ touch log/.gitignore cache/.gitignore

Now, when you do git add, only .gitignore files will be added for those directories, and all other files will be ignored.