Automatically add version to sources (not only Python) - GIT hooks


You want to know version of the application instance.

For mature development flow (development - testing - demo - production) there is always version. But for the price - somebody has to set it (for example as git tag).

But we need versions for our internal process like deployment to development server.

For this purposes we can use git hooks. This is scripts that run locally by git for different events. For example before commit.

Script below saves date and time to some file. Name this file as

#!/usr/bin/env bash
date "+%F %T" > "$FILE"

And this name as, it adds this file to the commit.

#!/usr/bin/env bash
git add "$FILE"
git commit --amend -C HEAD --no-verify

As it’s inside your source code you can use it like this:

def version():
        return open('build_timestamp', 'r').read().strip()
        return None

if __name__ == '__main__':

For security reasons you have to install git hooks by yourself on each machine you use for development.

Script below installs our scripts as pre-comit and post-commit git hooks.

#!/usr/bin/env bash
if [ ! -f .git/hooks/pre-commit ] ; then
    ln -s $PWD/ .git/hooks/pre-commit
    ln -s $PWD/ .git/hooks/post-commit