Skip to content

Commit

Permalink
Revert black implementation (cookiecutter#1299)
Browse files Browse the repository at this point in the history
  • Loading branch information
insspb authored Feb 1, 2020
1 parent 527f716 commit 15f6f53
Show file tree
Hide file tree
Showing 77 changed files with 2,141 additions and 1,801 deletions.
6 changes: 0 additions & 6 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
---
repos:
- repo: https://github.com/psf/black
rev: 19.10b0
hooks:
- id: black
exclude: ^tests\/hooks-abort-render\/hooks
language_version: python3.7
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.4.0
hooks:
Expand Down
2 changes: 1 addition & 1 deletion cookiecutter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@

"""Main package for Cookiecutter."""

__version__ = "1.7.0"
__version__ = '1.7.0'
128 changes: 56 additions & 72 deletions cookiecutter/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,100 +20,83 @@
UnknownExtension,
InvalidZipRepository,
RepositoryNotFound,
RepositoryCloneFailed,
RepositoryCloneFailed
)


def version_msg():
"""Return the Cookiecutter version, location and Python powering it."""
python_version = sys.version[:3]
location = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
message = u"Cookiecutter %(version)s from {} (Python {})"
message = u'Cookiecutter %(version)s from {} (Python {})'
return message.format(location, python_version)


def validate_extra_context(ctx, param, value):
"""Validate extra context."""
for s in value:
if "=" not in s:
if '=' not in s:
raise click.BadParameter(
"EXTRA_CONTEXT should contain items of the form key=value; "
'EXTRA_CONTEXT should contain items of the form key=value; '
"'{}' doesn't match that form".format(s)
)

# Convert tuple -- e.g.: (u'program_name=foobar', u'startsecs=66')
# to dict -- e.g.: {'program_name': 'foobar', 'startsecs': '66'}
return collections.OrderedDict(s.split("=", 1) for s in value) or None
return collections.OrderedDict(s.split('=', 1) for s in value) or None


@click.command(context_settings=dict(help_option_names=[u"-h", u"--help"]))
@click.version_option(__version__, u"-V", u"--version", message=version_msg())
@click.argument(u"template")
@click.argument(u"extra_context", nargs=-1, callback=validate_extra_context)
@click.command(context_settings=dict(help_option_names=[u'-h', u'--help']))
@click.version_option(__version__, u'-V', u'--version', message=version_msg())
@click.argument(u'template')
@click.argument(u'extra_context', nargs=-1, callback=validate_extra_context)
@click.option(
u"--no-input",
is_flag=True,
help=u"Do not prompt for parameters and only use cookiecutter.json "
u"file content",
u'--no-input', is_flag=True,
help=u'Do not prompt for parameters and only use cookiecutter.json '
u'file content',
)
@click.option(
u"-c", u"--checkout", help=u"branch, tag or commit to checkout after git clone",
u'-c', u'--checkout',
help=u'branch, tag or commit to checkout after git clone',
)
@click.option(
u"--directory",
help=u"Directory within repo that holds cookiecutter.json file "
u"for advanced repositories with multi templates in it",
u'--directory',
help=u'Directory within repo that holds cookiecutter.json file '
u'for advanced repositories with multi templates in it',
)
@click.option(
"-v", "--verbose", is_flag=True, help="Print debug information", default=False,
'-v', '--verbose',
is_flag=True, help='Print debug information', default=False
)
@click.option(
u"--replay",
is_flag=True,
help=u"Do not prompt for parameters and only use information entered "
u"previously",
u'--replay', is_flag=True,
help=u'Do not prompt for parameters and only use information entered '
u'previously',
)
@click.option(
u"-f",
u"--overwrite-if-exists",
is_flag=True,
help=u"Overwrite the contents of the output directory if it already exists",
u'-f', u'--overwrite-if-exists', is_flag=True,
help=u'Overwrite the contents of the output directory if it already exists'
)
@click.option(
u"-o",
u"--output-dir",
default=".",
type=click.Path(),
help=u"Where to output the generated project dir into",
u'-o', u'--output-dir', default='.', type=click.Path(),
help=u'Where to output the generated project dir into'
)
@click.option(
u"--config-file", type=click.Path(), default=None, help=u"User configuration file",
u'--config-file', type=click.Path(), default=None,
help=u'User configuration file'
)
@click.option(
u"--default-config",
is_flag=True,
help=u"Do not load a config file. Use the defaults instead",
u'--default-config', is_flag=True,
help=u'Do not load a config file. Use the defaults instead'
)
@click.option(
u"--debug-file",
type=click.Path(),
default=None,
help=u"File to be used as a stream for DEBUG logging",
u'--debug-file', type=click.Path(), default=None,
help=u'File to be used as a stream for DEBUG logging',
)
def main(
template,
extra_context,
no_input,
checkout,
verbose,
replay,
overwrite_if_exists,
output_dir,
config_file,
default_config,
debug_file,
directory,
):
template, extra_context, no_input, checkout, verbose,
replay, overwrite_if_exists, output_dir, config_file,
default_config, debug_file, directory):
"""Create a project from a Cookiecutter project template (TEMPLATE).
Cookiecutter is free and open source software, developed and managed by
Expand All @@ -122,45 +105,46 @@ def main(
"""
# If you _need_ to support a local template in a directory
# called 'help', use a qualified path to the directory.
if template == u"help":
if template == u'help':
click.echo(click.get_current_context().get_help())
sys.exit(0)

configure_logger(
stream_level="DEBUG" if verbose else "INFO", debug_file=debug_file,
stream_level='DEBUG' if verbose else 'INFO',
debug_file=debug_file,
)

try:
cookiecutter(
template,
checkout,
no_input,
template, checkout, no_input,
extra_context=extra_context,
replay=replay,
overwrite_if_exists=overwrite_if_exists,
output_dir=output_dir,
config_file=config_file,
default_config=default_config,
password=os.environ.get("COOKIECUTTER_REPO_PASSWORD"),
directory=directory,
password=os.environ.get('COOKIECUTTER_REPO_PASSWORD'),
directory=directory
)
except (
OutputDirExistsException,
InvalidModeException,
FailedHookException,
UnknownExtension,
InvalidZipRepository,
RepositoryNotFound,
RepositoryCloneFailed,
) as e:
except (OutputDirExistsException,
InvalidModeException,
FailedHookException,
UnknownExtension,
InvalidZipRepository,
RepositoryNotFound,
RepositoryCloneFailed) as e:
click.echo(e)
sys.exit(1)
except UndefinedVariableInTemplate as undefined_err:
click.echo("{}".format(undefined_err.message))
click.echo("Error message: {}".format(undefined_err.error.message))
click.echo('{}'.format(undefined_err.message))
click.echo('Error message: {}'.format(undefined_err.error.message))

context_str = json.dumps(undefined_err.context, indent=4, sort_keys=True)
click.echo("Context: {}".format(context_str))
context_str = json.dumps(
undefined_err.context,
indent=4,
sort_keys=True
)
click.echo('Context: {}'.format(context_str))
sys.exit(1)


Expand Down
33 changes: 17 additions & 16 deletions cookiecutter/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,19 @@

logger = logging.getLogger(__name__)

USER_CONFIG_PATH = os.path.expanduser("~/.cookiecutterrc")
USER_CONFIG_PATH = os.path.expanduser('~/.cookiecutterrc')

BUILTIN_ABBREVIATIONS = {
"gh": "https://github.com/{0}.git",
"gl": "https://gitlab.com/{0}.git",
"bb": "https://bitbucket.org/{0}",
'gh': 'https://github.com/{0}.git',
'gl': 'https://gitlab.com/{0}.git',
'bb': 'https://bitbucket.org/{0}',
}

DEFAULT_CONFIG = {
"cookiecutters_dir": os.path.expanduser("~/.cookiecutters/"),
"replay_dir": os.path.expanduser("~/.cookiecutter_replay/"),
"default_context": collections.OrderedDict([]),
"abbreviations": BUILTIN_ABBREVIATIONS,
'cookiecutters_dir': os.path.expanduser('~/.cookiecutters/'),
'replay_dir': os.path.expanduser('~/.cookiecutter_replay/'),
'default_context': collections.OrderedDict([]),
'abbreviations': BUILTIN_ABBREVIATIONS,
}


Expand Down Expand Up @@ -64,22 +64,23 @@ def get_config(config_path):
if not os.path.exists(config_path):
raise ConfigDoesNotExistException

logger.debug("config_path is {0}".format(config_path))
with io.open(config_path, encoding="utf-8") as file_handle:
logger.debug('config_path is {0}'.format(config_path))
with io.open(config_path, encoding='utf-8') as file_handle:
try:
yaml_dict = poyo.parse_string(file_handle.read())
except poyo.exceptions.PoyoException as e:
raise InvalidConfiguration(
"Unable to parse YAML file {}. Error: {}" "".format(config_path, e)
'Unable to parse YAML file {}. Error: {}'
''.format(config_path, e)
)

config_dict = merge_configs(DEFAULT_CONFIG, yaml_dict)

raw_replay_dir = config_dict["replay_dir"]
config_dict["replay_dir"] = _expand_path(raw_replay_dir)
raw_replay_dir = config_dict['replay_dir']
config_dict['replay_dir'] = _expand_path(raw_replay_dir)

raw_cookies_dir = config_dict["cookiecutters_dir"]
config_dict["cookiecutters_dir"] = _expand_path(raw_cookies_dir)
raw_cookies_dir = config_dict['cookiecutters_dir']
config_dict['cookiecutters_dir'] = _expand_path(raw_cookies_dir)

return config_dict

Expand Down Expand Up @@ -110,7 +111,7 @@ def get_user_config(config_file=None, default_config=False):

try:
# Does the user set up a config environment variable?
env_config_file = os.environ["COOKIECUTTER_CONFIG"]
env_config_file = os.environ['COOKIECUTTER_CONFIG']
except KeyError:
# Load an optional user config if it exists
# otherwise return the defaults
Expand Down
22 changes: 14 additions & 8 deletions cookiecutter/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,22 @@ def __init__(self, **kwargs):
2. Reads extensions set in the cookiecutter.json _extensions key.
3. Attempts to load the extensions. Provides useful error if fails.
"""
context = kwargs.pop("context", {})
context = kwargs.pop('context', {})

default_extensions = [
"cookiecutter.extensions.JsonifyExtension",
"cookiecutter.extensions.RandomStringExtension",
"jinja2_time.TimeExtension",
'cookiecutter.extensions.JsonifyExtension',
'cookiecutter.extensions.RandomStringExtension',
'jinja2_time.TimeExtension',
]
extensions = default_extensions + self._read_extensions(context)

try:
super(ExtensionLoaderMixin, self).__init__(extensions=extensions, **kwargs)
super(ExtensionLoaderMixin, self).__init__(
extensions=extensions,
**kwargs
)
except ImportError as err:
raise UnknownExtension("Unable to load extension: {}".format(err))
raise UnknownExtension('Unable to load extension: {}'.format(err))

def _read_extensions(self, context):
"""Return list of extensions as str to be passed on to the Jinja2 env.
Expand All @@ -44,7 +47,7 @@ def _read_extensions(self, context):
list instead.
"""
try:
extensions = context["cookiecutter"]["_extensions"]
extensions = context['cookiecutter']['_extensions']
except KeyError:
return []
else:
Expand All @@ -63,4 +66,7 @@ def __init__(self, **kwargs):
Also loading extensions defined in cookiecutter.json's _extensions key.
"""
super(StrictEnvironment, self).__init__(undefined=StrictUndefined, **kwargs)
super(StrictEnvironment, self).__init__(
undefined=StrictUndefined,
**kwargs
)
2 changes: 0 additions & 2 deletions cookiecutter/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ class UnknownTemplateDirException(CookiecutterException):
Raised when Cookiecutter cannot determine which directory is the project
template, e.g. more than one dir appears to be a template dir.
"""

# unused locally


Expand All @@ -38,7 +37,6 @@ class MissingProjectDir(CookiecutterException):
Raised during cleanup when remove_repo() can't find a generated project
directory inside of a repo.
"""

# unused locally


Expand Down
4 changes: 1 addition & 3 deletions cookiecutter/extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

import json
import string

try:
# Python 3.6 and above
from secrets import choice
Expand All @@ -24,7 +23,7 @@ def __init__(self, environment):
def jsonify(obj):
return json.dumps(obj, sort_keys=True, indent=4)

environment.filters["jsonify"] = jsonify
environment.filters['jsonify'] = jsonify


class RandomStringExtension(Extension):
Expand All @@ -40,5 +39,4 @@ def random_ascii_string(length, punctuation=False):
else:
corpus = string.ascii_letters
return "".join(choice(corpus) for _ in range(length))

environment.globals.update(random_ascii_string=random_ascii_string)
8 changes: 5 additions & 3 deletions cookiecutter/find.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,21 @@ def find_template(repo_dir):
:param repo_dir: Local directory of newly cloned repo.
:returns project_template: Relative path to project template.
"""
logger.debug("Searching {} for the project template.".format(repo_dir))
logger.debug('Searching {} for the project template.'.format(repo_dir))

repo_dir_contents = os.listdir(repo_dir)

project_template = None
for item in repo_dir_contents:
if "cookiecutter" in item and "{{" in item and "}}" in item:
if 'cookiecutter' in item and '{{' in item and '}}' in item:
project_template = item
break

if project_template:
project_template = os.path.join(repo_dir, project_template)
logger.debug("The project template appears to be {}".format(project_template))
logger.debug(
'The project template appears to be {}'.format(project_template)
)
return project_template
else:
raise NonTemplatedInputDirException
Loading

0 comments on commit 15f6f53

Please sign in to comment.