1 # -*- coding: utf-8 -*-
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
7 from collections import defaultdict
11 """Transforms XML to some text.
12 Used instead of XSLT which is difficult and cumbersome.
15 def __init__(self, options=None):
18 self._options.append(options)
19 self.text_filters = []
20 self.escaped_text_filters = []
22 def register_text_filter(self, fun):
23 self.text_filters.append(fun)
25 def filter_text(self, text):
26 for flt in self.text_filters:
31 # TODO: just work on the tree and let lxml handle escaping.
32 e = etree.Element("x")
34 # This whole mixing text with ML is so wrong.
35 output = etree.tostring(e, encoding=unicode)[3:-4]
36 for flt in self.escaped_text_filters:
41 def generate(self, document):
42 """Generate text from node using handlers defined in class."""
43 output = self._handle_element(document)
44 return u''.join([x for x in flatten(output) if x is not None])
48 """Returnes merged scoped options for current node.
50 # Here we can see how a decision not to return the modified map
51 # leads to a need for a hack.
52 return reduce(lambda a, b: a.update(b) or a, self._options, defaultdict(lambda: None))
55 def options(self, opts):
56 """Sets options overrides for current and child nodes
58 self._options.append(opts)
61 def _handle_for_element(self, element):
64 # from nose.tools import set_trace
66 if element.tag[0] == '{':
67 for nshort, nhref in element.nsmap.items():
69 if element.tag.index('{%s}' % nhref) == 0:
71 tagname = element.tag[len('{%s}' % nhref):]
76 raise ValueError("Strange ns for tag: %s, nsmap: %s" %
77 (element.tag, element.nsmap))
82 meth_name = "handle_%s__%s" % (ns, tagname)
84 meth_name = "handle_%s" % (tagname,)
86 handler = getattr(self, meth_name, None)
89 def next(self, element):
94 sibling = element.getnext()
95 if sibling is not None: return sibling # found a new branch to dig into
96 element = element.getparent()
97 if element is None: return None # end of tree
99 def _handle_element(self, element):
100 if isinstance(element, etree._Comment): return None
102 handler = self._handle_for_element(element)
105 options_scopes = len(self._options)
108 pre = [self.filter_text(element.text)]
109 post = [self.filter_text(element.tail)]
111 vals = handler(element)
112 # depending on number of returned values, vals can be None, a value, or a tuple.
113 # how poorly designed is that? 9 lines below are needed just to unpack this.
115 return [self.filter_text(element.tail)]
117 if not isinstance(vals, tuple):
118 return [vals, self.filter_text(element.tail)]
120 pre = [vals[0], self.filter_text(element.text)]
121 post = [vals[1], self.filter_text(element.tail)]
123 out = pre + [self._handle_element(child) for child in element] + post
125 # clean up option scopes if necessary
126 self._options = self._options[0:options_scopes]
130 def tag_open_close(name_, classes_=None, **attrs):
131 u"""Creates tag beginning and end.
133 >>> tag_open_close("a", "klass", x=u"ą<")
134 (u'<a x="\\u0105<" class="klass">', u'</a>')
138 if isinstance(classes_, (tuple, list)): classes_ = ' '.join(classes_)
139 attrs['class'] = classes_
141 e = etree.Element(name_)
143 for k, v in attrs.items():
145 pre, post = etree.tostring(e, encoding=unicode).split(u"> <")
146 return pre + u">", u"<" + post
148 def tag(name_, classes_=None, **attrs):
149 """Returns a handler which wraps node contents in tag `name', with class attribute
150 set to `classes' and other attributes according to keyword paramters
152 def _hnd(self, element):
153 return tag_open_close(name_, classes_, **attrs)
157 def tagged(name, classes=None, **attrs):
158 """Handler decorator which wraps handler output in tag `name', with class attribute
159 set to `classes' and other attributes according to keyword paramters
162 if isinstance(classes, (tuple,list)): classes = ' '.join(classes)
163 attrs['class'] = classes
164 a = ''.join([' %s="%s"' % (k,v) for (k,v) in attrs.items()])
166 def _wrap(self, element):
170 prepend = "<%s%s>" % (name, a)
171 append = "</%s>" % name
173 if isinstance(r, tuple):
174 return prepend + r[0], r[1] + append
175 return prepend + r + append
180 def ifoption(**options):
181 """Decorator which enables node only when options are set
184 def _handler(self, *args, **kw):
186 for k, v in options.items():
189 return f(self, *args, **kw)
193 def flatten(l, ltypes=(list, tuple)):
194 """flatten function from BasicPropery/BasicTypes package
200 while isinstance(l[i], ltypes):