#!/usr/bin/env python2.7

# to use gimport: use wget or curl to download the gimport.py file locally
#ie.  os.system('wget -q https://github.com/scottidler/gimport/raw/master/gimport.py -O gimport.py')

import os
import re
import imp
import sys
import contextlib
from subprocess import Popen, PIPE

sys.dont_write_bytecode = True

class RepospecDecompositionError(Exception):
    '''
    exception when repospec can't be decomposed
    '''
    pass

@contextlib.contextmanager
def cd(*args, **kwargs):
    '''
    helper change dir function to be used with 'with' expressions
    '''
    mkdir = kwargs.pop('mkdir', True)
    verbose = kwargs.pop('verbose', False)
    path = os.path.sep.join(args)
    path = os.path.normpath(path)
    path = os.path.expanduser(path)
    prev = os.getcwd()
    if path != prev:
        if mkdir:
            run('mkdir -p %(path)s' % locals(), verbose=verbose)
        os.chdir(path)
        curr = os.getcwd()
        sys.path.append(curr)
        if verbose:
            print 'cd %s' % curr
    try:
        yield
    finally:
        if path != prev:
            sys.path.remove(curr)
            os.chdir(prev)
            if verbose:
                print 'cd %s' % prev

def run(*args, **kwargs):
    '''
    thin wrapper around Popen; returns exitcode, stdout and stderr
    '''
    nerf = kwargs.pop('nerf', False)
    shell = kwargs.pop('shell', True)
    verbose = kwargs.pop('verbose', False)
    if (verbose or nerf) and args[0]:
        print args[0]
    if nerf:
        return (None, 'nerfed', 'nerfed')
    process = Popen(shell=shell, *args, **kwargs)
    stdout, stderr = process.communicate()
    exitcode = process.poll()
    if verbose and stdout:
        print stdout
    return exitcode, stdout, stderr

def expand(path):
    '''
    converts ~ -> /home/%{USER}
    '''
    if path:
        return os.path.expanduser(path)

def decompose(repospec, giturl=None):
    '''