Tuesday, September 13, 2011

Git and empty directories

One minor annoyance I have with Git is that it cannot track empty directories. This is especially annoying if you are working with an application framework, which creates an intricate structure of empty directories.

A common work-around you will see is to create an empty .gitignore file in each empty directory. It's not a very elegant solution, but it gets the job done. The trick is making sure you actually find every empty directory. So, I wrote a simple bash script, gitify.sh, to do it for you.
#!/bin/bash


gitify() {
    if [[ -z $(ls -1A "$1") ]]
    then
        touch "$1/.gitignore"
    else
        for file in "$1"/*
        do
            if [ -d "$file" ]
            then
                gitify "$file"
            fi
        done
    fi
}


rootdir=$(readlink -f .)


gitify $rootdir
Just navigate to the root directory of your Git project, and run the script. It will descend from the working directory into all subdirectories and drop a zero byte .gitignore file in any empty directory it finds. Just git-add all the newly created files and check them in to your repository.

I'm posting this not so much for the benefit of others as for myself. This is probably the fifth time I've written this script, because I keep losing it or deleting it. Maybe now that it's posted on the internet I won't lose it so easily.

No comments:

Post a Comment