mass communicating

Git Version in Python

Overview:

This is a very basic problem: I would like to know the Git checkout version of my Python code when running the code.

The standard way to achieve this is to use clean/smudge filters. However, the standard examples are quite basic and use a mixture of Perl/Ruby/Shell scripts.

Here is one script that can be added to a Python project, and which will work both as a clean and smudge filter:

https://gist.github.com/pkrusche/7369262

This script will transform stdin to expand some keywords with git version/author/date information. You can specify the option --clean to remove this information before commit.

Setup:

 __version__ = ""
 __author__ = ""
 __email__ = ""
 __date__ = ""
git add versioning.py
git add version.py
git commit -m "added versioning files"
git config filter.versioning.smudge 'python versioning.py'
git config filter.versioning.clean  'python versioning.py --clean'
echo 'version.py filter=versioning' >> .gitattributes
git add .gitattributes
git commit -m "Changed .gitattributes"

Note that the path to versioning.py must be relative to the root of your repository.

You update the file version like this (this can be a post-checkout hook, too – see below):

rm version.py
git checkout version.py
cat version.py

This should give you the following updated version.py file:

__version__ = "4d5ca36"
__author__ = "[Your Name]"
__email__ = "[Your Email]"
__date__ = "Fri Nov 8 11:06:28 2013 +0000"

Installing Hooks

Now, I might forget updating the version file every time I change something. The way to do this in git is to add hooks. I added two hooks to do this, a post-checkout hook and a post-commit hook. I used the same file (the files will be run in the root directory of the repository):

#!/bin/sh

cat version.py | python versioning.py --clean | python versioning.py > version.py

Now, every time I commit or checkout, my version number will be updated automatically.

Category: code Tags: python git