Completed
Pull Request — master (#694)
by Eric
01:25
created

cookiecutter()   D

Complexity

Conditions 8

Size

Total Lines 76

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
c 0
b 0
f 0
dl 0
loc 76
rs 4.8823

How to fix   Long Method   

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:

1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
4
"""
5
cookiecutter.main
6
-----------------
7
8
Main entry point for the `cookiecutter` command.
9
10
The code in this module is also a good example of how to use Cookiecutter as a
11
library rather than a script.
12
"""
13
14
from __future__ import unicode_literals
15
import logging
16
import os
17
import re
18
19
from .config import get_user_config, USER_CONFIG_PATH
20
from .exceptions import InvalidModeException, RepositoryNotFound
21
from .prompt import prompt_for_config
22
from .generate import generate_context, generate_files
23
from .vcs import clone
24
from .replay import dump, load
25
from .utils import work_in
26
from .hooks import run_hook
27
28
logger = logging.getLogger(__name__)
29
30
builtin_abbreviations = {
31
    'gh': 'https://github.com/{0}.git',
32
    'bb': 'https://bitbucket.org/{0}',
33
}
34
35
REPO_REGEX = re.compile(r"""
36
(?x)
37
((((git|hg)\+)?(git|ssh|https?):(//)?)  # something like git:// ssh:// etc.
38
 |                                      # or
39
 (\w+@[\w\.]+)                          # something like user@...
40
)
41
""")
42
43
44
def is_repo_url(value):
45
    """Return True if value is a repository URL."""
46
    return bool(REPO_REGEX.match(value))
47
48
49
def expand_abbreviations(template, config_dict):
50
    """
51
    Expand abbreviations in a template name.
52
53
    :param template: The project template name.
54
    :param config_dict: The user config, which will contain abbreviation
55
        definitions.
56
    """
57
58
    abbreviations = builtin_abbreviations.copy()
59
    abbreviations.update(config_dict.get('abbreviations', {}))
60
61
    if template in abbreviations:
62
        return abbreviations[template]
63
64
    # Split on colon. If there is no colon, rest will be empty
65
    # and prefix will be the whole template
66
    prefix, sep, rest = template.partition(':')
67
    if prefix in abbreviations:
68
        return abbreviations[prefix].format(rest)
69
70
    return template
71
72
73
def cookiecutter(
74
        template, checkout=None, no_input=False, extra_context=None,
75
        replay=False, overwrite_if_exists=False, output_dir='.',
76
        config_file=USER_CONFIG_PATH):
77
    """
78
    API equivalent to using Cookiecutter at the command line.
79
80
    :param template: A directory containing a project template directory,
81
        or a URL to a git repository.
82
    :param checkout: The branch, tag or commit ID to checkout after clone.
83
    :param no_input: Prompt the user at command line for manual configuration?
84
    :param extra_context: A dictionary of context that overrides default
85
        and user configuration.
86
    :param: overwrite_if_exists: Overwrite the contents of output directory
87
        if it exists
88
    :param output_dir: Where to output the generated project dir into.
89
    :param config_file: User configuration file path.
90
    """
91
    if replay and ((no_input is not False) or (extra_context is not None)):
92
        err_msg = (
93
            "You can not use both replay and no_input or extra_context "
94
            "at the same time."
95
        )
96
        raise InvalidModeException(err_msg)
97
98
    # Get user config from ~/.cookiecutterrc or equivalent
99
    # If no config file, sensible defaults from config.DEFAULT_CONFIG are used
100
    config_dict = get_user_config(config_file=config_file)
101
102
    template = expand_abbreviations(template, config_dict)
103
104
    if is_repo_url(template):
105
        repo_dir = clone(
106
            repo_url=template,
107
            checkout=checkout,
108
            clone_to_dir=config_dict['cookiecutters_dir'],
109
            no_input=no_input
110
        )
111
    else:
112
        # If it's a local repo, no need to clone or copy to your
113
        # cookiecutters_dir
114
        repo_dir = template
115
116
    if not os.path.isdir(repo_dir):
117
        raise RepositoryNotFound(
118
            'The repository {0} could not be located.'.format(template)
119
        )
120
121
    template_name = os.path.basename(template)
122
123
    if replay:
124
        context = load(config_dict['replay_dir'], template_name)
125
    else:
126
        context_file = os.path.join(repo_dir, 'cookiecutter.json')
127
        logging.debug('context_file is {0}'.format(context_file))
128
129
        context = generate_context(
130
            context_file=context_file,
131
            default_context=config_dict['default_context'],
132
            extra_context=extra_context,
133
        )
134
135
        with work_in(repo_dir):
136
            context = run_hook('pre_user_prompt', repo_dir, context)
137
        # prompt the user to manually configure at the command line.
138
        # except when 'no-input' flag is set
139
        context['cookiecutter'] = prompt_for_config(context, no_input)
140
141
        dump(config_dict['replay_dir'], template_name, context)
142
143
    # Create project from local context and project template.
144
    return generate_files(
145
        repo_dir=repo_dir,
146
        context=context,
147
        overwrite_if_exists=overwrite_if_exists,
148
        output_dir=output_dir
149
    )
150