Completed
Pull Request — master (#617)
by
unknown
01:00
created

cookiecutter.ExtensionLoaderMixin   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 29
Duplicated Lines 0 %
Metric Value
dl 0
loc 29
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __init__() 0 10 2
A _read_extensions() 0 11 4
1
# -*- coding: utf-8 -*-
2
3
from jinja2 import Environment, StrictUndefined
4
5
from .exceptions import UnknownExtension
6
7
8
class ExtensionLoaderMixin(object):
9
    """Mixin that provides a sane way of loading extensions specified in a
10
    given context.
11
12
    The context is being extracted from the keyword arguments before calling
13
    the next parent class in line of the child.
14
    """
15
    def __init__(self, **kwargs):
16
        context = kwargs.pop('context', {})
17
18
        try:
19
            super(ExtensionLoaderMixin, self).__init__(
20
                extensions=self._read_extensions(context),
21
                **kwargs
22
            )
23
        except ImportError as err:
24
            raise UnknownExtension('Unable to load extension: {}'.format(err))
25
26
    def _read_extensions(self, context):
27
        """Return a list of extensions as str to be passed on to the jinja2
28
        env. If context does not contain the relevant info, return an empty
29
        list instead.
30
        """
31
        try:
32
            extensions = context['cookiecutter']['_extensions']
33
        except KeyError:
34
            return []
35
        else:
36
            return [str(ext) for ext in extensions]
37
38
39
class StrictEnvironment(ExtensionLoaderMixin, Environment):
40
    """Jinja2 environment that raises an error when it hits a variable
41
    which is not defined in the context used to render a template.
42
    """
43
    def __init__(self, **kwargs):
44
        super(StrictEnvironment, self).__init__(
45
            undefined=StrictUndefined,
46
            **kwargs
47
        )
48