16233
|
1 |
#!/usr/bin/env python
|
|
2 |
# -*- coding: Latin-1 -*-
|
|
3 |
|
16323
|
4 |
"""
|
|
5 |
(on available processing instructions, see the Functions class)
|
|
6 |
"""
|
|
7 |
|
16233
|
8 |
__author__ = 'Florian Haftmann, florian.haftmann@informatik.tu-muenchen.de'
|
|
9 |
__revision__ = '$Id$'
|
|
10 |
|
|
11 |
# generic imports
|
|
12 |
import sys
|
|
13 |
import os
|
|
14 |
from os import path
|
|
15 |
import posixpath
|
|
16 |
import codecs
|
|
17 |
import shlex
|
|
18 |
import optparse
|
|
19 |
import time
|
|
20 |
|
|
21 |
# xml imports
|
|
22 |
from xml.sax.saxutils import escape
|
|
23 |
from xml.sax.saxutils import quoteattr
|
|
24 |
from xml.sax import make_parser as makeParser
|
|
25 |
from xml.sax.handler import ContentHandler
|
|
26 |
from xml.sax.handler import EntityResolver
|
|
27 |
from xml.sax.xmlreader import AttributesImpl as Attributes
|
|
28 |
from xml.sax import SAXException
|
|
29 |
from xml.sax import SAXParseException
|
|
30 |
|
|
31 |
nbsp = unichr(160)
|
|
32 |
|
|
33 |
# global configuration
|
|
34 |
outputEncoding = 'UTF-8'
|
|
35 |
|
|
36 |
# implement your own functions for PIs here
|
|
37 |
class Functions:
|
|
38 |
|
|
39 |
def __init__(self, pc, valdict, modtime, encodingMeta):
|
|
40 |
|
|
41 |
self._pc = pc
|
|
42 |
self._valdict = valdict
|
|
43 |
self._modtime = modtime
|
|
44 |
self._encodingMeta = encodingMeta
|
|
45 |
|
16323
|
46 |
def value(self, handler, **args):
|
16233
|
47 |
|
16323
|
48 |
"""<?value key="..."?> - inserts a property value given on the command line"""
|
16233
|
49 |
|
|
50 |
value = self._valdict[args[u"key"]]
|
|
51 |
handler.characters(value)
|
|
52 |
|
|
53 |
def title(self, handler, **args):
|
|
54 |
|
16323
|
55 |
"""<?title?> - inserts the document's title as glimpsed from the <title> tag"""
|
|
56 |
|
16233
|
57 |
handler.characters(handler._title)
|
|
58 |
|
|
59 |
def contentType(self, handler, **args):
|
|
60 |
|
16323
|
61 |
"""<?contentType?> - inserts the document's content type/encoding"""
|
|
62 |
|
16233
|
63 |
encoding = self._encodingMeta or handler._encoding
|
|
64 |
attr = {
|
|
65 |
u"http-equiv": u"Content-Type",
|
|
66 |
u"content": u"text/html; charset=%s" % encoding
|
|
67 |
}
|
|
68 |
handler.startElement(u"meta", attr)
|
|
69 |
handler.endElement(u"meta")
|
|
70 |
|
|
71 |
def currentDate(self, handler, **args):
|
|
72 |
|
16323
|
73 |
"""<?currentDate?> - inserts the current date"""
|
|
74 |
|
16233
|
75 |
handler.characters(unicode(time.strftime('%Y-%m-%d %H:%M:%S')))
|
|
76 |
|
|
77 |
def modificationDate(self, handler, **args):
|
|
78 |
|
16323
|
79 |
"""<?modificationDate?> - inserts the modification date of this file"""
|
|
80 |
|
16233
|
81 |
handler.characters(unicode(time.strftime('%Y-%m-%d %H:%M:%S',
|
|
82 |
time.localtime(self._modtime))))
|
|
83 |
|
|
84 |
def relativeRoot(self, handler, **args):
|
|
85 |
|
16323
|
86 |
"""<?relativeRoot href="..."?> - inserts the relative path specified by href"""
|
|
87 |
|
16233
|
88 |
href = args[u"href"].encode("latin-1")
|
|
89 |
handler.characters(self._pc.relDstPathOf('//'+href))
|
|
90 |
|
|
91 |
def include(self, handler, **args):
|
|
92 |
|
16323
|
93 |
"""<?include file="..."?> - includes an XML file"""
|
|
94 |
|
16233
|
95 |
filename = args[u"file"].encode("latin-1")
|
|
96 |
filename = self._pc.absSrcPathOf(filename)
|
|
97 |
self._modtime = max(self._modtime, os.stat(filename).st_mtime)
|
|
98 |
istream = open(filename, "r")
|
|
99 |
parseWithER(istream, handler)
|
|
100 |
istream.close()
|
|
101 |
|
|
102 |
def navitem(self, handler, **args):
|
|
103 |
|
16323
|
104 |
"""<?navitem target="..." title="..."?> - inserts an item in a navigation list,
|
16324
|
105 |
targeting to <target> and entitled <title>"""
|
16323
|
106 |
|
16233
|
107 |
target = args[u"target"].encode("latin-1")
|
|
108 |
target = self._pc.relDstPathOf(target)
|
|
109 |
if self._pc.isSrc(target):
|
|
110 |
wrapTagname = u"strong"
|
|
111 |
else:
|
|
112 |
wrapTagname = u"span"
|
|
113 |
title = args[u"title"]
|
|
114 |
attr = {}
|
|
115 |
handler.startElement(u"li", attr)
|
|
116 |
handler.startElement(wrapTagname, {})
|
|
117 |
handler.startElement(u"a", {
|
|
118 |
u"href": unicode(target, 'latin-1')
|
|
119 |
})
|
|
120 |
handler.characters(title)
|
|
121 |
handler.endElement(u"a")
|
|
122 |
handler.endElement(wrapTagname)
|
|
123 |
handler.endElement(u"li")
|
|
124 |
|
16296
|
125 |
def downloadLink(self, handler, **args):
|
|
126 |
|
16324
|
127 |
"""<?downloadLink target="..." [title="..."]?> - inserts a link to a file
|
|
128 |
to download; if the title is omitted, it is the bare filename itself"""
|
|
129 |
|
16296
|
130 |
target = args[u"target"].encode("latin-1")
|
|
131 |
targetReal = self._pc.absDstPathOf(target)
|
|
132 |
title = args.get(u"title", unicode(posixpath.split(targetReal)[1], 'latin-1'))
|
|
133 |
size = os.stat(targetReal).st_size
|
|
134 |
handler.startElement(u"a", {
|
|
135 |
u"href": target
|
|
136 |
})
|
|
137 |
handler.characters(title)
|
|
138 |
handler.endElement(u"a")
|
|
139 |
|
16233
|
140 |
def downloadCells(self, handler, **args):
|
|
141 |
|
16324
|
142 |
"""<?downloadCells target="..." [title="..."]?> - like downloadLink, but
|
|
143 |
puts the link into a table cell and appends a table cell displaying the
|
|
144 |
size of the linked file"""
|
|
145 |
|
16233
|
146 |
target = args[u"target"].encode("latin-1")
|
|
147 |
targetReal = self._pc.absDstPathOf(target)
|
16296
|
148 |
title = args.get(u"title", unicode(posixpath.split(targetReal)[1], 'latin-1'))
|
16233
|
149 |
size = os.stat(targetReal).st_size
|
|
150 |
handler.startElement(u"td", {})
|
|
151 |
handler.startElement(u"a", {
|
|
152 |
u"href": target
|
|
153 |
})
|
|
154 |
handler.characters(title)
|
|
155 |
handler.endElement(u"a")
|
|
156 |
handler.endElement(u"td")
|
|
157 |
handler.startElement(u"td", {})
|
|
158 |
handler.characters(u"%i%sKB" % (size / 1024, unichr(160)))
|
|
159 |
handler.endElement(u"td")
|
|
160 |
|
16574
|
161 |
def mirror(self, handler, **args):
|
|
162 |
|
|
163 |
"""<?mirror prefix="..." title="..."?> - generates a mirror switch link,
|
|
164 |
where prefix denotes the base root url of the mirror location
|
|
165 |
and title the visible description"""
|
|
166 |
|
|
167 |
prefix = args[u"prefix"]
|
|
168 |
title = args[u"title"]
|
|
169 |
handler.startElement(u"a", {u"href": posixpath.join(prefix, self._pc.relLocOfThis())})
|
|
170 |
handler.characters(title)
|
|
171 |
handler.endElement(u"a")
|
|
172 |
|
16323
|
173 |
def getPc(self):
|
|
174 |
|
|
175 |
return self._pc
|
|
176 |
|
16233
|
177 |
# a notion of paths
|
|
178 |
class PathCalculator:
|
|
179 |
|
|
180 |
def __init__(self, srcLoc, srcRoot, dstRoot):
|
|
181 |
|
|
182 |
self._src = path.normpath(path.abspath(srcLoc))
|
16574
|
183 |
srcPath, self._srcName = path.split(self._src)
|
16233
|
184 |
self._srcRoot = path.normpath(path.abspath(srcRoot))
|
|
185 |
self._dstRoot = path.normpath(path.abspath(dstRoot))
|
|
186 |
self._relRoot = ""
|
|
187 |
relLocChain = []
|
|
188 |
diffRoot = srcPath
|
|
189 |
while diffRoot != self._srcRoot:
|
|
190 |
self._relRoot = path.join(self._relRoot, os.pardir)
|
|
191 |
diffRoot, chainPiece = path.split(diffRoot)
|
|
192 |
relLocChain.insert(0, chainPiece)
|
|
193 |
self._relRoot = self._relRoot and self._relRoot + '/'
|
|
194 |
self._relLoc = relLocChain and path.join(*relLocChain) or ""
|
|
195 |
|
|
196 |
def isSrc(self, loc):
|
|
197 |
|
|
198 |
return self.absSrcPathOf(loc) == self._src
|
|
199 |
|
|
200 |
def relRootPath(self):
|
|
201 |
|
|
202 |
return self._relRoot
|
|
203 |
|
|
204 |
def absSrcPathOf(self, loc):
|
|
205 |
|
|
206 |
if loc.startswith("//"):
|
|
207 |
return path.normpath(path.abspath(loc[2:]))
|
|
208 |
else:
|
|
209 |
return path.normpath(path.abspath(path.join(self._relLoc, loc)))
|
|
210 |
|
|
211 |
def absDstPathOf(self, loc):
|
|
212 |
|
|
213 |
if loc.startswith("//"):
|
|
214 |
return path.join(self._dstRoot, loc[2:])
|
|
215 |
else:
|
|
216 |
return path.join(self._dstRoot, self._relLoc, loc)
|
|
217 |
|
|
218 |
def relSrcPathOf(self, loc):
|
|
219 |
|
|
220 |
loc = self.absSrcPathOf(loc)
|
|
221 |
loc = self.stripCommonPrefix(loc, self._srcRoot)
|
|
222 |
loc = self.stripCommonPrefix(loc, self._relLoc)
|
|
223 |
return loc
|
|
224 |
|
|
225 |
def relDstPathOf(self, loc):
|
|
226 |
|
|
227 |
loc = self.absDstPathOf(loc)
|
|
228 |
loc = self.stripCommonPrefix(loc, self._dstRoot)
|
|
229 |
loc = self.stripCommonPrefix(loc, self._relLoc)
|
|
230 |
return loc
|
|
231 |
|
16574
|
232 |
def relLocOfThis(self):
|
|
233 |
|
|
234 |
return posixpath.join(self._relLoc, self._srcName)
|
|
235 |
|
16233
|
236 |
def stripCommonPrefix(self, loc, prefix):
|
|
237 |
|
|
238 |
common = self.commonPrefix((loc, prefix))
|
|
239 |
if common:
|
|
240 |
loc = loc[len(common):]
|
|
241 |
if loc and loc[0] == '/':
|
|
242 |
loc = loc[1:]
|
|
243 |
return loc
|
|
244 |
|
|
245 |
def commonPrefix(self, locs):
|
|
246 |
|
|
247 |
common = path.commonprefix(locs)
|
|
248 |
# commonprefix bugs
|
|
249 |
if [ loc for loc in locs if len(loc) != common ] and \
|
|
250 |
[ loc for loc in locs if len(common) < len(loc) and loc[len(common)] != path.sep ]:
|
|
251 |
common = path.split(common)[0]
|
|
252 |
if common and common[-1] == path.sep:
|
|
253 |
common = common[:-1]
|
|
254 |
|
|
255 |
return common or ""
|
|
256 |
|
|
257 |
# the XML transformer
|
|
258 |
class TransformerHandler(ContentHandler, EntityResolver):
|
|
259 |
|
16574
|
260 |
def __init__(self, out, encoding, dtd, func, spamprotect):
|
16233
|
261 |
|
|
262 |
ContentHandler.__init__(self)
|
|
263 |
#~ EntityResolver.__init__(self)
|
|
264 |
self._out = codecs.getwriter(encoding)(out)
|
|
265 |
self._ns_contexts = [{}] # contains uri -> prefix dicts
|
|
266 |
self._current_context = self._ns_contexts[-1]
|
|
267 |
self._undeclared_ns_maps = []
|
|
268 |
self._encoding = encoding
|
|
269 |
self._lastStart = False
|
|
270 |
self._func = func
|
16574
|
271 |
self._spamprotect = spamprotect
|
16233
|
272 |
self._characterBuffer = {}
|
|
273 |
self._currentXPath = []
|
|
274 |
self._title = None
|
|
275 |
self._init = False
|
|
276 |
self._dtd = dtd
|
|
277 |
|
|
278 |
def closeLastStart(self):
|
|
279 |
|
|
280 |
if self._lastStart:
|
|
281 |
self._out.write(u'>')
|
|
282 |
self._lastStart = False
|
|
283 |
|
|
284 |
def flushCharacterBuffer(self):
|
|
285 |
|
16574
|
286 |
self._out.write(escape(u"".join(self._characterBuffer)).replace(u"@", u"@"))
|
16233
|
287 |
self._characterBuffer = []
|
|
288 |
|
|
289 |
def transformAbsPath(self, attrs, attrname):
|
|
290 |
|
|
291 |
pathval = attrs.get(attrname, None)
|
|
292 |
if pathval and pathval.startswith(u"//"):
|
|
293 |
attrs = dict(attrs)
|
|
294 |
pathRel = self._func.getPc().relDstPathOf(pathval)
|
|
295 |
pathDst = self._func.getPc().absDstPathOf(pathval)
|
|
296 |
if not path.exists(pathDst):
|
|
297 |
raise Exception("Path does not exist: %s" % pathDst)
|
|
298 |
attrs[attrname] = pathRel
|
|
299 |
return attrs
|
|
300 |
else:
|
|
301 |
return attrs
|
|
302 |
|
|
303 |
def startDocument(self):
|
|
304 |
|
|
305 |
if not self._init:
|
|
306 |
if self._encoding.upper() != 'UTF-8':
|
|
307 |
self._out.write(u'<?xml version="1.0" encoding="%s"?>\n' %
|
|
308 |
self._encoding)
|
|
309 |
else:
|
|
310 |
self._out.write(u'<?xml version="1.0"?>\n')
|
|
311 |
self._init = True
|
|
312 |
|
|
313 |
def startPrefixMapping(self, prefix, uri):
|
|
314 |
|
|
315 |
self._ns_contexts.append(self._current_context.copy())
|
|
316 |
self._current_context[uri] = prefix
|
|
317 |
self._undeclared_ns_maps.append((prefix, uri))
|
|
318 |
|
|
319 |
def endPrefixMapping(self, prefix):
|
|
320 |
|
|
321 |
self._current_context = self._ns_contexts[-1]
|
|
322 |
del self._ns_contexts[-1]
|
|
323 |
|
|
324 |
def startElement(self, name, attrs):
|
|
325 |
|
|
326 |
if name == u"dummy:wrapper":
|
|
327 |
return
|
|
328 |
self.closeLastStart()
|
|
329 |
self.flushCharacterBuffer()
|
|
330 |
self._out.write(u'<' + name)
|
|
331 |
# this list is not exhaustive
|
|
332 |
for tagname, attrname in ((u"a", u"href"), (u"img", u"src"), (u"link", u"href")):
|
|
333 |
if name == tagname:
|
|
334 |
attrs = self.transformAbsPath(attrs, attrname)
|
16577
|
335 |
if self._spamprotect and name == u"a":
|
16574
|
336 |
value = attrs.get(u"href")
|
|
337 |
if value and value.startswith(u"mailto:"):
|
|
338 |
attrs = dict(attrs)
|
|
339 |
attrs[u"href"] = "".join([ ("&#%i;" % ord(c)) for c in value ])
|
|
340 |
for (key, value) in attrs.items():
|
|
341 |
self._out.write(u' %s=%s' % (key, quoteattr(value)))
|
16576
|
342 |
self._currentXPath.append(key)
|
16233
|
343 |
self._lastStart = True
|
|
344 |
|
|
345 |
def endElement(self, name):
|
|
346 |
|
|
347 |
if name == u"dummy:wrapper":
|
|
348 |
return
|
|
349 |
elif name == u'title':
|
|
350 |
self._title = u"".join(self._characterBuffer)
|
|
351 |
self.flushCharacterBuffer()
|
|
352 |
if self._lastStart:
|
|
353 |
self._out.write(u'/>')
|
|
354 |
self._lastStart = False
|
|
355 |
else:
|
|
356 |
self._out.write('</%s>' % name)
|
|
357 |
self._currentXPath.pop()
|
|
358 |
|
|
359 |
def startElementNS(self, name, qname, attrs):
|
|
360 |
|
|
361 |
self.closeLastStart()
|
|
362 |
self.flushCharacterBuffer()
|
|
363 |
if name[0] is None:
|
|
364 |
# if the name was not namespace-scoped, use the unqualified part
|
|
365 |
name = name[1]
|
|
366 |
else:
|
|
367 |
# else try to restore the original prefix from the namespace
|
|
368 |
name = self._current_context[name[0]] + u":" + name[1]
|
|
369 |
self._out.write(u'<' + name)
|
|
370 |
|
|
371 |
for pair in self._undeclared_ns_maps:
|
|
372 |
self._out.write(u' xmlns:%s="%s"' % pair)
|
|
373 |
self._undeclared_ns_maps = []
|
|
374 |
|
|
375 |
for (name, value) in attrs.items():
|
|
376 |
name = self._current_context[name[0]] + ":" + name[1]
|
|
377 |
self._out.write(' %s=%s' % (name, quoteattr(value)))
|
|
378 |
self._out.write('>')
|
|
379 |
self._currentXPath.append(name)
|
|
380 |
|
|
381 |
def endElementNS(self, name, qname):
|
|
382 |
|
|
383 |
self.flushCharacterBuffer()
|
|
384 |
if name[0] is None:
|
|
385 |
name = name[1]
|
|
386 |
else:
|
|
387 |
name = self._current_context[name[0]] + u":" + name[1]
|
|
388 |
if self._lastStart:
|
|
389 |
self._out.write(u'/>')
|
|
390 |
self._lastStart = False
|
|
391 |
else:
|
|
392 |
self._out.write(u'</%s>' % name)
|
|
393 |
self._currentXPath.pop()
|
|
394 |
|
|
395 |
def characters(self, content):
|
|
396 |
|
|
397 |
self.closeLastStart()
|
|
398 |
self._characterBuffer.append(content)
|
|
399 |
|
|
400 |
def ignorableWhitespace(self, content):
|
|
401 |
|
|
402 |
self.closeLastStart()
|
|
403 |
self.flushCharacterBuffer()
|
|
404 |
self._out.write(content)
|
|
405 |
|
|
406 |
def resolveEntity(self, publicId, systemId):
|
|
407 |
|
|
408 |
loc, name = posixpath.split(systemId)
|
|
409 |
if loc == u"http://www.w3.org/TR/xhtml1/DTD" or loc == u"":
|
|
410 |
systemId = path.join(self._dtd, name)
|
|
411 |
return EntityResolver.resolveEntity(self, publicId, systemId)
|
|
412 |
|
|
413 |
def processingInstruction(self, target, data):
|
|
414 |
|
|
415 |
self.closeLastStart()
|
|
416 |
self.flushCharacterBuffer()
|
|
417 |
func = getattr(self._func, target)
|
|
418 |
args = {}
|
|
419 |
for keyval in shlex.split(data.encode("utf-8")):
|
|
420 |
key, val = keyval.split("=", 1)
|
|
421 |
args[key] = val
|
|
422 |
func(self, **args)
|
|
423 |
|
|
424 |
def parseWithER(istream, handler):
|
|
425 |
|
|
426 |
parser = makeParser()
|
|
427 |
parser.setContentHandler(handler)
|
|
428 |
parser.setEntityResolver(handler)
|
|
429 |
parser.parse(istream)
|
|
430 |
|
|
431 |
def main():
|
|
432 |
|
|
433 |
# parse command line
|
|
434 |
cmdlineparser = optparse.OptionParser(
|
|
435 |
usage = '%prog [options] [key=value]* src [dst]',
|
|
436 |
conflict_handler = "error",
|
|
437 |
description = '''Leightweight HTML page generation tool''',
|
|
438 |
add_help_option = True,
|
|
439 |
)
|
|
440 |
cmdlineparser.add_option("-s", "--srcroot",
|
|
441 |
action="store", dest="srcroot",
|
|
442 |
type="string", default=".",
|
|
443 |
help="source tree root", metavar='location')
|
|
444 |
cmdlineparser.add_option("-d", "--dstroot",
|
|
445 |
action="store", dest="dstroot",
|
|
446 |
type="string", default=".",
|
|
447 |
help="destination tree root", metavar='location')
|
|
448 |
cmdlineparser.add_option("-t", "--dtd",
|
|
449 |
action="store", dest="dtd",
|
|
450 |
type="string", default=".",
|
|
451 |
help="local mirror of XHTML DTDs", metavar='location')
|
|
452 |
cmdlineparser.add_option("-m", "--encodinghtml",
|
|
453 |
action="store", dest="encodinghtml",
|
|
454 |
type="string", default="",
|
16574
|
455 |
help="force value of html content encoding meta tag", metavar='encoding')
|
16575
|
456 |
cmdlineparser.add_option("-p", "--spamprotect",
|
16574
|
457 |
action="store_true", dest="spamprotect",
|
|
458 |
help="rewrite mailto-links using entities")
|
16233
|
459 |
|
|
460 |
options, args = cmdlineparser.parse_args(sys.argv[1:])
|
|
461 |
|
|
462 |
# check source
|
|
463 |
if len(args) < 1:
|
|
464 |
cmdlineparser.error("Exactly one soure file must be given")
|
|
465 |
|
|
466 |
# read arguments
|
|
467 |
valdict = {}
|
|
468 |
if len(args) == 1:
|
|
469 |
src = args[0]
|
|
470 |
dst = None
|
|
471 |
else:
|
|
472 |
if "=" in args[-2]:
|
|
473 |
src = args[-1]
|
|
474 |
dst = None
|
|
475 |
vallist = args[:-1]
|
|
476 |
else:
|
|
477 |
src = args[-2]
|
|
478 |
dst = args[-1]
|
|
479 |
if dst == "-":
|
|
480 |
dst = None
|
|
481 |
vallist = args[:-2]
|
|
482 |
for keyval in vallist:
|
|
483 |
key, val = keyval.split("=", 1)
|
|
484 |
valdict[unicode(key, 'latin-1')] = unicode(val, 'latin-1')
|
|
485 |
|
|
486 |
# path calculator
|
|
487 |
pc = PathCalculator(src, options.srcroot, options.dstroot)
|
|
488 |
|
|
489 |
# function space
|
|
490 |
modtime = os.stat(src).st_mtime
|
|
491 |
func = Functions(pc, valdict, modtime, options.encodinghtml)
|
|
492 |
|
|
493 |
# allocate file handles
|
|
494 |
istream = open(src, 'r')
|
|
495 |
if dst is not None:
|
|
496 |
ostream = open(dst, 'wb')
|
|
497 |
else:
|
|
498 |
ostream = sys.stdout
|
|
499 |
|
|
500 |
# process file
|
16574
|
501 |
transformer = TransformerHandler(ostream, outputEncoding, options.dtd, func, options.spamprotect)
|
16233
|
502 |
parseWithER(istream, transformer)
|
|
503 |
|
|
504 |
# close handles
|
|
505 |
ostream.close()
|
|
506 |
istream.close()
|
|
507 |
|
|
508 |
if __name__ == '__main__':
|
|
509 |
main()
|
|
510 |
|
|
511 |
__todo__ = '''
|
|
512 |
'''
|