from __future__ import unicode_literals
import os
import shutil
import subprocess

from ..version import __version__


def app_version():
    def minimal_env_cmd(cmd):
        # make minimal environment
        env = {k: os.environ[k] for k in ['SYSTEMROOT', 'PATH'] if k in os.environ}
        env.update({'LANGUAGE': 'C', 'LANG': 'C', 'LC_ALL': 'C'})
        out = subprocess.Popen(cmd, stdout=subprocess.PIPE, env=env).communicate()[0]
        return out

    subst_list = {
        'version': __version__,
        'branch': None,
        'commit': None,
    }

    # Use shutil.which instead of `command -v`/os.system so we don't spawn a
    # shell (CWE-78 hardening) and so it works cross-platform.
    if shutil.which('git') is None:
        return subst_list

    try:
        # Check we are inside a git work tree. Using DEVNULL avoids the
        # file-handle leak from `open(os.devnull, 'w')`.
        rc = subprocess.call(
            ['git', 'branch'],
            stderr=subprocess.DEVNULL,
            stdout=subprocess.DEVNULL,
        )
    except OSError:
        return subst_list
    if rc != 0:
        return subst_list

    describe = minimal_env_cmd(['git', 'describe', '--tags', '--always'])
    git_revision = describe.strip().decode('ascii')

    branch = minimal_env_cmd(['git', 'branch', '--show-current'])
    git_branch = branch.strip().decode('ascii')

    subst_list.update({
        'branch': git_branch,
        'commit': git_revision,
    })

    return subst_list


if __name__ == '__main__':
    app_version()
