Completed
Pull Request — master (#914)
by
unknown
01:36
created

prompt_and_delete_repo()   B

Complexity

Conditions 3

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
c 2
b 0
f 0
dl 0
loc 24
rs 8.9713
1
# -*- coding: utf-8 -*-
2
3
"""Helper functions for working with version control systems."""
4
5
from __future__ import unicode_literals
6
import logging
7
import os
8
import subprocess
9
import sys
10
11
from whichcraft import which
12
13
from .exceptions import (
14
    RepositoryNotFound, RepositoryCloneFailed, UnknownRepoType, VCSNotInstalled
15
)
16
from .prompt import read_user_yes_no
17
from .utils import make_sure_path_exists, rmtree
18
19
logger = logging.getLogger(__name__)
20
21
22
BRANCH_ERRORS = [
23
    'error: pathspec',
24
    'unknown revision',
25
]
26
27
28
def prompt_and_delete_repo(repo_dir, no_input=False):
29
    """Ask the user whether it's okay to delete the previously-cloned repo.
30
31
    If yes, deletes it. Otherwise, Cookiecutter exits.
32
33
    :param repo_dir: Directory of previously-cloned repo.
34
    :param no_input: Suppress prompt to delete repo and just delete it.
35
    """
36
    # Suppress prompt if called via API
37
    if no_input:
38
        ok_to_delete = True
39
    else:
40
        question = (
41
            "You've cloned {} before. "
42
            "And It wasn't possible to pull new changes. "
43
            "Is it okay to delete and re-clone it?"
44
        ).format(repo_dir)
45
46
        ok_to_delete = read_user_yes_no(question, 'yes')
47
48
    if ok_to_delete:
49
        rmtree(repo_dir)
50
    else:
51
        sys.exit()
52
53
54
def identify_repo(repo_url):
55
    """Determine if `repo_url` should be treated as a URL to a git or hg repo.
56
57
    Repos can be identified by prepending "hg+" or "git+" to the repo URL.
58
59
    :param repo_url: Repo URL of unknown type.
60
    :returns: ('git', repo_url), ('hg', repo_url), or None.
61
    """
62
    repo_url_values = repo_url.split('+')
63
    if len(repo_url_values) == 2:
64
        repo_type = repo_url_values[0]
65
        if repo_type in ["git", "hg"]:
66
            return repo_type, repo_url_values[1]
67
        else:
68
            raise UnknownRepoType
69
    else:
70
        if 'git' in repo_url:
71
            return 'git', repo_url
72
        elif 'bitbucket' in repo_url:
73
            return 'hg', repo_url
74
        else:
75
            raise UnknownRepoType
76
77
78
def is_vcs_installed(repo_type):
79
    """
80
    Check if the version control system for a repo type is installed.
81
82
    :param repo_type:
83
    """
84
    return bool(which(repo_type))
85
86
87
def clone(repo_url, checkout=None, clone_to_dir='.', no_input=False):
88
    """Clone a repo to the current directory.
89
90
    :param repo_url: Repo URL of unknown type.
91
    :param checkout: The branch, tag or commit ID to checkout after clone.
92
    :param clone_to_dir: The directory to clone to.
93
                         Defaults to the current directory.
94
    :param no_input: Suppress all user prompts when calling via API.
95
    """
96
    # Ensure that clone_to_dir exists
97
    clone_to_dir = os.path.expanduser(clone_to_dir)
98
    make_sure_path_exists(clone_to_dir)
99
100
    # identify the repo_type
101
    repo_type, repo_url = identify_repo(repo_url)
102
103
    # check that the appropriate VCS for the repo_type is installed
104
    if not is_vcs_installed(repo_type):
105
        msg = "'{0}' is not installed.".format(repo_type)
106
        raise VCSNotInstalled(msg)
107
108
    repo_url = repo_url.rstrip('/')
109
    tail = os.path.split(repo_url)[1]
110
    if repo_type == 'git':
111
        repo_dir = os.path.normpath(os.path.join(clone_to_dir,
112
                                                 tail.rsplit('.git')[0]))
113
    elif repo_type == 'hg':
114
        repo_dir = os.path.normpath(os.path.join(clone_to_dir, tail))
115
    logger.debug('repo_dir is {0}'.format(repo_dir))
116
117
    if os.path.isdir(repo_dir):
118
        # Try to pull from origin repo before re-cloning
119
        try:
120
            if checkout is not None:
121
                subprocess.check_output(
122
                    [repo_type, 'checkout', checkout],
123
                    cwd=repo_dir,
124
                    stderr=subprocess.STDOUT,
125
                )
126
127
            if repo_type == 'git':
128
                pull_cmd = [repo_type, 'pull', 'origin', checkout or 'master']
129
            elif repo_type == 'hg':
130
                pull_cmd = [repo_type, 'pull', checkout or 'default']
131
            subprocess.check_output(
132
                pull_cmd,
133
                cwd=repo_dir,
134
                stderr=subprocess.STDOUT,
135
            )
136
137
            return repo_dir
138
        except subprocess.CalledProcessError:
139
            prompt_and_delete_repo(repo_dir, no_input=no_input)
140
141
    try:
142
        subprocess.check_output(
143
            [repo_type, 'clone', repo_url],
144
            cwd=clone_to_dir,
145
            stderr=subprocess.STDOUT,
146
        )
147
        if checkout is not None:
148
            subprocess.check_output(
149
                [repo_type, 'checkout', checkout],
150
                cwd=repo_dir,
151
                stderr=subprocess.STDOUT,
152
            )
153
    except subprocess.CalledProcessError as clone_error:
154
        if 'not found' in clone_error.output.lower():
155
            raise RepositoryNotFound(
156
                'The repository {} could not be found, '
157
                'have you made a typo?'.format(repo_url)
158
            )
159
        if any(error in clone_error.output for error in BRANCH_ERRORS):
160
            raise RepositoryCloneFailed(
161
                'The {} branch of repository {} could not found, '
162
                'have you made a typo?'.format(checkout, repo_url)
163
            )
164
        raise
165
166
    return repo_dir
167