|
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
|
|
|
|
|
17
|
|
|
def __init__(self, **kwargs): |
|
18
|
|
|
"""Initialize the Jinja2 Environment object while loading extensions. |
|
19
|
|
|
|
|
20
|
|
|
Does the following: |
|
21
|
|
|
|
|
22
|
|
|
1. Establishes default_extensions (currently just a Time feature) |
|
23
|
|
|
2. Reads extensions set in the cookiecutter.json _extensions key. |
|
24
|
|
|
3. Attempts to load the extensions. Provides useful error if fails. |
|
25
|
|
|
""" |
|
26
|
|
|
context = kwargs.pop('context', {}) |
|
27
|
|
|
|
|
28
|
|
|
default_extensions = [ |
|
29
|
|
|
'cookiecutter.extensions.JsonifyExtension', |
|
30
|
|
|
'jinja2_time.TimeExtension', |
|
31
|
|
|
] |
|
32
|
|
|
extensions = default_extensions + self._read_extensions(context) |
|
33
|
|
|
|
|
34
|
|
|
try: |
|
35
|
|
|
super(ExtensionLoaderMixin, self).__init__( |
|
36
|
|
|
extensions=extensions, |
|
37
|
|
|
**kwargs |
|
38
|
|
|
) |
|
39
|
|
|
except ImportError as err: |
|
40
|
|
|
raise UnknownExtension('Unable to load extension: {}'.format(err)) |
|
41
|
|
|
|
|
42
|
|
|
def _read_extensions(self, context): |
|
43
|
|
|
"""Return list of extensions as str to be passed on to the Jinja2 env. |
|
44
|
|
|
|
|
45
|
|
|
If context does not contain the relevant info, return an empty |
|
46
|
|
|
list instead. |
|
47
|
|
|
""" |
|
48
|
|
|
try: |
|
49
|
|
|
extensions = context['cookiecutter']['_extensions'] |
|
50
|
|
|
except KeyError: |
|
51
|
|
|
return [] |
|
52
|
|
|
else: |
|
53
|
|
|
return [str(ext) for ext in extensions] |
|
54
|
|
|
|
|
55
|
|
|
|
|
56
|
|
|
class StrictEnvironment(ExtensionLoaderMixin, Environment): |
|
57
|
|
|
"""Create strict Jinja2 environment. |
|
58
|
|
|
|
|
59
|
|
|
Jinja2 environment will raise error on undefined variable in template- |
|
60
|
|
|
rendering context. |
|
61
|
|
|
""" |
|
62
|
|
|
|
|
63
|
|
|
def __init__(self, **kwargs): |
|
64
|
|
|
"""Set the standard Cookiecutter StrictEnvironment. |
|
65
|
|
|
|
|
66
|
|
|
Also loading extensions defined in cookiecutter.json's _extensions key. |
|
67
|
|
|
""" |
|
68
|
|
|
super(StrictEnvironment, self).__init__( |
|
69
|
|
|
undefined=StrictUndefined, |
|
70
|
|
|
**kwargs |
|
71
|
|
|
) |
|
72
|
|
|
|