# Path: jasy/core/Util.py
# def executeCommand(args, failmsg=None, path=None):
#     """
#     Executes the given process and outputs failmsg when errors happen.
#     Returns the combined shell output (stdout and strerr combined).
# 
#     :param args: 
#     :type args: str or list
#     :param failmsg: Message for exception when command fails
#     :type failmsg: str
#     :param path: Directory path where the command should be executed
#     :type path: str
#     :raise Exception: Raises an exception whenever the shell command fails in execution
#     """
# 
#     if type(args) == str:
#         args = shlex.split(args)
# 
#     prevpath = os.getcwd()
# 
#     # Execute in custom directory
#     if path:
#         path = os.path.abspath(os.path.expanduser(path))
#         os.chdir(path)
# 
#     Console.debug("Executing command: %s", " ".join(args))
#     Console.indent()
#     
#     # Using shell on Windows to resolve binaries like "git"
#     output = tempfile.TemporaryFile(mode="w+t")
#     returnValue = subprocess.call(args, stdout=output, stderr=output, shell=sys.platform == "win32")
#         
#     output.seek(0)
#     result = output.read().strip("\n\r")
#     output.close()
# 
#     # Change back to previous path
#     os.chdir(prevpath)
# 
#     if returnValue != 0:
#         raise Exception("Error during executing shell command: %s (%s)" % (failmsg, result))
#     
#     for line in result.splitlines():
#         Console.debug(line)
#     
#     Console.outdent()
#     
#     return result


import os.path, re, urllib.parse, shutil
import jasy.core.Console as Console
from jasy.core.Util import executeCommand
# Copyright 2010-2012 Zynga Inc.
#




__versionNumber = re.compile(r"^v?([0-9\.]+)(-?(a|b|rc|alpha|beta)([0-9]+)?)?\+?$")

__gitAccountUrl = re.compile("([a-zA-Z0-9-_]+)@([a-zA-Z0-9-_\.]+):([a-zA-Z0-9/_-]+\.git)")
__gitHash = re.compile(r"^[a-f0-9]{40}$")
__gitSchemes = ('git', 'git+http', 'git+https', 'git+ssh', 'git+git', 'git+file')


def update(url, version, path, update=True, submodules=True):
    """Clones the given repository URL (optionally with overriding/update features)"""

    # Prepend git+ so that user knows that we identified the URL as git repository
    if not url.startswith("git+"):
        url = "git+%s" % url

    old = os.getcwd()

    if os.path.exists(path) and os.path.exists(os.path.join(path, ".git")):
        
        if not os.path.exists(os.path.join(path, ".git", "HEAD")):
            Console.error("Invalid git clone. Cleaning up...")
            shutil.rmtree(path)

        else:
            os.chdir(path)

# Path: jasy/core/Util.py
# def executeCommand(args, failmsg=None, path=None):
#     """
#     Executes the given process and outputs failmsg when errors happen.
#     Returns the combined shell output (stdout and strerr combined).
# 
#     :param args: 
#     :type args: str or list
#     :param failmsg: Message for exception when command fails
#     :type failmsg: str
#     :param path: Directory path where the command should be executed
#     :type path: str
#     :raise Exception: Raises an exception whenever the shell command fails in execution
#     """
# 
#     if type(args) == str:
#         args = shlex.split(args)
# 
#     prevpath = os.getcwd()
# 
#     # Execute in custom directory
#     if path:
#         path = os.path.abspath(os.path.expanduser(path))
#         os.chdir(path)
# 
#     Console.debug("Executing command: %s", " ".join(args))
#     Console.indent()
#     
#     # Using shell on Windows to resolve binaries like "git"
#     output = tempfile.TemporaryFile(mode="w+t")
#     returnValue = subprocess.call(args, stdout=output, stderr=output, shell=sys.platform == "win32")
#         
#     output.seek(0)
#     result = output.read().strip("\n\r")
#     output.close()
# 
#     # Change back to previous path
#     os.chdir(prevpath)
# 
#     if returnValue != 0:
#         raise Exception("Error during executing shell command: %s (%s)" % (failmsg, result))
#     
#     for line in result.splitlines():
#         Console.debug(line)
#     
#     Console.outdent()
#     
#     return result


# Path: jasy/vcs/Git.py
import os.path, re, urllib.parse, shutil
import jasy.core.Console as Console
from jasy.core.Util import executeCommand

# Copyright 2010-2012 Zynga Inc.
#




__versionNumber = re.compile(r"^v?([0-9\.]+)(-?(a|b|rc|alpha|beta)([0-9]+)?)?\+?$")

__gitAccountUrl = re.compile("([a-zA-Z0-9-_]+)@([a-zA-Z0-9-_\.]+):([a-zA-Z0-9/_-]+\.git)")
__gitHash = re.compile(r"^[a-f0-9]{40}$")
__gitSchemes = ('git', 'git+http', 'git+https', 'git+ssh', 'git+git', 'git+file')


def update(url, version, path, update=True, submodules=True):
    """Clones the given repository URL (optionally with overriding/update features)"""

    # Prepend git+ so that user knows that we identified the URL as git repository
    if not url.startswith("git+"):
        url = "git+%s" % url

    old = os.getcwd()

    if os.path.exists(path) and os.path.exists(os.path.join(path, ".git")):
        
        if not os.path.exists(os.path.join(path, ".git", "HEAD")):
            Console.error("Invalid git clone. Cleaning up...")
            shutil.rmtree(path)

        else:
            os.chdir(path)

            revision = executeCommand(["git", "rev-parse", "HEAD"], "Could not detect current revision")