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 shlex
|
|
17 |
import optparse
|
|
18 |
import time
|
|
19 |
|
19533
|
20 |
# xhtml parsing
|
|
21 |
from xhtmlparse import TransformerHandler, parseWithER
|
16233
|
22 |
|
|
23 |
nbsp = unichr(160)
|
|
24 |
|
|
25 |
# global configuration
|
|
26 |
outputEncoding = 'UTF-8'
|
|
27 |
|
|
28 |
# implement your own functions for PIs here
|
19533
|
29 |
class Functions(object):
|
16233
|
30 |
|
|
31 |
def __init__(self, pc, valdict, modtime, encodingMeta):
|
|
32 |
|
|
33 |
self._pc = pc
|
|
34 |
self._valdict = valdict
|
|
35 |
self._modtime = modtime
|
|
36 |
self._encodingMeta = encodingMeta
|
|
37 |
|
16586
|
38 |
def value(self, handler, key):
|
16233
|
39 |
|
16323
|
40 |
"""<?value key="..."?> - inserts a property value given on the command line"""
|
16233
|
41 |
|
16586
|
42 |
value = self._valdict[key]
|
16233
|
43 |
handler.characters(value)
|
|
44 |
|
16586
|
45 |
def title(self, handler):
|
16233
|
46 |
|
16323
|
47 |
"""<?title?> - inserts the document's title as glimpsed from the <title> tag"""
|
|
48 |
|
16233
|
49 |
handler.characters(handler._title)
|
|
50 |
|
16586
|
51 |
def contentType(self, handler):
|
16233
|
52 |
|
16323
|
53 |
"""<?contentType?> - inserts the document's content type/encoding"""
|
|
54 |
|
16233
|
55 |
encoding = self._encodingMeta or handler._encoding
|
|
56 |
attr = {
|
|
57 |
u"http-equiv": u"Content-Type",
|
|
58 |
u"content": u"text/html; charset=%s" % encoding
|
|
59 |
}
|
|
60 |
handler.startElement(u"meta", attr)
|
|
61 |
handler.endElement(u"meta")
|
|
62 |
|
16586
|
63 |
def currentDate(self, handler):
|
16233
|
64 |
|
16323
|
65 |
"""<?currentDate?> - inserts the current date"""
|
|
66 |
|
16233
|
67 |
handler.characters(unicode(time.strftime('%Y-%m-%d %H:%M:%S')))
|
|
68 |
|
16586
|
69 |
def modificationDate(self, handler):
|
16233
|
70 |
|
16323
|
71 |
"""<?modificationDate?> - inserts the modification date of this file"""
|
|
72 |
|
16233
|
73 |
handler.characters(unicode(time.strftime('%Y-%m-%d %H:%M:%S',
|
|
74 |
time.localtime(self._modtime))))
|
|
75 |
|
16586
|
76 |
def relativeRoot(self, handler, href):
|
16233
|
77 |
|
16323
|
78 |
"""<?relativeRoot href="..."?> - inserts the relative path specified by href"""
|
|
79 |
|
16586
|
80 |
handler.characters(self._pc.relDstPathOf('//'+href.encode("latin-1")))
|
16233
|
81 |
|
16586
|
82 |
def include(self, handler, file):
|
16233
|
83 |
|
16323
|
84 |
"""<?include file="..."?> - includes an XML file"""
|
|
85 |
|
16586
|
86 |
filename = self._pc.absSrcPathOf(file.encode("latin-1"))
|
16233
|
87 |
self._modtime = max(self._modtime, os.stat(filename).st_mtime)
|
|
88 |
istream = open(filename, "r")
|
|
89 |
parseWithER(istream, handler)
|
|
90 |
istream.close()
|
|
91 |
|
16586
|
92 |
def navitem(self, handler, target, title):
|
16233
|
93 |
|
16323
|
94 |
"""<?navitem target="..." title="..."?> - inserts an item in a navigation list,
|
16324
|
95 |
targeting to <target> and entitled <title>"""
|
16323
|
96 |
|
16586
|
97 |
target = self._pc.relDstPathOf(target.encode("latin-1"))
|
16233
|
98 |
if self._pc.isSrc(target):
|
|
99 |
wrapTagname = u"strong"
|
|
100 |
else:
|
|
101 |
wrapTagname = u"span"
|
|
102 |
attr = {}
|
|
103 |
handler.startElement(u"li", attr)
|
|
104 |
handler.startElement(wrapTagname, {})
|
|
105 |
handler.startElement(u"a", {
|
|
106 |
u"href": unicode(target, 'latin-1')
|
|
107 |
})
|
|
108 |
handler.characters(title)
|
|
109 |
handler.endElement(u"a")
|
|
110 |
handler.endElement(wrapTagname)
|
|
111 |
handler.endElement(u"li")
|
|
112 |
|
16586
|
113 |
def downloadLink(self, handler, target, title = None):
|
16296
|
114 |
|
16324
|
115 |
"""<?downloadLink target="..." [title="..."]?> - inserts a link to a file
|
|
116 |
to download; if the title is omitted, it is the bare filename itself"""
|
|
117 |
|
16586
|
118 |
targetReal = self._pc.absDstPathOf(target.encode("latin-1"))
|
|
119 |
if not title:
|
|
120 |
title = unicode(posixpath.split(targetReal)[1], 'latin-1')
|
16296
|
121 |
size = os.stat(targetReal).st_size
|
|
122 |
handler.startElement(u"a", {
|
|
123 |
u"href": target
|
|
124 |
})
|
|
125 |
handler.characters(title)
|
|
126 |
handler.endElement(u"a")
|
|
127 |
|
16586
|
128 |
def downloadCells(self, handler, target, title = None):
|
16233
|
129 |
|
16324
|
130 |
"""<?downloadCells target="..." [title="..."]?> - like downloadLink, but
|
|
131 |
puts the link into a table cell and appends a table cell displaying the
|
|
132 |
size of the linked file"""
|
|
133 |
|
16586
|
134 |
targetReal = self._pc.absDstPathOf(target.encode("latin-1"))
|
|
135 |
if not title:
|
|
136 |
title = unicode(posixpath.split(targetReal)[1], 'latin-1')
|
16233
|
137 |
size = os.stat(targetReal).st_size
|
|
138 |
handler.startElement(u"td", {})
|
|
139 |
handler.startElement(u"a", {
|
|
140 |
u"href": target
|
|
141 |
})
|
|
142 |
handler.characters(title)
|
|
143 |
handler.endElement(u"a")
|
|
144 |
handler.endElement(u"td")
|
|
145 |
handler.startElement(u"td", {})
|
17686
|
146 |
handler.characters(u"%.1f%sMB" % (size / (1024.0 * 1024), unichr(160)))
|
16233
|
147 |
handler.endElement(u"td")
|
|
148 |
|
16590
|
149 |
def mirror(self, handler, prefix, title, stripprefix = u""):
|
16574
|
150 |
|
16590
|
151 |
"""<?mirror prefix="..." title="..." [stripprefix="..."] ?> - generates a mirror switch link,
|
16574
|
152 |
where prefix denotes the base root url of the mirror location
|
|
153 |
and title the visible description"""
|
|
154 |
|
16619
|
155 |
title = title.replace(u" ", unichr(160))
|
16582
|
156 |
thisloc = self._pc.relLocOfThis()
|
|
157 |
if thisloc.startswith(stripprefix):
|
|
158 |
thisloc = thisloc[len(stripprefix):]
|
16584
|
159 |
else:
|
|
160 |
raise Exception("Incompatible mirror (prefix to strip not found): %s" % title.encode("latin-1"))
|
16582
|
161 |
handler.startElement(u"a", {u"href": posixpath.join(prefix, thisloc)})
|
16574
|
162 |
handler.characters(title)
|
|
163 |
handler.endElement(u"a")
|
|
164 |
|
16323
|
165 |
def getPc(self):
|
|
166 |
|
|
167 |
return self._pc
|
|
168 |
|
16233
|
169 |
# a notion of paths
|
|
170 |
class PathCalculator:
|
|
171 |
|
|
172 |
def __init__(self, srcLoc, srcRoot, dstRoot):
|
|
173 |
|
|
174 |
self._src = path.normpath(path.abspath(srcLoc))
|
16574
|
175 |
srcPath, self._srcName = path.split(self._src)
|
16233
|
176 |
self._srcRoot = path.normpath(path.abspath(srcRoot))
|
|
177 |
self._dstRoot = path.normpath(path.abspath(dstRoot))
|
|
178 |
self._relRoot = ""
|
|
179 |
relLocChain = []
|
|
180 |
diffRoot = srcPath
|
|
181 |
while diffRoot != self._srcRoot:
|
|
182 |
self._relRoot = path.join(self._relRoot, os.pardir)
|
|
183 |
diffRoot, chainPiece = path.split(diffRoot)
|
|
184 |
relLocChain.insert(0, chainPiece)
|
|
185 |
self._relRoot = self._relRoot and self._relRoot + '/'
|
|
186 |
self._relLoc = relLocChain and path.join(*relLocChain) or ""
|
|
187 |
|
|
188 |
def isSrc(self, loc):
|
|
189 |
|
|
190 |
return self.absSrcPathOf(loc) == self._src
|
|
191 |
|
|
192 |
def relRootPath(self):
|
|
193 |
|
|
194 |
return self._relRoot
|
|
195 |
|
|
196 |
def absSrcPathOf(self, loc):
|
|
197 |
|
|
198 |
if loc.startswith("//"):
|
|
199 |
return path.normpath(path.abspath(loc[2:]))
|
|
200 |
else:
|
|
201 |
return path.normpath(path.abspath(path.join(self._relLoc, loc)))
|
|
202 |
|
|
203 |
def absDstPathOf(self, loc):
|
|
204 |
|
|
205 |
if loc.startswith("//"):
|
|
206 |
return path.join(self._dstRoot, loc[2:])
|
|
207 |
else:
|
|
208 |
return path.join(self._dstRoot, self._relLoc, loc)
|
|
209 |
|
|
210 |
def relSrcPathOf(self, loc):
|
|
211 |
|
|
212 |
loc = self.absSrcPathOf(loc)
|
|
213 |
loc = self.stripCommonPrefix(loc, self._srcRoot)
|
|
214 |
loc = self.stripCommonPrefix(loc, self._relLoc)
|
|
215 |
return loc
|
|
216 |
|
|
217 |
def relDstPathOf(self, loc):
|
|
218 |
|
|
219 |
loc = self.absDstPathOf(loc)
|
|
220 |
loc = self.stripCommonPrefix(loc, self._dstRoot)
|
|
221 |
loc = self.stripCommonPrefix(loc, self._relLoc)
|
|
222 |
return loc
|
|
223 |
|
16574
|
224 |
def relLocOfThis(self):
|
|
225 |
|
|
226 |
return posixpath.join(self._relLoc, self._srcName)
|
|
227 |
|
16233
|
228 |
def stripCommonPrefix(self, loc, prefix):
|
|
229 |
|
|
230 |
common = self.commonPrefix((loc, prefix))
|
|
231 |
if common:
|
|
232 |
loc = loc[len(common):]
|
|
233 |
if loc and loc[0] == '/':
|
|
234 |
loc = loc[1:]
|
|
235 |
return loc
|
|
236 |
|
|
237 |
def commonPrefix(self, locs):
|
|
238 |
|
|
239 |
common = path.commonprefix(locs)
|
|
240 |
# commonprefix bugs
|
|
241 |
if [ loc for loc in locs if len(loc) != common ] and \
|
|
242 |
[ loc for loc in locs if len(common) < len(loc) and loc[len(common)] != path.sep ]:
|
|
243 |
common = path.split(common)[0]
|
|
244 |
if common and common[-1] == path.sep:
|
|
245 |
common = common[:-1]
|
|
246 |
|
|
247 |
return common or ""
|
|
248 |
|
19533
|
249 |
class FunctionsHandler(TransformerHandler):
|
16233
|
250 |
|
16579
|
251 |
def __init__(self, out, encoding, dtd, func):
|
16233
|
252 |
|
19533
|
253 |
super(FunctionsHandler, self).__init__(out, encoding, dtd)
|
16233
|
254 |
self._func = func
|
|
255 |
self._title = None
|
|
256 |
|
|
257 |
def transformAbsPath(self, attrs, attrname):
|
|
258 |
|
|
259 |
pathval = attrs.get(attrname, None)
|
|
260 |
if pathval and pathval.startswith(u"//"):
|
|
261 |
attrs = dict(attrs)
|
|
262 |
pathRel = self._func.getPc().relDstPathOf(pathval)
|
|
263 |
pathDst = self._func.getPc().absDstPathOf(pathval)
|
|
264 |
if not path.exists(pathDst):
|
|
265 |
raise Exception("Path does not exist: %s" % pathDst)
|
|
266 |
attrs[attrname] = pathRel
|
|
267 |
return attrs
|
|
268 |
else:
|
|
269 |
return attrs
|
|
270 |
|
|
271 |
def startElement(self, name, attrs):
|
|
272 |
|
|
273 |
if name == u"dummy:wrapper":
|
|
274 |
return
|
|
275 |
# this list is not exhaustive
|
19554
|
276 |
for tagname, attrname in ((u"a", u"href"), (u"img", u"src"), (u"link", u"href"), (u"script", u"src")):
|
16233
|
277 |
if name == tagname:
|
|
278 |
attrs = self.transformAbsPath(attrs, attrname)
|
19533
|
279 |
super(FunctionsHandler, self).startElement(name, attrs)
|
16233
|
280 |
|
|
281 |
def endElement(self, name):
|
|
282 |
|
|
283 |
if name == u"dummy:wrapper":
|
|
284 |
return
|
|
285 |
elif name == u'title':
|
|
286 |
self._title = u"".join(self._characterBuffer)
|
19533
|
287 |
super(FunctionsHandler, self).endElement(name)
|
16233
|
288 |
|
|
289 |
def processingInstruction(self, target, data):
|
|
290 |
|
|
291 |
self.closeLastStart()
|
|
292 |
self.flushCharacterBuffer()
|
|
293 |
func = getattr(self._func, target)
|
|
294 |
args = {}
|
|
295 |
for keyval in shlex.split(data.encode("utf-8")):
|
|
296 |
key, val = keyval.split("=", 1)
|
|
297 |
args[key] = val
|
|
298 |
func(self, **args)
|
|
299 |
|
|
300 |
|
|
301 |
def main():
|
|
302 |
|
|
303 |
# parse command line
|
|
304 |
cmdlineparser = optparse.OptionParser(
|
|
305 |
usage = '%prog [options] [key=value]* src [dst]',
|
|
306 |
conflict_handler = "error",
|
|
307 |
description = '''Leightweight HTML page generation tool''',
|
|
308 |
add_help_option = True,
|
|
309 |
)
|
|
310 |
cmdlineparser.add_option("-s", "--srcroot",
|
|
311 |
action="store", dest="srcroot",
|
|
312 |
type="string", default=".",
|
|
313 |
help="source tree root", metavar='location')
|
|
314 |
cmdlineparser.add_option("-d", "--dstroot",
|
|
315 |
action="store", dest="dstroot",
|
|
316 |
type="string", default=".",
|
|
317 |
help="destination tree root", metavar='location')
|
|
318 |
cmdlineparser.add_option("-t", "--dtd",
|
|
319 |
action="store", dest="dtd",
|
|
320 |
type="string", default=".",
|
|
321 |
help="local mirror of XHTML DTDs", metavar='location')
|
|
322 |
cmdlineparser.add_option("-m", "--encodinghtml",
|
|
323 |
action="store", dest="encodinghtml",
|
|
324 |
type="string", default="",
|
16574
|
325 |
help="force value of html content encoding meta tag", metavar='encoding')
|
16233
|
326 |
|
|
327 |
options, args = cmdlineparser.parse_args(sys.argv[1:])
|
|
328 |
|
|
329 |
# check source
|
|
330 |
if len(args) < 1:
|
|
331 |
cmdlineparser.error("Exactly one soure file must be given")
|
|
332 |
|
|
333 |
# read arguments
|
|
334 |
valdict = {}
|
|
335 |
if len(args) == 1:
|
|
336 |
src = args[0]
|
|
337 |
dst = None
|
|
338 |
else:
|
|
339 |
if "=" in args[-2]:
|
|
340 |
src = args[-1]
|
|
341 |
dst = None
|
|
342 |
vallist = args[:-1]
|
|
343 |
else:
|
|
344 |
src = args[-2]
|
|
345 |
dst = args[-1]
|
|
346 |
if dst == "-":
|
|
347 |
dst = None
|
|
348 |
vallist = args[:-2]
|
|
349 |
for keyval in vallist:
|
|
350 |
key, val = keyval.split("=", 1)
|
|
351 |
valdict[unicode(key, 'latin-1')] = unicode(val, 'latin-1')
|
|
352 |
|
|
353 |
# path calculator
|
|
354 |
pc = PathCalculator(src, options.srcroot, options.dstroot)
|
|
355 |
|
|
356 |
# function space
|
|
357 |
modtime = os.stat(src).st_mtime
|
|
358 |
func = Functions(pc, valdict, modtime, options.encodinghtml)
|
|
359 |
|
|
360 |
# allocate file handles
|
|
361 |
istream = open(src, 'r')
|
|
362 |
if dst is not None:
|
|
363 |
ostream = open(dst, 'wb')
|
|
364 |
else:
|
|
365 |
ostream = sys.stdout
|
|
366 |
|
|
367 |
# process file
|
17751
|
368 |
try:
|
19533
|
369 |
transformer = FunctionsHandler(ostream, outputEncoding, options.dtd, func)
|
17751
|
370 |
parseWithER(istream, transformer)
|
|
371 |
except Exception:
|
|
372 |
if dst is not None:
|
|
373 |
os.unlink(dst)
|
|
374 |
raise
|
16233
|
375 |
|
|
376 |
# close handles
|
|
377 |
ostream.close()
|
|
378 |
istream.close()
|
|
379 |
|
|
380 |
if __name__ == '__main__':
|
|
381 |
main()
|
|
382 |
|
|
383 |
__todo__ = '''
|
|
384 |
'''
|