import os
import subprocess

# Versioning code here, based on
# http://blogs.nopcode.org/brainstorm/2013/05/20/pragmatic-python-versioning-via-setuptools-and-git-tags/
def maintain_version(version_file):
    """
    Get the version from git tags, and write it to version.py.
    When git is not available (PyPi package), use version in version.py.
    """

    try:
        version_git = subprocess.check_output(['git', 'describe', '--tags']).rstrip()
    except:
        with open(version_file, 'r') as fh:
            version_git = open(version_file).read().strip().split('=')[-1].replace('"','')

    version_msg = "# Do not edit this file, pipeline versioning is governed by git tags"

    with open(version_file, 'w') as fh:
        content = ''.join([version_msg, os.linesep, '__version__="', version_git, '"'])
        fh.write(content)

    return version_git