Completed
Push — update-cookiecutter-command ( e74ec6 )
by Michael
01:05
created

cookiecutter.generate()   B

Complexity

Conditions 6

Size

Total Lines 86

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 6
dl 0
loc 86
rs 7.2894

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.cli
6
-----------------
7
8
Main `cookiecutter` CLI.
9
"""
10
11
import os
12
import sys
13
import logging
14
import json
15
16
import click
17
18
from cookiecutter import __version__
19
from cookiecutter.config import USER_CONFIG_PATH
20
from cookiecutter.main import cookiecutter
21
from cookiecutter.exceptions import (
22
    OutputDirExistsException,
23
    InvalidModeException,
24
    FailedHookException,
25
    UndefinedVariableInTemplate,
26
    UnknownExtension,
27
    RepositoryNotFound
28
)
29
30
logger = logging.getLogger(__name__)
31
32
33
def version_msg():
34
    python_version = sys.version[:3]
35
    location = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
36
    message = u'Cookiecutter %(version)s from {} (Python {})'
37
    return message.format(location, python_version)
38
39
40
@click.command(context_settings=dict(help_option_names=[u'-h', u'--help']))
41
@click.version_option(__version__, u'-V', u'--version', message=version_msg())
42
@click.argument(u'template')
43
@click.option(
44
    u'--no-input', is_flag=True,
45
    help=u'Do not prompt for parameters and only use cookiecutter.json '
46
         u'file content',
47
)
48
@click.option(
49
    u'-c', u'--checkout',
50
    help=u'branch, tag or commit to checkout after git clone',
51
)
52
@click.option(
53
    '-v', '--verbose',
54
    is_flag=True, help='Print debug information', default=False
55
)
56
@click.option(
57
    u'--replay', is_flag=True,
58
    help=u'Do not prompt for parameters and only use information entered '
59
         u'previously',
60
)
61
@click.option(
62
    u'-f', u'--overwrite-if-exists', is_flag=True,
63
    help=u'Overwrite the contents of the output directory if it already exists'
64
)
65
@click.option(
66
    u'-o', u'--output-dir', default='.', type=click.Path(),
67
    help=u'Where to output the generated project dir into'
68
)
69
@click.option(
70
    u'--config-file', type=click.Path(), default=USER_CONFIG_PATH,
71
    help=u'User configuration file'
72
)
73
@click.option(
74
    u'--default-config', is_flag=True,
75
    help=u'Do not load a config file. Use the defaults instead'
76
)
77
def generate(template, no_input, checkout, verbose, replay,
78
             overwrite_if_exists, output_dir, config_file, default_config):
79
    """Create a project from a Cookiecutter project template (TEMPLATE)."""
80
    if verbose:
81
        logging.basicConfig(
82
            format=u'%(levelname)s %(filename)s: %(message)s',
83
            level=logging.DEBUG
84
        )
85
    else:
86
        # Log info and above to console
87
        logging.basicConfig(
88
            format=u'%(levelname)s: %(message)s',
89
            level=logging.INFO
90
        )
91
92
    try:
93
        # If you _need_ to support a local template in a directory
94
        # called 'help', use a qualified path to the directory.
95
        if template == u'help':
96
            click.echo(click.get_current_context().get_help())
97
            sys.exit(0)
98
99
        user_config = None if default_config else config_file
100
101
        cookiecutter(
102
            template, checkout, no_input,
103
            replay=replay,
104
            overwrite_if_exists=overwrite_if_exists,
105
            output_dir=output_dir,
106
            config_file=user_config
107
        )
108
    except (OutputDirExistsException,
109
            InvalidModeException,
110
            FailedHookException,
111
            UnknownExtension,
112
            RepositoryNotFound) as e:
113
        click.echo(e)
114
        sys.exit(1)
115
    except UndefinedVariableInTemplate as undefined_err:
116
        click.echo('{}'.format(undefined_err.message))
117
        click.echo('Error message: {}'.format(undefined_err.error.message))
118
119
        context_str = json.dumps(
120
            undefined_err.context,
121
            indent=4,
122
            sort_keys=True
123
        )
124
        click.echo('Context: {}'.format(context_str))
125
        sys.exit(1)
126
127
128
if __name__ == "__main__":
129
    generate()
130
131
132
@click.command()
133
@click.argument('template')
134
@click.option(
135
    '-c', '--checkout',
136
    help='branch, tag or commit to checkout after git clone',
137
)
138
@click.option(
139
    '--no-input', is_flag=True,
140
    help='Do not prompt for parameters and only use cookiecutter.json '
141
         'file content',
142
)
143
def update(template, checkout, no_input):
144
    """Updates a rendered project"""
145
    cookiecutter(template, checkout, no_input, overwrite=False)
146