Set application version in gengetopt config based on Mercurial revision

2013-11-02
#python #gengetopt #mercurial

Previously I wrote about the gengetopt tool for parsing command line arguments. There was a line about the application version.

1version "13.10.25"

It is important to keep this line up to date every time you compile and deploy the binary.

I suggest using a Python script for this. Preliminaries: hg id -n returns the local revision number, hg id -i returns the global revision id. By combining the date, the local revision, and the global revision, I generate a version detailed enough to determine the source files used to create the binary. For the following script, the gengetopt config must be placed in the src/cmdline.ggo file. The script replaces the version line with the string “date local_revision:global_revision”. Listing of version.py:

 1#!/usr/bin/env python
 2
 3from subprocess import check_output
 4from datetime import datetime
 5
 6ggofile = open('src/cmdline.ggo', 'r')
 7ggo = [line.strip('\n') for line in ggofile.readlines() if not 'version' in line]
 8ggofile.close()
 9
10version = check_output(['hg','id','-n']).strip('\n')+':'+check_output(['hg','id','-i']).strip('\n')
11version = datetime.now().strftime('%Y.%m.%d') + ' ' + version
12
13ggo.insert(0, 'version "' + version + '"')
14
15ggofile = open('src/cmdline.ggo', 'w')
16print >>ggofile,'\n'.join(ggo)
17ggofile.close()

Now just run version.py every time you want to build and deploy the application binary (do not forget to regenerate the parser files with gengetopt: gengetopt -G -i cmdline.ggo in the directory with the config).