DevOps Zone is brought to you in partnership with:

I work at Tangent Labs, a digital agency, writing applications in python and django. I spend most of my free time hacking. I run commandlinefu.com and am the author of the e-commerce framework django-oscar amongst other things. I used to be a mathematician; I have a PhD in Mathematics from the University of Nottingham and an associated interest in cryptic crosswords, chess and playing devil's advocate. David is a DZone MVB and is not an employee of DZone and has posted 27 posts at DZone. You can read more from them at their website. View Full User Profile

A Useful Git Post-Checkout Hook for Python Repos

04.25.2013
| 8004 views |
  • submit to reddit

Every now and again, an innocent python developer checks out a new Git branch then proceeds to bang their head against a bug caused by an orphaned.pyc file from the previous branch. Since *.pyc files are typically in the repo's.gitignore file, they are not removed when switching branches and can cause issues if the corresponding .py is removed.

This can be neatly addressed through a 'post checkout' hook which deletes all such files. Here is such a script, which also removes empty folders and prints a summary:

#!/usr/bin/env bash

# Delete .pyc files and empty directories from root of project
cd ./$(git rev-parse --show-cdup)

# Clean-up
find . -name ".DS_Store" -delete

NUM_PYC_FILES=$( find . -name "*.pyc" | wc -l | tr -d ' ' )
if [ $NUM_PYC_FILES -gt 0 ]; then
    find . -name "*.pyc" -delete
    printf "\e[00;31mDeleted $NUM_PYC_FILES .pyc files\e[00m\n"
fi

NUM_EMPTY_DIRS=$( find . -type d -empty | wc -l | tr -d ' ' )
if [ $NUM_EMPTY_DIRS -gt 0 ]; then
    find . -type d -empty -delete
    printf "\e[00;31mDeleted $NUM_EMPTY_DIRS empty directories\e[00m\n"
fi

Sample output:

/static/images/screenshots/post-checkout.png

Inspiration:

The above version is a extension of the snippets in the referenced Stack Overflow question.

Published at DZone with permission of David Winterbottom, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)