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()
            .decode('utf-8'))
    except:
        with open(version_file, 'r') as fh:
            version_git = (fh.read()
                            .strip()
                            .split('=')[-1]
                            .replace('"','')
                            .decode('utf-8'))

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

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

    return version_git