-
Notifications
You must be signed in to change notification settings - Fork 10
/
transformer.py
328 lines (288 loc) · 13.4 KB
/
transformer.py
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from tempfile import mkdtemp
import os
import shutil
import re
from lxml import etree
from lxml.etree import XSLT
from ferenda import errors, util
from ferenda import ResourceLoader
# assumption: A transformer is initialized with a single template. If
# you want to use a different template, create a different
# transformer.
class Transformer(object):
"""Transforms parsed "pure content" documents into "browser-ready"
HTML5 files with site branding and navigation, using a template of
some kind.
:param transformertype: The engine to be used for transforming. Right now only ``"XSLT"`` is supported.
:type transformertype: str
:param resourceloader: The :py:class:`~ferenda.ResourceLoader` instance used to find template files.
:type template: ferenda.ResourceLoader
:param template: The name of the main template file.
:type template: str
:param templatedir: Directory for supporting templates to the main template.
:type templatedir: str
:param documentroot: The base directory for all generated files -- used to make relative references to CSS/JS files correct.
:type documentroot: str
:param config: Any configuration information used by the
transforming engine. Can be a path to a config
file, a python data structure, or anything else
compatible with the engine selected by
``transformertype``.
.. note::
An initialized Transformer object only transforms using the
template file provided at initialization. If you need to use
another template file, create another Transformer object.
"""
def __init__(self,
transformertype,
template,
templatedir, # within the resourceloader
resourceloader=None,
documentroot=None,
config=None):
cls = {'XSLT': XSLTTransform,
'JINJA': JinjaTransform}[transformertype]
if not resourceloader:
resourceloader = ResourceLoader()
self.resourceloader = resourceloader
self.t = cls(template, templatedir, self.resourceloader)
self.documentroot = documentroot
self.config = config
# valid parameters
# - annotationfile: intermediate/basefile.grit.xml
def transform(self, indata, depth, parameters=None, uritransform=None):
"""Perform the transformation. This method always operates on the
"native" datastructure -- this might be different depending on
the transformer engine. For XSLT, which is implemented through
lxml, its in- and outdata are lxml trees
If you need an engine-indepent API, use
:meth:`~ferenda.Transformer.transform_stream` or
:meth:`~ferenda.Transformer.transform_file` instead
:param indata: The document to be transformed
:param depth: The directory nesting level, compared to ``documentroot``
:type depth: int
:param parameters: Any parameters that should be provided to the
template
:type parameters: dict
:param uritransform: A function, when called with an URI,
returns a transformed URI/URL (such as
the relative path to a static file) --
used when transforming to files used for
static offline use.
:type uritransform: callable
:returns: The transformed document
"""
if parameters is None:
parameters = {}
# the provided configuration (might be a file or a python dict
# or anything else, depending on the transformer engine) will
# contain lists of JS/CSS resources. In order to make it
# possible to use relative links to these (needed for offline
# static HTML files), we first do a transformer
# engine-specific adaption of the configuration depending on
# the directory depth level of the outfile (as provided
# through the depth parameter), then we provide this adapted
# configuration to the transform call
if self.config:
adapted_config = self.t.getconfig(self.config, depth)
else:
adapted_config = None
outdata = self.t.transform(indata, adapted_config, parameters)
if uritransform:
self._transform_links(outdata.getroot(), uritransform)
return outdata
def _transform_links(self, tree, uritransform):
for part in tree:
# depth-first transformation seems the easiest
self._transform_links(part, uritransform)
if part.tag != "a":
continue
uri = part.get("href")
if not uri:
continue
part.set("href", uritransform(uri))
def transform_stream(self, instream, depth,
parameters=None, uritransform=None):
"""Accepts a file-like object, returns a file-like object."""
return self.t.native_to_stream(
self.transform(self.t.stream_to_native(instream),
depth,
parameters,
uritransform))
def transform_file(self, infile, outfile,
parameters=None, uritransform=None):
"""Accepts two filenames, reads from *infile*, writes to *outfile*."""
depth = self._depth(os.path.dirname(outfile),
self.documentroot + os.sep + "index.html")
helpful = os.environ.get('FERENDA_TRANSFORMDEBUG', False)
if helpful:
import logging
log = logging.getLogger("ferenda.transformer")
if self.config:
xslfile = self.resourceloader.filename(self.t.orig_template)
p = parameters.copy()
for key, value in p.items():
if key.endswith("file"):
p[key] = os.path.relpath(value,
os.path.dirname(xslfile))
p['configurationfile'] = self.t.getconfig(self.config, depth)
log.debug("Equiv: xsltproc --nonet %s %s %s > %s" %
(" ".join(['--stringparam %s "%s"' % (x, p[x]) for x in p]),
os.path.relpath(xslfile,
os.getcwd()),
infile, outfile))
else:
log.warning(
"self.config not set, cannot construct equivalent xsltproc command line")
self.t.native_to_file(self.transform(self.t.file_to_native(infile),
depth,
parameters,
uritransform),
outfile)
def _depth(self, outfiledir, root):
# NB: root must be a file in the root dir
return os.path.relpath(root, outfiledir).count("..")
class TransformerEngine(object):
def __init__(self, template, templatedir):
pass
class XSLTTransform(TransformerEngine):
def __init__(self, template, templatedir, resourceloader, **kwargs):
self.orig_template = template
self.orig_templatedir = templatedir # ?
self.format = True # FIXME: make configurable
self.resourceloader = resourceloader
self.templdir = self._setup_templates(template, templatedir)
# worktemplate = self.templdir + os.sep + template
worktemplate = self.templdir + os.sep + os.path.basename(template)
assert os.path.exists(worktemplate)
parser = etree.XMLParser(remove_blank_text=self.format)
xsltree = etree.parse(worktemplate, parser)
try:
self._transformer = etree.XSLT(xsltree)
except etree.XSLTParseError as e:
raise errors.TransformError(str(e.error_log))
def __del__(self):
if os.path.exists(self.templdir):
# this had better be a tempdir!
shutil.rmtree(self.templdir)
# purpose: get all XSLT files (main and supporting) into one place
# (should support zipped eggs, even if setup.py don't)
# template: full path to actual template to be used
# templatedir: directory of supporting XSLT templates
# returns: directory name of the place where all files ended up
def _setup_templates(self, template, templatedir):
workdir = mkdtemp()
self.resourceloader.extractdir(templatedir, workdir, (".xsl", ".xslt"))
if os.path.basename(template) not in os.listdir(workdir):
shutil.copy2(template, workdir)
return workdir
# getconfig may return different data depending on engine -- in
# this case it creates a xml file and returns the path for it
def getconfig(self, configfile, depth):
filename = configfile
if depth != 0:
(base, ext) = os.path.splitext(configfile)
filename = "%(base)s-depth-%(depth)d%(ext)s" % locals()
if not util.outfile_is_newer([configfile], filename):
tree = etree.parse(configfile)
# adjust the relevant link attribute for some nodes
for xpath, attrib in (("stylesheets/link", "href"),
("javascripts/script", "src"),
(".//img", "src")):
for node in tree.findall(xpath):
# don't adjust absolute links
if not (re.match("(https?://|/)", node.get(attrib))):
node.set(attrib, "../" * depth + node.get(attrib))
tree.write(filename)
return filename
def transform(self, indata, config=None, parameters={}):
strparams = {}
if config:
# paths to be used with the document() function
# must use unix path separators
if os.sep == "\\":
config = config.replace(os.sep, "/")
# print("Tranform: Using config %s. Contents:" % config)
# print(util.readfile(config))
config_fullpath = os.path.abspath(config)
strparams['configurationfile'] = XSLT.strparam(config_fullpath)
for key, value in parameters.items():
if key.endswith("file"):
# relativize path of file relative to the XSL file
# we'll be using. The mechanism could be clearer...
value = os.path.relpath(value, self.templdir)
if os.sep == "\\":
value = value.replace(os.sep, "/")
strparams[key] = XSLT.strparam(value)
try:
return self._transformer(indata, **strparams)
except etree.XSLTApplyError as e:
raise errors.TransformError(str(e))
if len(self._transformer.error_log) > 0:
raise errors.TransformError(str(_transformer.error_log))
# nativedata = lxml.etree
def native_to_file(self, nativedata, outfile):
res = self.html5_doctype_workaround(
etree.tostring(nativedata, pretty_print=self.format))
util.ensure_dir(outfile)
with open(outfile, "wb") as fp:
fp.write(res)
@staticmethod
def html5_doctype_workaround(indata):
# FIXME: This is horrible
if indata.startswith(b"<remove-this-tag>"):
found = False
endidx = -1
while not found:
if indata[endidx] == b"<" or indata[endidx] == 60:
found = True
else:
endidx -= 1
indata = b"<!DOCTYPE html>\n" + indata[17:endidx].strip()
return indata
def file_to_native(self, infile):
return etree.parse(infile)
# FIXME: hook in the transform_links step somehow?
class JinjaTransform(TransformerEngine):
pass
# client code
#
# doc.body = elements.Body()
# for r in res:
# doc.body.append(html.Div(
# [html.H2([elements.Link(r['title'], uri=r['uri'])]),
# r['text']], **{'class':'hit'}))
# pages = [html.P(["Results %(firstresult)s-%(lastresult)s of %(totalresults)s" % pager])]
# for pagenum in range(pager['pagecount']):
# if pagenum + 1 == pager['pagenum']:
# pages.append(html.Span([str(pagenum+1)],**{'class':'page'}))
# else:
# querystring['p'] = str(pagenum+1)
# url = environ['PATH_INFO'] + "?" + urlencode(querystring)
# pages.append(html.A([str(pagenum+1)],**{'class':'page',
# 'href':url}))
# doc.body.append(html.Div(pages, **{'class':'pager'}))
#
# transformer = TemplateTransformer(transformertype="XSLT",
# template="res/xsl/generic.xsl",
# templatedir=["res/xsl"],
# documentroot="/var/www/site")
#
# newtree = transformer.transform_tree(doc.body.as_xhtml(),
# reldepth=1)
# fp.write(etree.tostring(newtree, pretty_print=True))
#
# -- or --
#
#
# util.writefile("indata.xhtml", doc.body.as_xhtml().serialize())
# transformer.transform("indata.xhtml", "/var/www/site/my/own/file.html")
#
# references to root resources in file.html are now on the form
# "../../css/main.css", since file.html is 2 levels deep compared to
# documentroot.
#