/usr/share/pyshared/cubictemp.py is in python-cubictemp 2.0-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 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 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 | # Copyright (c) 2003-2008, Nullcube Pty Ltd All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
import cgi, re, itertools
class TemplateError(Exception):
"""
Template evaluation exception class.
"""
# Character offset within the raw template at which the error occurred
pos = None
# Template object
template = None
# Line number
lineNo = None
# Error context length
contextLen = 2
def __init__(self, message, pos, template):
Exception.__init__(self, message)
self.pos, self.template = pos, template
self.lineNo, self._contextStr = self._getLines(template.txt, pos)
def _getLines(self, txt, pos):
lines = txt.splitlines(True)
cur = 0
for i, l in enumerate(lines):
cur += len(l)
if cur > pos:
break
if i < self.contextLen:
startc = 0
else:
startc = i - self.contextLen
if i + self.contextLen > len(lines):
endc = len(lines)
else:
endc = i + self.contextLen + 1
marker = "%s\n"%("^"*len(lines[i].rstrip()))
_contextStr = lines[startc:i+1] + [marker] + lines[i+1:endc]
_contextStr = [" " + l.rstrip() for l in _contextStr]
_contextStr = "\n".join(_contextStr)
return i + 1, _contextStr
def __str__(self):
ret = [
"%s"%self.message,
"\tContext: line %s in %s:"%(self.lineNo, self.template.name),
]
ret.append(self._contextStr)
return "\n".join(ret)
def escape(s):
"""
Replace special characters '&', '<', '>', ''', and '"' with the
appropriate HTML escape sequences.
"""
s = s.replace("&", "&") # Must be done first!
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace('"', """)
s = s.replace("'", "'")
return s
class _Processor:
def __init__(self):
self.funcs = []
def __or__(self, other):
self.funcs.append(other)
return self
def __call__(self, s):
for i in self.funcs:
s = i(s)
return s
class _Text:
def __init__(self, txt):
self.txt = txt
def __call__(self, **ns):
return self.txt
class _Eval:
def _compile(self, expr, pos, tmpl):
try:
return compile(expr, "<string>", "eval")
except SyntaxError, value:
s = 'Invalid expression: "%s"'%(expr)
raise TemplateError(s, pos, tmpl)
def _eval(self, e, ns):
try:
return eval(e, {}, ns)
except NameError, value:
s = 'NameError: "%s"'%value
raise TemplateError(s, self.pos, self.tmpl)
class _Expression(_Eval):
def __init__(self, expr, flavor, pos, tmpl, ns):
self.expr, self.flavor = expr, flavor
self.pos, self.tmpl = pos, tmpl
self.ns = ns
self._ecache = self._compile(expr, pos, tmpl)
def __call__(self, **ns):
ns.update(self.ns)
ret = self._eval(self._ecache, ns)
if isinstance(ret, _Block):
ret = ret(**ns)
if self.flavor == "@":
if not getattr(ret, "_cubictemp_unescaped", 0):
return escape(str(ret))
return str(ret)
class _Block(list, _Eval):
def __init__(self, processor, pos, tmpl, ns):
self.ns, self.processor = ns, processor
self.pos, self.tmpl = pos, tmpl
if processor:
self._ecache = self._compile(
"_cubictemp_processor | " + processor, pos, tmpl
)
def __call__(self, **ns):
r = "".join([i(**ns) for i in self])
if self.processor:
ns["_cubictemp_processor"] = _Processor()
proc = self._eval(self._ecache, ns)
return proc(r)
else:
return r
class _Iterable(list, _Eval):
def __init__(self, iterable, varname, pos, tmpl, ns):
self.iterable, self.varname = iterable, varname
self.pos, self.tmpl = pos, tmpl
self.ns = ns
self._ecache = self._compile(iterable, pos, tmpl)
def __call__(self, **ns):
loopIter = self._eval(self._ecache, ns)
try:
loopIter = iter(loopIter)
except TypeError:
s = "Can not iterate over %s"%self.iterable
raise TemplateError(s, self.pos, self.tmpl)
s = []
for i in loopIter:
ns[self.varname] = i
s.append("".join([i(**ns) for i in self]))
return "".join(s)
class Template:
_cubictemp_unescaped = 1
_bStart = r"""
# Two kinds of tags: named blocks and for loops
(^[ \t]*<!--\(\s*
(
for\s+(?P<varName>\w+)\s+in\s+(?P<iterable>.+)
| block(\s+(?P<blockName>\w+))? \s* (\|\s*(?P<processor>.+))?
)
\s*\)(-->)?[ \t\r\f\v]*?\n) |
# The end of a tag
(?P<end>^[ \t]*(<!--)?\(\s*end\s*\)-->[ \t\r\f\v]*\n) |
# An expression
((?P<flavor>@|\$)!(?P<expr>.+?)!(?P=flavor))
"""
_reParts = re.compile(_bStart, re.X|re.M)
# Name by which this template is referred to in exceptions.
name = "<string>"
def __init__(self, txt, **nsDict):
"""
:txt Template body
:nsDict Namespace dictionary
"""
self.nsDict, self.txt = nsDict, txt
matches = self._reParts.finditer(txt)
pos = 0
self.block = _Block(None, pos, self, {})
stack = [self.block]
for m in matches:
parent = stack[-1]
if m.start() > pos:
parent.append(_Text(txt[pos:m.start()]))
pos = m.end()
g = m.groupdict()
if g["blockName"]:
b = _Block(g["processor"], pos, self, parent.ns.copy())
parent.ns[g["blockName"]] = b
stack.append(b)
if g["processor"]:
b = _Block(g["processor"], pos, self, parent.ns.copy())
stack.append(b)
parent.append(b)
elif g["iterable"]:
b = _Iterable(
g["iterable"],
g["varName"],
pos,
self,
parent.ns.copy()
)
parent.append(b)
stack.append(b)
elif g["end"]:
stack.pop()
if not stack:
raise TemplateError("Unbalanced block.", pos, self)
elif g["expr"]:
e = _Expression(g["expr"], g["flavor"], pos, self, parent.ns.copy())
parent.append(e)
if pos < len(txt):
stack[-1].append(_Text(txt[pos:]))
def __str__(self):
"""
Evaluate the template in the namespace provided at instantiation.
"""
return self()
def __call__(self, **override):
"""
:override A set of key/value pairs.
Evaluate the template, over-riding the instantiation namespace with
the specified key/value pairs. Returns a string.
"""
ns = self.nsDict.copy()
ns.update(override)
return self.block(**ns)
class File(Template):
"""
Convenience class that extends Template to provide easy instantiation
from a file.
"""
def __init__(self, filename, **nsDict):
"""
:filename Full Path to file containing template body.
:nsDict Instantiation namespace dictionary.
"""
self.name = filename
data = open(filename).read()
Template.__init__(self, data, **nsDict)
|