17
17
"""XML externalization support."""
19
from __future__ import absolute_import
21
19
# "XML is like violence: if it doesn't solve your problem, you aren't
22
20
# using enough of it." -- various
24
22
# importing this module is fairly slow because it has to load several
25
from bzrlib.serializer import Serializer
26
from bzrlib.trace import mutter
30
import xml.etree.cElementTree as elementtree
31
ParseError = getattr(elementtree, "ParseError", SyntaxError)
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
32
39
except ImportError:
33
# Fall back to pure python implementation if C extension is unavailable
34
import xml.etree.ElementTree as elementtree
36
from xml.etree.ElementTree import ParseError
38
from xml.parsers.expat import ExpatError as ParseError
40
(ElementTree, SubElement, Element, fromstring, tostring) = (
41
elementtree.ElementTree, elementtree.SubElement, elementtree.Element,
42
elementtree.fromstring, elementtree.tostring)
50
from ..sixish import text_type, bytesintern
57
class XMLSerializer(serializer.Serializer):
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
49
from bzrlib import errors
52
class XMLSerializer(Serializer):
58
53
"""Abstract XML object serialize/deserialize"""
60
55
squashes_xml_invalid_characters = True
111
103
def _write_element(self, elt, f):
112
104
ElementTree(elt).write(f, 'utf-8')
115
107
def _read_element(self, f):
116
108
return ElementTree().parse(f)
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
119
178
def escape_invalid_chars(message):
120
179
"""Escape the XML-invalid characters in a commit message.
129
188
# aren't listed in the XML specification
130
189
# (http://www.w3.org/TR/REC-xml/#NT-Char).
131
190
return re.subn(u'[^\x09\x0A\x0D\u0020-\uD7FF\uE000-\uFFFD]+',
132
lambda match: match.group(0).encode(
133
'unicode_escape').decode('ascii'),
137
def get_utf8_or_ascii(a_str, _encode_utf8=cache_utf8.encode):
138
"""Return a cached version of the string.
140
cElementTree will return a plain string if the XML is plain ascii. It only
141
returns Unicode when it needs to. We want to work in utf-8 strings. So if
142
cElementTree returns a plain string, we can just return the cached version.
143
If it is Unicode, then we need to encode it.
145
:param a_str: An 8-bit string or Unicode as returned by
146
cElementTree.Element.get()
147
:return: A utf-8 encoded 8-bit string.
149
# This is fairly optimized because we know what cElementTree does, this is
150
# not meant as a generic function for all cases. Because it is possible for
151
# an 8-bit string to not be ascii or valid utf8.
152
if a_str.__class__ is text_type:
153
return _encode_utf8(a_str)
155
return bytesintern(a_str)
158
_utf8_re = lazy_regex.lazy_compile(b'[&<>\'\"]|[\x80-\xff]+')
159
_unicode_re = lazy_regex.lazy_compile(u'[&<>\'\"\u0080-\uffff]')
164
"'": "'", # FIXME: overkill
171
def _unicode_escape_replace(match, _map=_xml_escape_map):
172
"""Replace a string of non-ascii, non XML safe characters with their escape
174
This will escape both Standard XML escapes, like <>"', etc.
175
As well as escaping non ascii characters, because ElementTree did.
176
This helps us remain compatible to older versions of bzr. We may change
177
our policy in the future, though.
179
# jam 20060816 Benchmarks show that try/KeyError is faster if you
180
# expect the entity to rarely miss. There is about a 10% difference
181
# in overall time. But if you miss frequently, then if None is much
182
# faster. For our use case, we *rarely* have a revision id, file id
183
# or path name that is unicode. So use try/KeyError.
185
return _map[match.group()]
187
return "&#%d;" % ord(match.group())
190
def _utf8_escape_replace(match, _map=_xml_escape_map):
191
"""Escape utf8 characters into XML safe ones.
193
This uses 2 tricks. It is either escaping "standard" characters, like "&<>,
194
or it is handling characters with the high-bit set. For ascii characters,
195
we just lookup the replacement in the dictionary. For everything else, we
196
decode back into Unicode, and then use the XML escape code.
199
return _map[match.group().decode('ascii', 'replace')].encode()
201
return b''.join(b'&#%d;' % ord(uni_chr)
202
for uni_chr in match.group().decode('utf8'))
208
def encode_and_escape(unicode_or_utf8_str, _map=_to_escaped_map):
209
"""Encode the string into utf8, and escape invalid XML characters"""
210
# We frequently get entities we have not seen before, so it is better
211
# to check if None, rather than try/KeyError
212
text = _map.get(unicode_or_utf8_str)
214
if isinstance(unicode_or_utf8_str, text_type):
215
# The alternative policy is to do a regular UTF8 encoding
216
# and then escape only XML meta characters.
217
# Performance is equivalent once you use cache_utf8. *However*
218
# this makes the serialized texts incompatible with old versions
219
# of bzr. So no net gain. (Perhaps the read code would handle utf8
220
# better than entity escapes, but cElementTree seems to do just
222
text = _unicode_re.sub(
223
_unicode_escape_replace, unicode_or_utf8_str).encode() + b'"'
225
# Plain strings are considered to already be in utf-8 so we do a
226
# slightly different method for escaping.
227
text = _utf8_re.sub(_utf8_escape_replace,
228
unicode_or_utf8_str) + b'"'
229
_map[unicode_or_utf8_str] = text
234
"""Clean out the unicode => escaped map"""
235
_to_escaped_map.clear()
238
def unpack_inventory_entry(elt, entry_cache=None, return_from_cache=False):
240
file_id = elt_get('file_id')
241
revision = elt_get('revision')
242
# Check and see if we have already unpacked this exact entry
243
# Some timings for "repo.revision_trees(last_100_revs)"
245
# unmodified 4.1s 40.8s
247
# using fifo 2.83s 29.1s
251
# no_copy 2.00s 20.5s
252
# no_c,dict 1.95s 18.0s
253
# Note that a cache of 10k nodes is more than sufficient to hold all of
254
# the inventory for the last 100 revs for bzr, but not for mysql (20k
255
# is enough for mysql, which saves the same 2s as using a dict)
257
# Breakdown of mysql using time.clock()
258
# 4.1s 2 calls to element.get for file_id, revision_id
259
# 4.5s cache_hit lookup
260
# 7.1s InventoryFile.copy()
261
# 2.4s InventoryDirectory.copy()
262
# 0.4s decoding unique entries
263
# 1.6s decoding entries after FIFO fills up
264
# 0.8s Adding nodes to FIFO (including flushes)
265
# 0.1s cache miss lookups
267
# 4.1s 2 calls to element.get for file_id, revision_id
268
# 9.9s cache_hit lookup
269
# 10.8s InventoryEntry.copy()
270
# 0.3s cache miss lookus
271
# 1.2s decoding entries
272
# 1.0s adding nodes to LRU
273
if entry_cache is not None and revision is not None:
274
key = (file_id, revision)
276
# We copy it, because some operations may mutate it
277
cached_ie = entry_cache[key]
281
# Only copying directory entries drops us 2.85s => 2.35s
282
if return_from_cache:
283
if cached_ie.kind == 'directory':
284
return cached_ie.copy()
286
return cached_ie.copy()
289
if not inventory.InventoryEntry.versionable_kind(kind):
290
raise AssertionError('unsupported entry kind %s' % kind)
292
file_id = get_utf8_or_ascii(file_id)
293
if revision is not None:
294
revision = get_utf8_or_ascii(revision)
295
parent_id = elt_get('parent_id')
296
if parent_id is not None:
297
parent_id = get_utf8_or_ascii(parent_id)
299
if kind == 'directory':
300
ie = inventory.InventoryDirectory(file_id,
304
ie = inventory.InventoryFile(file_id,
307
ie.text_sha1 = elt_get('text_sha1')
308
if ie.text_sha1 is not None:
309
ie.text_sha1 = ie.text_sha1.encode('ascii')
310
if elt_get('executable') == 'yes':
312
v = elt_get('text_size')
313
ie.text_size = v and int(v)
314
elif kind == 'symlink':
315
ie = inventory.InventoryLink(file_id,
318
ie.symlink_target = elt_get('symlink_target')
319
elif kind == 'tree-reference':
320
file_id = get_utf8_or_ascii(elt.attrib['file_id'])
321
name = elt.attrib['name']
322
parent_id = get_utf8_or_ascii(elt.attrib['parent_id'])
323
revision = get_utf8_or_ascii(elt.get('revision'))
324
reference_revision = get_utf8_or_ascii(elt.get('reference_revision'))
325
ie = inventory.TreeReference(file_id, name, parent_id, revision,
328
raise errors.UnsupportedInventoryKind(kind)
329
ie.revision = revision
330
if revision is not None and entry_cache is not None:
331
# We cache a copy() because callers like to mutate objects, and
332
# that would cause the item in cache to mutate as well.
333
# This has a small effect on many-inventory performance, because
334
# the majority fraction is spent in cache hits, not misses.
335
entry_cache[key] = ie.copy()
340
def unpack_inventory_flat(elt, format_num, unpack_entry,
341
entry_cache=None, return_from_cache=False):
342
"""Unpack a flat XML inventory.
344
:param elt: XML element for the inventory
345
:param format_num: Expected format number
346
:param unpack_entry: Function for unpacking inventory entries
347
:return: An inventory
348
:raise UnexpectedInventoryFormat: When unexpected elements or data is
351
if elt.tag != 'inventory':
352
raise errors.UnexpectedInventoryFormat('Root tag is %r' % elt.tag)
353
format = elt.get('format')
354
if ((format is None and format_num is not None) or
355
format.encode() != format_num):
356
raise errors.UnexpectedInventoryFormat('Invalid format version %r'
358
revision_id = elt.get('revision_id')
359
if revision_id is not None:
360
revision_id = cache_utf8.encode(revision_id)
361
inv = inventory.Inventory(root_id=None, revision_id=revision_id)
363
ie = unpack_entry(e, entry_cache, return_from_cache)
368
def serialize_inventory_flat(inv, append, root_id, supported_kinds, working):
369
"""Serialize an inventory to a flat XML file.
371
:param inv: Inventory to serialize
372
:param append: Function for writing a line of output
373
:param working: If True skip history data - text_sha1, text_size,
374
reference_revision, symlink_target. self._check_revisions(inv)
376
entries = inv.iter_entries()
378
root_path, root_ie = next(entries)
379
for path, ie in entries:
380
if ie.parent_id != root_id:
381
parent_str = b' parent_id="'
382
parent_id = encode_and_escape(ie.parent_id)
386
if ie.kind == 'file':
388
executable = b' executable="yes"'
392
append(b'<file%s file_id="%s name="%s%s%s revision="%s '
393
b'text_sha1="%s" text_size="%d" />\n' % (
394
executable, encode_and_escape(ie.file_id),
395
encode_and_escape(ie.name), parent_str, parent_id,
396
encode_and_escape(ie.revision), ie.text_sha1,
399
append(b'<file%s file_id="%s name="%s%s%s />\n' % (
400
executable, encode_and_escape(ie.file_id),
401
encode_and_escape(ie.name), parent_str, parent_id))
402
elif ie.kind == 'directory':
404
append(b'<directory file_id="%s name="%s%s%s revision="%s '
406
encode_and_escape(ie.file_id),
407
encode_and_escape(ie.name),
408
parent_str, parent_id,
409
encode_and_escape(ie.revision)))
411
append(b'<directory file_id="%s name="%s%s%s />\n' % (
412
encode_and_escape(ie.file_id),
413
encode_and_escape(ie.name),
414
parent_str, parent_id))
415
elif ie.kind == 'symlink':
417
append(b'<symlink file_id="%s name="%s%s%s revision="%s '
418
b'symlink_target="%s />\n' % (
419
encode_and_escape(ie.file_id),
420
encode_and_escape(ie.name),
421
parent_str, parent_id,
422
encode_and_escape(ie.revision),
423
encode_and_escape(ie.symlink_target)))
425
append(b'<symlink file_id="%s name="%s%s%s />\n' % (
426
encode_and_escape(ie.file_id),
427
encode_and_escape(ie.name),
428
parent_str, parent_id))
429
elif ie.kind == 'tree-reference':
430
if ie.kind not in supported_kinds:
431
raise errors.UnsupportedInventoryKind(ie.kind)
433
append(b'<tree-reference file_id="%s name="%s%s%s '
434
b'revision="%s reference_revision="%s />\n' % (
435
encode_and_escape(ie.file_id),
436
encode_and_escape(ie.name),
437
parent_str, parent_id,
438
encode_and_escape(ie.revision),
439
encode_and_escape(ie.reference_revision)))
441
append(b'<tree-reference file_id="%s name="%s%s%s />\n' % (
442
encode_and_escape(ie.file_id),
443
encode_and_escape(ie.name),
444
parent_str, parent_id))
446
raise errors.UnsupportedInventoryKind(ie.kind)
447
append(b'</inventory>\n')
191
lambda match: match.group(0).encode('unicode_escape'),