Completed
Pull Request — master (#623)
by
unknown
57s
created

cookiecutter.cookiecutter()   C

Complexity

Conditions 7

Size

Total Lines 73

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 73
rs 5.5062
cc 7

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
16
import logging
17
18
import os
19
import re
20
21
from .config import get_user_config, get_user_config_path
22
from .exceptions import InvalidModeException
23
from .generate import generate_context, generate_files
24
from .prompt import prompt_for_config
25
from .replay import dump, load
26
from .vcs import clone
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 = """
36
(
37
((git|ssh|https|http):(//)?)    # something like git:// ssh:// etc.
38
 |                              # or
39
 (\w+@[\w\.]+)                  # something like user@...
40
)
41
.*
42
"""
43
44
45
def is_repo_url(value):
46
    """Return True if value is a repository URL."""
47
    return bool(re.match(REPO_REGEX, value, re.VERBOSE))
48
49
50
def expand_abbreviations(template, config_dict):
51
    """
52
    Expand abbreviations in a template name.
53
54
    :param template: The project template name.
55
    :param config_dict: The user config, which will contain abbreviation
56
        definitions.
57
    """
58
59
    abbreviations = builtin_abbreviations.copy()
60
    abbreviations.update(config_dict.get('abbreviations', {}))
61
62
    if template in abbreviations:
63
        return abbreviations[template]
64
65
    # Split on colon. If there is no colon, rest will be empty
66
    # and prefix will be the whole template
67
    prefix, sep, rest = template.partition(':')
68
    if prefix in abbreviations:
69
        return abbreviations[prefix].format(rest)
70
71
    return template
72
73
74
def cookiecutter(
75
        template, checkout=None, no_input=False, extra_context=None,
76
        replay=False, overwrite_if_exists=False, output_dir='.',
77
        config_file=None):
78
    """
79
    API equivalent to using Cookiecutter at the command line.
80
81
    :param template: A directory containing a project template directory,
82
        or a URL to a git repository.
83
    :param checkout: The branch, tag or commit ID to checkout after clone.
84
    :param no_input: Prompt the user at command line for manual configuration?
85
    :param extra_context: A dictionary of context that overrides default
86
        and user configuration.
87
    :param: overwrite_if_exists: Overwrite the contents of output directory
88
        if it exists
89
    :param output_dir: Where to output the generated project dir into.
90
    :param config_file: User configuration file path.
91
    """
92
    if config_file is None:
93
        config_file = get_user_config_path()
94
95
    if replay and ((no_input is not False) or (extra_context is not None)):
96
        err_msg = (
97
            "You can not use both replay and no_input or extra_context "
98
            "at the same time."
99
        )
100
        raise InvalidModeException(err_msg)
101
102
    # Get user config from ~/.cookiecutterrc or equivalent
103
    # If no config file,
104
    #   sensible defaults from config.get_default_config() are used
105
    config_dict = get_user_config(config_file=config_file)
106
107
    template = expand_abbreviations(template, config_dict)
108
109
    if is_repo_url(template):
110
        repo_dir = clone(
111
            repo_url=template,
112
            checkout=checkout,
113
            clone_to_dir=config_dict['cookiecutters_dir'],
114
            no_input=no_input
115
        )
116
    else:
117
        # If it's a local repo, no need to clone or copy to your
118
        # cookiecutters_dir
119
        repo_dir = template
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
        # prompt the user to manually configure at the command line.
136
        # except when 'no-input' flag is set
137
        context['cookiecutter'] = prompt_for_config(context, no_input)
138
139
        dump(config_dict['replay_dir'], template_name, context)
140
141
    # Create project from local context and project template.
142
    return generate_files(
143
        repo_dir=repo_dir,
144
        context=context,
145
        overwrite_if_exists=overwrite_if_exists,
146
        output_dir=output_dir
147
    )
148