Completed
Push — master ( 14c8ac...ce45ac )
by Michael
7s
created

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