Completed
Pull Request — master (#961)
by
unknown
41s
created

clone()   F

Complexity

Conditions 11

Size

Total Lines 63

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
c 0
b 0
f 0
dl 0
loc 63
rs 3.9705

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like clone() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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 .utils import make_sure_path_exists, prompt_and_delete
17
18
logger = logging.getLogger(__name__)
19
20
21
BRANCH_ERRORS = [
22
    'error: pathspec',
23
    'unknown revision',
24
]
25
26
27
def identify_repo(repo_url):
28
    """Determine if `repo_url` should be treated as a URL to a git or hg repo.
29
30
    Repos can be identified by prepending "hg+" or "git+" to the repo URL.
31
32
    :param repo_url: Repo URL of unknown type.
33
    :returns: ('git', repo_url), ('hg', repo_url), or None.
34
    """
35
    repo_url_values = repo_url.split('+')
36
    if len(repo_url_values) == 2:
37
        repo_type = repo_url_values[0]
38
        if repo_type in ["git", "hg"]:
39
            return repo_type, repo_url_values[1]
40
        else:
41
            raise UnknownRepoType
42
    else:
43
        if 'git' in repo_url:
44
            return 'git', repo_url
45
        elif 'bitbucket' in repo_url:
46
            return 'hg', repo_url
47
        else:
48
            raise UnknownRepoType
49
50
51
def is_vcs_installed(repo_type):
52
    """
53
    Check if the version control system for a repo type is installed.
54
55
    :param repo_type:
56
    """
57
    return bool(which(repo_type))
58
59
60
def clone(repo_url, checkout=None, clone_to_dir='.', no_input=False):
61
    """Clone a repo to the current directory.
62
63
    :param repo_url: Repo URL of unknown type.
64
    :param checkout: The branch, tag or commit ID to checkout after clone.
65
    :param clone_to_dir: The directory to clone to.
66
                         Defaults to the current directory.
67
    :param no_input: Suppress all user prompts when calling via API.
68
    """
69
    # Ensure that clone_to_dir exists
70
    clone_to_dir = os.path.expanduser(clone_to_dir)
71
    make_sure_path_exists(clone_to_dir)
72
73
    # identify the repo_type
74
    repo_type, repo_url = identify_repo(repo_url)
75
76
    # check that the appropriate VCS for the repo_type is installed
77
    if not is_vcs_installed(repo_type):
78
        msg = "'{0}' is not installed.".format(repo_type)
79
        raise VCSNotInstalled(msg)
80
81
    repo_url = repo_url.rstrip('/')
82
    tail = os.path.split(repo_url)[1]
83
    if repo_type == 'git':
84
        repo_dir = os.path.normpath(os.path.join(clone_to_dir,
85
                                                 tail.rsplit('.git')[0]))
86
    elif repo_type == 'hg':
87
        repo_dir = os.path.normpath(os.path.join(clone_to_dir, tail))
88
    logger.debug('repo_dir is {0}'.format(repo_dir))
89
90
    if os.path.isdir(repo_dir):
91
        clone = prompt_and_delete(repo_dir, no_input=no_input)
92
    else:
93
        clone = True
94
95
    if clone:
96
        try:
97
            subprocess.check_output(
98
                [repo_type, 'clone', repo_url],
99
                cwd=clone_to_dir,
100
                stderr=subprocess.STDOUT,
101
            )
102
            if checkout is not None:
103
                subprocess.check_output(
104
                    [repo_type, 'checkout', checkout],
105
                    cwd=repo_dir,
106
                    stderr=subprocess.STDOUT,
107
                )
108
        except subprocess.CalledProcessError as clone_error:
109
            output = clone_error.output.decode('utf-8')
110
            if 'not found' in output.lower():
111
                raise RepositoryNotFound(
112
                    'The repository {} could not be found, '
113
                    'have you made a typo?'.format(repo_url)
114
                )
115
            if any(error in output for error in BRANCH_ERRORS):
116
                raise RepositoryCloneFailed(
117
                    'The {} branch of repository {} could not found, '
118
                    'have you made a typo?'.format(checkout, repo_url)
119
                )
120
            raise
121
122
    return repo_dir
123