Git Version in Python


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:

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.


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

Note that the path to 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):

git checkout

This should give you the following updated 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):


cat | python --clean | python >

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

Category: code Tags: python git