jinja2_template.py 7.49 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
##############################################################################
#
# Copyright (c) 2012 Vifib SARL and Contributors. All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################
27
import errno
28 29 30
import os
import json
import zc.buildout
31 32
from jinja2 import Environment, StrictUndefined, \
    BaseLoader, TemplateNotFound, PrefixLoader
33 34
from contextlib import contextmanager

35 36
_buildout_safe_dumps = getattr(zc.buildout.buildout, 'dumps', None)
DUMPS_KEY = 'dumps'
37
DEFAULT_IMPORT_DELIMITER = '/'
38

39 40
@contextmanager
def umask(mask):
41 42 43
    if mask is None:
        yield
        return
44 45 46 47 48 49
    original = os.umask(mask)
    try:
        yield original
    finally:
        os.umask(original)

Vincent Pelletier's avatar
Vincent Pelletier committed
50
def getKey(expression, buildout, _, options):
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
    section, entry = expression.split(':')
    if section:
        return buildout[section][entry]
    else:
        return options[entry]

def getJsonKey(expression, buildout, _, __):
    return json.loads(getKey(expression, buildout, _, __))

EXPRESSION_HANDLER = {
    'raw': (lambda expression, _, __, ___: expression),
    'key': getKey,
    'json': (lambda expression, _, __, ___: json.loads(expression)),
    'jsonkey': getJsonKey,
    'import': (lambda expression, _, __, ___: __import__(expression)),
Vincent Pelletier's avatar
Vincent Pelletier committed
66 67
    'section': (lambda expression, buildout, _, __: dict(
        buildout[expression])),
68 69
}

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
class RelaxedPrefixLoader(PrefixLoader):
    """
    Same as PrefixLoader, but accepts imports lacking separator.
    """
    def get_source(self, environment, template):
        if self.delimiter not in template:
            template += self.delimiter
        return super(RelaxedPrefixLoader, self).get_source(environment,
            template)

class RecipeBaseLoader(BaseLoader):
    """
    Base class for import classes altering import path.
    """
    def __init__(self, path, delimiter):
        self.base = os.path.normpath(path)
        self.delimiter = delimiter

    def get_source(self, environment, template):
        path = self._getPath(template)
        # Code adapted from jinja2's doc on BaseLoader.
        if path is None or not os.path.exists(path):
            raise TemplateNotFound(template)
        mtime = os.path.getmtime(path)
        with file(path) as f:
            source = f.read().decode('utf-8')
        return source, path, lambda: mtime == os.path.getmtime(path)

    def _getPath(self, template):
        raise NotImplementedError

class FileLoader(RecipeBaseLoader):
    """
    Single-path loader.
    """
    def _getPath(self, template):
        if template:
            return None
        return self.base

class FolderLoader(RecipeBaseLoader):
    """
    Multi-path loader (to allow importing a folder's content).
    """
    def _getPath(self, template):
        path = os.path.normpath(os.path.join(
            self.base,
            *template.split(self.delimiter)
        ))
        if path.startswith(self.base):
            return path
        return None

LOADER_TYPE_DICT = {
    'rawfile': (FileLoader, EXPRESSION_HANDLER['raw']),
    'file': (FileLoader, getKey),
    'rawfolder': (FolderLoader, EXPRESSION_HANDLER['raw']),
    'folder': (FolderLoader, getKey),
}

130
class Recipe(object):
131
    mode = 0777 # BBB: 0666 may have been a better default value
132
    loader = None
133
    umask = None
134

135 136 137 138 139 140 141 142
    def __init__(self, buildout, name, options):
        self.template = zc.buildout.download.Download(
                buildout['buildout'],
                hash_name=True,
            )(
                options['template'],
                md5sum=options.get('md5sum'),
            )[0]
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
        import_delimiter = options.get('import-delimiter',
            DEFAULT_IMPORT_DELIMITER)
        import_dict = {}
        for line in options.get('import-list', '').splitlines(False):
            if not line:
                continue
            expression_type, alias, expression = line.split(None, 2)
            if alias in import_dict:
                raise ValueError('Duplicate import-list entry %r' % alias)
            loader_type, expression_handler = LOADER_TYPE_DICT[
                expression_type]
            import_dict[alias] = loader_type(
                expression_handler(expression, buildout, name, options),
                import_delimiter,
            )
        if import_dict:
            self.loader = RelaxedPrefixLoader(import_dict,
                delimiter=import_delimiter)
161
        self.rendered = options['rendered']
Vincent Pelletier's avatar
Vincent Pelletier committed
162 163
        self.extension_list = [x for x in (y.strip()
            for y in options.get('extensions', '').split()) if x]
164
        self.context = context = {}
165 166
        if _buildout_safe_dumps is not None:
            context[DUMPS_KEY] = _buildout_safe_dumps
167
        for line in options.get('context', '').splitlines(False):
168 169 170 171 172 173 174 175
            if not line:
                continue
            expression_type, variable_name, expression = line.split(None, 2)
            if variable_name in context:
                raise ValueError('Duplicate context entry %r' % (
                    variable_name, ))
            context[variable_name] = EXPRESSION_HANDLER[expression_type](
                expression, buildout, name, options)
176 177 178 179
        mode = options.get('mode')
        if mode:
            self.mode = int(mode, 8)
        # umask is deprecated, but kept for backward compatibility
180 181 182
        umask_value = options.get('umask')
        if umask_value:
            self.umask = int(umask_value, 8)
183 184

    def install(self):
185 186
        # Unlink any existing file, so umask is always applied.
        try:
187
            os.unlink(self.rendered)
188 189 190
        except OSError, e:
            if e.errno != errno.ENOENT:
                raise
191 192 193 194
        with umask(self.umask):
            outdir = os.path.dirname(self.rendered)
            if outdir and not os.path.exists(outdir):
                os.makedirs(outdir)
195 196
            # XXX: open doesn't allow providing a filesystem mode, so use
            # os.open and os.fdopen instead.
197 198 199
            with os.fdopen(os.open(self.rendered,
                  os.O_CREAT | os.O_EXCL | os.O_WRONLY,
                  self.mode), 'w') as out:
200 201
                out.write(
                    Environment(
202 203
                        extensions=self.extension_list,
                        undefined=StrictUndefined,
204 205 206
                        loader=self.loader,
                    ).from_string(
                        open(self.template).read(),
207 208 209 210 211 212 213 214
                    ).render(
                        **self.context
                    )
                )
        return self.rendered

    update = install