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 and add this file to the commit.

Name this file as git_hook_add_commit_date.sh.

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

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 script as pre-comit git hook.

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

In fact I wanted to add commit message as well. But I have not found way for doing this. Commit message you can easily get in the git hook commit-msg. But if you add something to commit on this phase (for example as git commit --amend) git will fail the commit with message that HEAD was changed.

If you know how to do that please let me know.

Written on December 22, 2018