Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Git version in Python
#!/usr/bin/env python
""" Git Versioning Script
Will transform stdin to expand some keywords with git version/author/date information.
Specify --clean to remove this information before commit.
1. Copy into your git repository
2. Run:
git config filter.versioning.smudge 'python'
git config filter.versioning.clean 'python --clean'
echo ' filter=versioning' >> .gitattributes
git add
3. add a file with this contents:
__version__ = ""
__author__ = ""
__email__ = ""
__date__ = ""
import sys
import subprocess
import re
def main():
clean = False
if len(sys.argv) > 1:
if sys.argv[1] == '--clean':
clean = True
# initialise empty here. Otherwise: forkbomb through the git calls.
subst_list = {
"version": "",
"date": "",
"author": "",
"email": ""
for line in sys.stdin:
if not clean:
subst_list = {
# '--dirty' could be added to the following, too, but is not supported everywhere
"version": subprocess.check_output(['git', 'describe', '--always']),
"date": subprocess.check_output(['git', 'log', '--pretty=format:"%ad"', '-1']),
"author": subprocess.check_output(['git', 'log', '--pretty=format:"%an"', '-1']),
"email": subprocess.check_output(['git', 'log', '--pretty=format:"%ae"', '-1'])
for k, v in subst_list.iteritems():
v = re.sub(r'[\n\r\t"\']', "", v)
rexp = "__%s__\s*=[\s'\"]+" % k
line = re.sub(rexp, "__%s__ = \"%s\"\n" % (k, v), line)
for k in subst_list:
rexp = "__%s__\s*=.*" % k
line = re.sub(rexp, "__%s__ = \"\"" % k, line)
if __name__ == "__main__":
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment