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

cookiecutter.get_user_config_path()   A

Complexity

Conditions 1

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 2
rs 10
cc 1
1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
4
"""
5
cookiecutter.config
6
-------------------
7
8
Global configuration handling
9
"""
10
11
from __future__ import unicode_literals
12
13
import copy
14
import io
15
import logging
16
17
import os
18
19
try:
20
    import ruamel.yaml as yaml
21
except ImportError:
22
    import yaml
23
24
from .exceptions import ConfigDoesNotExistException
25
from .exceptions import InvalidConfiguration
26
27
logger = logging.getLogger(__name__)
28
29
30
def get_user_config_path():
31
    return os.path.expanduser('~/.cookiecutterrc')
32
33
34
def get_default_config():
35
    return copy.copy({
36
        'cookiecutters_dir': os.path.expanduser('~/.cookiecutters/'),
37
        'replay_dir': os.path.expanduser('~/.cookiecutter_replay/'),
38
        'default_context': {}
39
    })
40
41
42
def get_config(config_path):
43
    """
44
    Retrieve the config from the specified path, returning it as a config dict.
45
    """
46
47
    if not os.path.exists(config_path):
48
        raise ConfigDoesNotExistException
49
50
    logger.debug('config_path is {0}'.format(config_path))
51
    with io.open(config_path, encoding='utf-8') as file_handle:
52
        try:
53
            yaml_dict = yaml.safe_load(file_handle)
54
        except yaml.scanner.ScannerError as e:
55
            raise InvalidConfiguration(
56
                '{0} is not a valid YAML file: line {1}: {2}'.format(
57
                    config_path,
58
                    e.problem_mark.line,
59
                    e.problem))
60
61
    config_dict = get_default_config()
62
    config_dict.update(yaml_dict)
63
64
    return config_dict
65
66
67
def get_user_config(config_file=None):
68
    """Retrieve the config from a file or return the defaults if None is
69
    passed. If an environment variable `COOKIECUTTER_CONFIG` is set up, try
70
    to load its value. Otherwise fall back to a default file or config.
71
    """
72
    if config_file is None:
73
        config_file = get_user_config_path()
74
75
    default_config = get_default_config()
76
    user_config_path = get_user_config_path()
77
78
    # Load the given config file
79
    if config_file and config_file != user_config_path:
80
        return get_config(config_file)
81
82
    try:
83
        # Does the user set up a config environment variable?
84
        env_config_file = os.environ['COOKIECUTTER_CONFIG']
85
    except KeyError:
86
        # Load an optional user config if it exists
87
        # otherwise return the defaults
88
        if os.path.exists(user_config_path):
89
            return get_config(user_config_path)
90
        else:
91
            return default_config
92
    else:
93
        # There is a config environment variable. Try to load it.
94
        # Do not check for existence, so invalid file paths raise an error.
95
        return get_config(env_config_file)
96