def clone_git_repo(git_url, target_dir, commit=None):
    """
    clone provided git repo to target_dir, optionally checkout provided commit

    :param git_url: str, git repo to clone
    :param target_dir: str, filesystem path where the repo should be cloned
    :param commit: str, commit to checkout, SHA-1 or ref
    :return: str, commit ID of HEAD
    """
    commit = commit or "master"
    logger.info("cloning git repo '%s'", git_url)
    logger.debug("url = '%s', dir = '%s', commit = '%s'",
                 git_url, target_dir, commit)

    cmd = ["git", "clone", "-b", commit, "--depth", "1", git_url, quote(target_dir)]
    logger.debug("doing a shallow clone '%s'", cmd)
    try:
        subprocess.check_call(cmd)
    except subprocess.CalledProcessError as ex:
        logger.warning(repr(ex))
        # http://stackoverflow.com/questions/1911109/clone-a-specific-git-branch/4568323#4568323
        # -b takes only refs, not SHA-1
        cmd = ["git", "clone", "-b", commit, "--single-branch", git_url, quote(target_dir)]
        logger.debug("cloning single branch '%s'", cmd)
        try:
            subprocess.check_call(cmd)
        except subprocess.CalledProcessError as ex:
            logger.warning(repr(ex))
            # let's try again with plain `git clone $url && git checkout`
            cmd = ["git", "clone", git_url, quote(target_dir)]
            logger.debug("cloning '%s'", cmd)
            subprocess.check_call(cmd)
            cmd = ["git", "reset", "--hard", commit]
            logger.debug("checking out branch '%s'", cmd)
            subprocess.check_call(cmd, cwd=target_dir)
    cmd = ["git", "rev-parse", "HEAD"]
    logger.debug("getting SHA-1 of provided ref '%s'", cmd)
    try:
        commit_id = subprocess.check_output(cmd, cwd=target_dir)  # py 2.7
    except __HOLE__:
        commit_id = backported_check_output(cmd, cwd=target_dir)  # py 2.6
    commit_id = commit_id.strip()
    logger.info("commit ID = %s", commit_id)
    return commit_id
dataset/ETHPy150Open projectatomic/atomic-reactor/atomic_reactor/util.py/clone_git_repo