2 # GObject-Introspection - a framework for introspecting GObject libraries
3 # Copyright (C) 2008 Johan Dahlin
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21 from contextlib import contextmanager
22 from cStringIO import StringIO
23 from xml.sax.saxutils import quoteattr
26 class XMLWriter(object):
28 self._data = StringIO()
32 self._indent_char = ' '
36 def _calc_attrs_length(self, attributes, indent):
40 for attr, value in attributes:
43 "value for attribute %r cannot be None" % (attr,))
44 attr_length += 2 + len(attr) + len(quoteattr(value))
45 return attr_length + indent
47 def _collect_attributes(self, attributes, extra_indent=-1):
50 extra_indent += len(self._indent_char) * self._indent
51 if self._calc_attrs_length(attributes, extra_indent) > 79:
52 indent_len = extra_indent
57 for attr, value in attributes:
58 if indent_len and not first:
59 attr_value += '\n%s' % (self._indent_char * indent_len)
62 "value for attribute %r cannot be None" % (attr,))
63 attr_value += ' %s=%s' % (attr, quoteattr(value))
68 def _open_tag(self, tag_name, attributes=None):
69 attrs = self._collect_attributes(
70 attributes, len(tag_name) + 1)
71 self.write_line('<%s%s>' % (tag_name, attrs))
73 def _close_tag(self, tag_name):
74 self.write_line('</%s>' % (tag_name,))
79 return self._data.getvalue()
81 def write_line(self, line=''):
82 self._data.write('%s%s\n' % (self._indent_char * self._indent, line))
84 def write_tag(self, tag_name, attributes, data=None):
85 prefix = '<%s' % (tag_name,)
87 suffix = '>%s</%s>' % (data, tag_name)
90 attrs = self._collect_attributes(
91 attributes, len(prefix) + len(suffix))
92 self.write_line(prefix + attrs + suffix)
94 def push_tag(self, tag_name, attributes=None):
95 self._open_tag(tag_name, attributes)
96 self._tag_stack.append(tag_name)
97 self._indent += self._indent_unit
100 self._indent -= self._indent_unit
101 tag_name = self._tag_stack.pop()
102 self._close_tag(tag_name)
106 def tagcontext(self, tag_name, attributes=None):
107 self.push_tag(tag_name, attributes)