Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

A Useful Git Post-Checkout Hook for Python Repos

DZone's Guide to

A Useful Git Post-Checkout Hook for Python Repos

· DevOps Zone
Free Resource

Download “The DevOps Journey - From Waterfall to Continuous Delivery” to learn learn about the importance of integrating automated testing into the DevOps workflow, brought to you in partnership with Sauce Labs.

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.

Discover how to optimize your DevOps workflows with our cloud-based automated testing infrastructure, brought to you in partnership with Sauce Labs

Topics:

Published at DZone with permission of David Winterbottom, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}