Completed
Pull Request — master (#989)
by
unknown
28s
created

main()   D

Complexity

Conditions 8

Size

Total Lines 111

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 8
c 2
b 0
f 0
dl 0
loc 111
rs 4

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
# -*- coding: utf-8 -*-
2
3
"""Main `cookiecutter` CLI."""
4
5
import os
6
import sys
7
import json
8
9
import click
10
11
from cookiecutter import __version__
12
from cookiecutter.log import configure_logger
13
from cookiecutter.main import cookiecutter
14
from cookiecutter.exceptions import (
15
    OutputDirExistsException,
16
    InvalidModeException,
17
    FailedHookException,
18
    UndefinedVariableInTemplate,
19
    UnknownExtension,
20
    RepositoryNotFound,
21
    RepositoryCloneFailed
22
)
23
24
25
def version_msg():
26
    """Return the Cookiecutter version, location and Python powering it."""
27
    python_version = sys.version[:3]
28
    location = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
29
    message = u'Cookiecutter %(version)s from {} (Python {})'
30
    return message.format(location, python_version)
31
32
33
def validate_extra_context(ctx, param, value):
34
    """Validate extra context."""
35
    for s in value:
36
        if '=' not in s:
37
            raise click.BadParameter(
38
                'EXTRA_CONTEXT should contain items of the form key=value; '
39
                "'{}' doesn't match that form".format(s)
40
            )
41
42
    # Convert tuple -- e.g.: (u'program_name=foobar', u'startsecs=66')
43
    # to dict -- e.g.: {'program_name': 'foobar', 'startsecs': '66'}
44
    return dict(s.split('=', 1) for s in value) or None
45
46
47
@click.command(context_settings=dict(help_option_names=[u'-h', u'--help']))
48
@click.version_option(__version__, u'-V', u'--version', message=version_msg())
49
@click.argument(u'template')
50
@click.argument(u'extra_context', nargs=-1, callback=validate_extra_context)
51
@click.option(
52
    u'--no-input', is_flag=True,
53
    help=u'Do not prompt for parameters and only use cookiecutter.json '
54
         u'file content',
55
)
56
@click.option(
57
    u'-c', u'--checkout',
58
    help=u'branch, tag or commit to checkout after git clone',
59
)
60
@click.option(
61
    '-v', '--verbose',
62
    is_flag=True, help='Print debug information', default=False
63
)
64
@click.option(
65
    u'--replay', is_flag=True,
66
    help=u'Do not prompt for parameters and only use information entered '
67
         u'previously',
68
)
69
@click.option(
70
    u'-f', u'--overwrite-if-exists', is_flag=True,
71
    help=u'Overwrite the contents of the output directory if it already exists'
72
)
73
@click.option(
74
    u'-o', u'--output-dir', default='.', type=click.Path(),
75
    help=u'Where to output the generated project dir into'
76
)
77
@click.option(
78
    u'--config-file', type=click.Path(), default=None,
79
    help=u'User configuration file'
80
)
81
@click.option(
82
    u'--default-config', is_flag=True,
83
    help=u'Do not load a config file. Use the defaults instead'
84
)
85
@click.option(
86
    u'--debug-file', type=click.Path(), default=None,
87
    help=u'File to be used as a stream for DEBUG logging',
88
)
89
def main(
90
        template, extra_context, no_input, checkout, verbose,
91
        replay, overwrite_if_exists, output_dir, config_file,
92
        default_config, debug_file):
93
    """Create a project from a Cookiecutter project template (TEMPLATE).
94
95
    TEMPLATE is a local path or a link to a cookiecutter project template.
96
    It can also be help, python, django or pytest for Cookiecutter
97
    specials.
98
99
    Cookiecutter is free and open source software, developed and managed by
100
    volunteers. If you would like to help out or fund the project, please get
101
    in touch at https://github.com/audreyr/cookiecutter.
102
    """
103
    # If you _need_ to support a local template in a directory
104
    # called 'help', use a qualified path to the directory.
105
    if template == u'help':
106
        click.echo(click.get_current_context().get_help())
107
        sys.exit(0)
108
    elif template == u'python':
109
        template = 'https://github.com/audreyr/cookiecutter-pypackage'
110
        click.echo(
111
            'Using default Python package project template {}'.format(template)
112
        )
113
    elif template == u'django':
114
        template = 'https://github.com/pydanny/cookiecutter-django'
115
        click.echo(
116
            'Using default Django project template {}'.format(template)
117
        )
118
    elif template == u'pytest':
119
        template = 'https://github.com/pytest-dev/cookiecutter-pytest-plugin'
120
        click.echo(
121
            'Using default pytest template {}'.format(template)
122
        )
123
124
    configure_logger(
125
        stream_level='DEBUG' if verbose else 'INFO',
126
        debug_file=debug_file,
127
    )
128
129
    try:
130
        cookiecutter(
131
            template, checkout, no_input,
132
            extra_context=extra_context,
133
            replay=replay,
134
            overwrite_if_exists=overwrite_if_exists,
135
            output_dir=output_dir,
136
            config_file=config_file,
137
            default_config=default_config,
138
        )
139
    except (OutputDirExistsException,
140
            InvalidModeException,
141
            FailedHookException,
142
            UnknownExtension,
143
            RepositoryNotFound,
144
            RepositoryCloneFailed) as e:
145
        click.echo(e)
146
        sys.exit(1)
147
    except UndefinedVariableInTemplate as undefined_err:
148
        click.echo('{}'.format(undefined_err.message))
149
        click.echo('Error message: {}'.format(undefined_err.error.message))
150
151
        context_str = json.dumps(
152
            undefined_err.context,
153
            indent=4,
154
            sort_keys=True
155
        )
156
        click.echo('Context: {}'.format(context_str))
157
        sys.exit(1)
158
159
160
if __name__ == "__main__":
161
    main()
162