• Giacomo Debidda
    • Articles
    • Projects
    • Services
    • Notes
    • Likes
    • Bookmarks
    • Photos
    • About
    • Contact

A simple git hook for your Python projects

10 Sep 2017 Giacomo Debidda
  • article
  • git

Table of Contents 📑

A git hook is a script that git executes before or after a relevant git event or action is triggered. The hooks are stored in the .git/hooks directory of your repository, which is created automatically when you run git init.

Git hooks can be really useful to enforce a certain policy on your commits, push your changes to a continuous integration server, or automatically deploy your code.

I wanted to enforce a very simple policy for my commits: no broken code should be deployed on the master branch. So I wrote this small pre-commit hook:

#!/bin/sh
current_branch=`git branch | grep '*' | sed 's/* //'`

if [ "$current_branch" = "master" ]; then
    echo "You are about to commit on master. I will run your tests first..."
    python -m unittest discover tests
    if [ $? -eq 0 ]; then
        # tests passed, proceed to prepare commit message
        exit 0
    else
        # some tests failed, prevent from committing broken code on master
        echo "Some tests failed. You are not allowed to commit broken code on master! Aborting the commit."
        echo "Note: you can still commit broken code on feature branches"
        exit 1
    fi
fi

It’s a simple client side hook that runs all of my Python tests before committing on master. I can still create a feature branch and commit broken code on that, but as soon as I try to merge the feature branch into master, all test run. If any of the tests fails I can’t commit. Simple as that.

Git hooks are language agnostic. I wrote this small hook as a shell script, but you can use other languages liek Perl, Ruby or Python. Here is an example of a pre-commit hook in written in Python.


  • article
  • git

🗣️ Let's have a chat!

Each week, I carve out some time for anyone to contact me. Feel free to reach out to me. I'll do my best to help you with whatever you need.

Reserve your spot here:
https://cal.com/giacomodebidda/30min

If no time slot fits you, send me a DM on LinkedIn or Twitter.

Webmentions

Did you mention this blog post on your website? Let me know the URL of your article using the form below.

Upon form submission, your webmention will be sent to Webmention.io.

    Webmentions collected by Bridgy.

    No webmentions to show.

    • Articles feed
    • Notes feed
    • Talks feed
    • GitHub
    • Twitter
    • Linkedin
    • Mastodon
    • Stack Overflow
    Copyright © 2020 – 2024 Giacomo Debidda – All rights reserved