Merge branch 'master' into python2
[wrw.git] / wrw / sp / cons.py
CommitLineData
1273171c 1import sys, collections
ff79cdbf
FT
2import xml.dom.minidom
3
4class node(object):
d703ed47 5 pass
ff79cdbf
FT
6
7class text(node, unicode):
8 def __todom__(self, doc):
9 return doc.createTextNode(self)
10
f3464a4a
FT
11class raw(node, unicode):
12 def __todom__(self, doc):
13 raise Exception("Cannot convert raw code to DOM objects")
14
ff79cdbf
FT
15class element(node):
16 def __init__(self, ns, name, ctx):
17 self.ns = ns
18 self.name = unicode(name)
19 self.ctx = ctx
20 self.attrs = {}
21 self.children = []
22
23 def __call__(self, *children, **attrs):
24 for child in children:
a573465e 25 self.ctx.addchild(self, child)
ff79cdbf 26 for k, v in attrs.iteritems():
a573465e 27 self.ctx.addattr(self, k, v)
ff79cdbf
FT
28 return self
29
30 def __todom__(self, doc):
31 el = doc.createElementNS(self.ns, self.name)
32 for k, v in self.attrs.iteritems():
33 el.setAttribute(k, v)
34 for child in self.children:
35 el.appendChild(child.__todom__(doc))
36 return el
37
d703ed47
FT
38 def __str__(self):
39 doc = xml.dom.minidom.Document()
40 return self.__todom__(doc).toxml()
41
ff79cdbf 42class context(object):
50be6d54 43 charset = (sys.getfilesystemencoding() or "ascii")
85ed5fa5 44
ff79cdbf
FT
45 def __init__(self):
46 self.nodeconv = {}
85ed5fa5 47 self.nodeconv[str] = lambda ob: text(ob, self.charset)
ff79cdbf
FT
48 self.nodeconv[unicode] = text
49 self.nodeconv[int] = text
50 self.nodeconv[long] = text
51 self.nodeconv[float] = text
52
53 def nodefrom(self, ob):
54 if isinstance(ob, node):
55 return ob
56 if hasattr(ob, "__tonode__"):
57 return ob.__tonode__()
58 if type(ob) in self.nodeconv:
59 return self.nodeconv[type(ob)](ob)
6d764ed2 60 return None
ff79cdbf 61
a573465e 62 def addchild(self, node, child):
b339a677
FT
63 if child is None:
64 return
6d764ed2
FT
65 new = self.nodefrom(child)
66 if new is not None:
8f33b1de 67 node.children.append(new)
1273171c 68 elif isinstance(child, collections.Iterable):
6d764ed2
FT
69 for ch in child:
70 self.addchild(node, ch)
71 else:
8f33b1de 72 raise Exception("No node conversion known for %s objects" % str(type(child)))
a573465e
FT
73
74 def addattr(self, node, k, v):
4c4dcf7a
FT
75 if v is not None:
76 node.attrs[unicode(k)] = unicode(v)
a573465e 77
ff79cdbf 78class constructor(object):
9bc70dab 79 def __init__(self, ns, elcls=element, ctx=None):
ff79cdbf
FT
80 self._ns = ns
81 self._elcls = elcls
82 if ctx is None: ctx = context()
83 self._ctx = ctx
84
85 def __getattr__(self, name):
86 return self._elcls(self._ns, name, self._ctx)
fb5f9f27
FT
87
88class doctype(node):
89 def __init__(self, rootname, pubid, dtdid):
90 self.rootname = rootname
91 self.pubid = pubid
92 self.dtdid = dtdid