gitgit-checkoutgit-clean

Git: clean empty directories after checkout


I'm on my "devel" branch and git status says "working directory clean".

I want to look at a past release and so checkout a tag: git checkout tags/v1.0.0. After this some directories which were created between "v1.0.0" and my current "devel" HEAD are left empty but not removed (although they didn't exist when the tag was created). I believe this is because git doesn't track empty directories.

In order to have exactly the same state as when the tag was created, I additionally need to call git clean -fd which removes these remaining empty directories.

When I checkout a tag, I want the exact state of the filesystem when that tag was created - should I always call git clean -fd after a checkout?


Solution

  • Yes, you will need to clean the directories manually since directories are never tracked in git, only files are.

    To do this in one step, you can define a shell function as a git alias to do this for you in a single step.

    Either do the following in your terminal:

    git config alias.cco "! f(){ git checkout \"\$1\" && git clean -fd; }; f"
    

    or edit your .git/config file and add this entry there:

    [alias]
        cco = "! f(){ git checkout \"$1\" && git clean -fd; }; f"
    

    Now, you can run both these commands in a single go using:

    git cco tag_name