23
22
# importing this module is fairly slow because it has to load several
25
from bzrlib import registry
26
from bzrlib.trace import mutter, warning
27
from util.cElementTree import ElementTree, SubElement, Element
30
# it's in this package in python2.5
31
from xml.etree.cElementTree import (ElementTree, SubElement, Element,
32
XMLTreeBuilder, fromstring, tostring)
33
import xml.etree as elementtree
35
from cElementTree import (ElementTree, SubElement, Element,
36
XMLTreeBuilder, fromstring, tostring)
37
import elementtree.ElementTree
38
ParseError = SyntaxError
28
39
except ImportError:
29
from util.elementtree.ElementTree import ElementTree, SubElement, Element
40
mutter('WARNING: using slower ElementTree; consider installing cElementTree'
41
" and make sure it's on your PYTHONPATH")
42
# this copy is shipped with bzr
43
from util.elementtree.ElementTree import (ElementTree, SubElement,
44
Element, XMLTreeBuilder,
46
import util.elementtree as elementtree
47
from xml.parsers.expat import ExpatError as ParseError
31
from bzrlib.inventory import ROOT_ID, Inventory, InventoryEntry
32
from bzrlib.revision import Revision, RevisionReference
49
from bzrlib import errors
35
52
class Serializer(object):
36
53
"""Abstract object serialize/deserialize"""
37
55
def write_inventory(self, inv, f):
38
56
"""Write inventory to a file"""
39
elt = self._pack_inventory(inv)
40
self._write_element(elt, f)
42
def read_inventory(self, f):
43
return self._unpack_inventory(self._read_element(f))
57
raise NotImplementedError(self.write_inventory)
59
def write_inventory_to_string(self, inv):
60
raise NotImplementedError(self.write_inventory_to_string)
62
def read_inventory_from_string(self, xml_string, revision_id=None,
64
"""Read xml_string into an inventory object.
66
:param xml_string: The xml to read.
67
:param revision_id: If not-None, the expected revision id of the
68
inventory. Some serialisers use this to set the results' root
69
revision. This should be supplied for deserialising all
70
from-repository inventories so that xml5 inventories that were
71
serialised without a revision identifier can be given the right
72
revision id (but not for working tree inventories where users can
73
edit the data without triggering checksum errors or anything).
74
:param entry_cache: An optional cache of InventoryEntry objects. If
75
supplied we will look up entries via (file_id, revision_id) which
76
should map to a valid InventoryEntry (File/Directory/etc) object.
79
return self._unpack_inventory(fromstring(xml_string), revision_id,
80
entry_cache=entry_cache)
82
raise errors.UnexpectedInventoryFormat(e)
84
def read_inventory(self, f, revision_id=None):
86
return self._unpack_inventory(self._read_element(f),
89
raise errors.UnexpectedInventoryFormat(e)
45
91
def write_revision(self, rev, f):
46
92
self._write_element(self._pack_revision(rev), f)
94
def write_revision_to_string(self, rev):
95
return tostring(self._pack_revision(rev)) + '\n'
48
97
def read_revision(self, f):
49
98
return self._unpack_revision(self._read_element(f))
100
def read_revision_from_string(self, xml_string):
101
return self._unpack_revision(fromstring(xml_string))
51
103
def _write_element(self, elt, f):
52
104
ElementTree(elt).write(f, 'utf-8')
56
108
return ElementTree().parse(f)
60
class _Serializer_v4(Serializer):
61
"""Version 0.0.4 serializer"""
65
def _pack_inventory(self, inv):
66
"""Convert to XML Element"""
67
e = Element('inventory')
69
if inv.root.file_id not in (None, ROOT_ID):
70
e.set('file_id', inv.root.file_id)
71
for path, ie in inv.iter_entries():
72
e.append(self._pack_entry(ie))
76
def _pack_entry(self, ie):
77
"""Convert InventoryEntry to XML element"""
79
e.set('name', ie.name)
80
e.set('file_id', ie.file_id)
81
e.set('kind', ie.kind)
83
if ie.text_size != None:
84
e.set('text_size', '%d' % ie.text_size)
86
for f in ['text_id', 'text_sha1']:
91
# to be conservative, we don't externalize the root pointers
92
# for now, leaving them as null in the xml form. in a future
93
# version it will be implied by nested elements.
94
if ie.parent_id != ROOT_ID:
95
assert isinstance(ie.parent_id, basestring)
96
e.set('parent_id', ie.parent_id)
103
def _unpack_inventory(self, elt):
104
"""Construct from XML Element
106
assert elt.tag == 'inventory'
107
root_id = elt.get('file_id') or ROOT_ID
108
inv = Inventory(root_id)
110
ie = self._unpack_entry(e)
111
if ie.parent_id == ROOT_ID:
112
ie.parent_id = root_id
117
def _unpack_entry(self, elt):
118
assert elt.tag == 'entry'
120
## original format inventories don't have a parent_id for
121
## nodes in the root directory, but it's cleaner to use one
123
parent_id = elt.get('parent_id')
124
if parent_id == None:
127
ie = InventoryEntry(elt.get('file_id'),
131
ie.text_id = elt.get('text_id')
132
ie.text_sha1 = elt.get('text_sha1')
134
## mutter("read inventoryentry: %r" % (elt.attrib))
136
v = elt.get('text_size')
137
ie.text_size = v and int(v)
142
def _pack_revision(self, rev):
143
"""Revision object -> xml tree"""
144
root = Element('revision',
145
committer = rev.committer,
146
timestamp = '%.9f' % rev.timestamp,
147
revision_id = rev.revision_id,
148
inventory_id = rev.inventory_id,
149
inventory_sha1 = rev.inventory_sha1,
152
root.set('timezone', str(rev.timezone))
155
msg = SubElement(root, 'message')
156
msg.text = rev.message
160
pelts = SubElement(root, 'parents')
161
pelts.tail = pelts.text = '\n'
162
for rr in rev.parents:
163
assert isinstance(rr, RevisionReference)
164
p = SubElement(pelts, 'revision_ref')
166
assert rr.revision_id
167
p.set('revision_id', rr.revision_id)
169
p.set('revision_sha1', rr.revision_sha1)
174
def _unpack_revision(self, elt):
175
"""XML Element -> Revision object"""
177
# <changeset> is deprecated...
178
if elt.tag not in ('revision', 'changeset'):
179
raise bzrlib.errors.BzrError("unexpected tag in revision file: %r" % elt)
181
rev = Revision(committer = elt.get('committer'),
182
timestamp = float(elt.get('timestamp')),
183
revision_id = elt.get('revision_id'),
184
inventory_id = elt.get('inventory_id'),
185
inventory_sha1 = elt.get('inventory_sha1')
188
precursor = elt.get('precursor')
189
precursor_sha1 = elt.get('precursor_sha1')
191
pelts = elt.find('parents')
195
assert p.tag == 'revision_ref', \
196
"bad parent node tag %r" % p.tag
197
rev_ref = RevisionReference(p.get('revision_id'),
198
p.get('revision_sha1'))
199
rev.parents.append(rev_ref)
203
prec_parent = rev.parents[0].revision_id
204
assert prec_parent == precursor
206
# revisions written prior to 0.0.5 have a single precursor
207
# give as an attribute
208
rev_ref = RevisionReference(precursor, precursor_sha1)
209
rev.parents.append(rev_ref)
211
v = elt.get('timezone')
212
rev.timezone = v and int(v)
214
rev.message = elt.findtext('message') # text of <message>
219
"""singleton instance"""
220
serializer_v4 = _Serializer_v4()
111
# performance tuning for elementree's serialiser. This should be
112
# sent upstream - RBC 20060523.
113
# the functions here are patched into elementtree at runtime.
115
escape_re = re.compile("[&'\"<>]")
118
"'":"'", # FIXME: overkill
123
def _escape_replace(match, map=escape_map):
124
return map[match.group()]
126
def _escape_attrib(text, encoding=None, replace=None):
127
# escape attribute value
131
text = elementtree.ElementTree._encode(text, encoding)
133
return elementtree.ElementTree._encode_entity(text)
135
return escape_re.sub(_escape_replace, text)
137
text = replace(text, "&", "&")
138
text = replace(text, "'", "'") # FIXME: overkill
139
text = replace(text, "\"", """)
140
text = replace(text, "<", "<")
141
text = replace(text, ">", ">")
143
except (TypeError, AttributeError):
144
elementtree.ElementTree._raise_serialization_error(text)
146
elementtree.ElementTree._escape_attrib = _escape_attrib
148
escape_cdata_re = re.compile("[&<>]")
154
def _escape_cdata_replace(match, map=escape_cdata_map):
155
return map[match.group()]
157
def _escape_cdata(text, encoding=None, replace=None):
158
# escape character data
162
text = elementtree.ElementTree._encode(text, encoding)
164
return elementtree.ElementTree._encode_entity(text)
166
return escape_cdata_re.sub(_escape_cdata_replace, text)
168
text = replace(text, "&", "&")
169
text = replace(text, "<", "<")
170
text = replace(text, ">", ">")
172
except (TypeError, AttributeError):
173
elementtree.ElementTree._raise_serialization_error(text)
175
elementtree.ElementTree._escape_cdata = _escape_cdata
178
class SerializerRegistry(registry.Registry):
179
"""Registry for serializer objects"""
182
format_registry = SerializerRegistry()
183
format_registry.register_lazy('4', 'bzrlib.xml4', 'serializer_v4')
184
format_registry.register_lazy('5', 'bzrlib.xml5', 'serializer_v5')
185
format_registry.register_lazy('6', 'bzrlib.xml6', 'serializer_v6')
186
format_registry.register_lazy('7', 'bzrlib.xml7', 'serializer_v7')
187
format_registry.register_lazy('8', 'bzrlib.xml8', 'serializer_v8')