#!/usr/bin/env python
import os
import sys
from os.path import join, isfile, abspath, dirname, relpath, isdir
import shutil
import pip
from pip.req import parse_requirements


def err(msg=''):
    sys.stderr.write(msg + '\n')
    

def clean_package(package_name, dirpath='.'):
    print('Cleaning up binary, build and dist for ' + package_name + ' in ' + dirpath + '...')
    if isdir(join(dirpath, 'build')):
        shutil.rmtree(join(dirpath, 'build'))
    if isdir(join(dirpath, 'dist')):
        shutil.rmtree(join(dirpath, 'dist'))
    if isdir(join(dirpath, package_name + '.egg-info')):
        shutil.rmtree(join(dirpath, package_name + '.egg-info'))
    print('Done.')


def get_reqs():
    try:
        install_reqs = parse_requirements('requirements.txt', session=False)
    except TypeError:
        install_reqs = parse_requirements('requirements.txt')
    reqs = [str(ir.req) for ir in install_reqs if ir.req]
    return reqs


def find_package_files(dirpath, package, skip_exts=None):
    paths = []
    for (path, dirs, fnames) in os.walk(join(package, dirpath)):
        for fname in fnames:
            if skip_exts and any(fname.endswith(ext) for ext in skip_exts):
                continue
            fpath = join(path, fname)
            paths.append(relpath(fpath, package))
    return paths


''' Versioning:
1. Write each version to VERSION.txt
2. If the changes are significant, tag the release and push the new tag:
   $ python setup.py tag '''
def write_version_py(package_name):
    version_txt = 'VERSION.txt'
    if not isfile(version_txt):
        return None

    with open(version_txt) as f:
        v = f.read().strip().split('\n')[0]

    try:
        import subprocess
        git_revision = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).rstrip()
    except:
        git_revision = ''
        pass

    version_py = os.path.join(package_name, 'version.py')
    with open(version_py, 'w') as f:
        f.write((
            '# Do not edit this file, pipeline versioning is governed by git tags\n' +
            '__version__ = \'' + v + '\'\n' +
            '__git_revision__ = \'' + str(git_revision) + '\'') + '\n')
    return v


def run_cmdl(_cmd):
    print('$ ' + _cmd)
    os.system(_cmd)
