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

Problem

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 git_hook_pre_commit.sh.

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

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

#!/usr/bin/env bash
FILE=build_timestamp
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():
    try:
        return open('build_timestamp', 'r').read().strip()
    except:
        return None


if __name__ == '__main__':
    print(version())

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_hook_pre_commit.sh .git/hooks/pre-commit
    ln -s $PWD/git_hook_post_commit.sh .git/hooks/post-commit
fi