Completed
Pull Request — master (#946)
by
unknown
01:28
created

ExtensionLoaderMixin._read_extensions()   A

Complexity

Conditions 4

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
dl 0
loc 12
rs 9.2
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
2
3
"""Jinja2 environment and extensions loading."""
4
5
from jinja2 import Environment, StrictUndefined
6
7
from .exceptions import UnknownExtension
8
9
10
class ExtensionLoaderMixin(object):
11
    """Mixin providing sane loading of extensions specified in a given context.
12
13
    The context is being extracted from the keyword arguments before calling
14
    the next parent class in line of the child.
15
    """
16
    default_extensions = [
17
        'cookiecutter.extensions.JsonifyExtension',
18
        'jinja2_time.TimeExtension',
19
    ]
20
21
    def __init__(self, **kwargs):
22
        """Initialize the Jinja2 Environment object while loading extensions.
23
24
        Does the following:
25
26
        1. Establishes default_extensions (currently just a Time feature)
27
        2. Reads extensions set in the cookiecutter.json _extensions key.
28
        3. Attempts to load the extensions. Provides useful error if fails.
29
        """
30
        kwargs.setdefault('extensions', [])
31
        kwargs['extensions'] += self.default_extensions
32
33
        context = kwargs.pop('context', {}).get('cookiecutter')
34
        if context:
35
            extensions = context.get('_extensions')
36
            if extensions:
37
                kwargs['extensions'] += extensions
38
            environment = context.get('_environment')
39
            if environment:
40
                kwargs.update(**environment)
41
42
        try:
43
            super(ExtensionLoaderMixin, self).__init__(**kwargs)
44
        except ImportError as err:
45
            raise UnknownExtension('Unable to load extension: {}'.format(err))
46
47
48
class StrictEnvironment(ExtensionLoaderMixin, Environment):
49
    """Create strict Jinja2 environment.
50
51
    Jinja2 environment will raise error on undefined variable in template-
52
    rendering context.
53
    """
54
55
    def __init__(self, **kwargs):
56
        """Set the standard Cookiecutter StrictEnvironment.
57
58
        Also loading extensions defined in cookiecutter.json's _extensions key.
59
        """
60
        super(StrictEnvironment, self).__init__(
61
            undefined=StrictUndefined,
62
            **kwargs
63
        )
64