/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/xml.py

  • Committer: Martin Pool
  • Date: 2005-06-28 03:02:31 UTC
  • Revision ID: mbp@sourcefrog.net-20050628030231-d311e4ebcd467ef4
Merge John's import-speedup branch:

                                                                                         
  777 John Arbash Meinel <john@arbash-meinel.com>       Sun 2005-06-26 22:20:32 -0500
      revision-id: john@arbash-meinel.com-20050627032031-e82a50db3863b18e
      bzr selftest was not using the correct bzr

  776 John Arbash Meinel <john@arbash-meinel.com>       Sun 2005-06-26 22:20:22 -0500
      revision-id: john@arbash-meinel.com-20050627032021-c9f21fde989ddaee
      Add was using an old mutter

  775 John Arbash Meinel <john@arbash-meinel.com>       Sun 2005-06-26 22:02:33 -0500
      revision-id: john@arbash-meinel.com-20050627030233-9165cfe98fc63298
      Cleaned up to be less different

  774 John Arbash Meinel <john@arbash-meinel.com>       Sun 2005-06-26 21:54:53 -0500
      revision-id: john@arbash-meinel.com-20050627025452-4260d0e744edef43
      Allow BZR_PLUGIN_PATH='' to negate plugin loading.

  773 John Arbash Meinel <john@arbash-meinel.com>       Sun 2005-06-26 21:49:34 -0500
      revision-id: john@arbash-meinel.com-20050627024933-b7158f67b7b9eae5
      Finished the previous cleanup (allowing load_plugins to be called twice)

  772 John Arbash Meinel <john@arbash-meinel.com>       Sun 2005-06-26 21:45:08 -0500
      revision-id: john@arbash-meinel.com-20050627024508-723b1df510d196fc
      Work on making the tests pass. versioning.py is calling run_cmd directly, but plugins have been loaded.

  771 John Arbash Meinel <john@arbash-meinel.com>       Sun 2005-06-26 21:32:29 -0500
      revision-id: john@arbash-meinel.com-20050627023228-79972744d7c53e15
      Got it down a little bit more by removing import of tree and inventory.

  770 John Arbash Meinel <john@arbash-meinel.com>       Sun 2005-06-26 21:26:05 -0500
      revision-id: john@arbash-meinel.com-20050627022604-350b9773ef622f95
      Reducing the number of import from bzrlib/__init__.py and bzrlib/branch.py

  769 John Arbash Meinel <john@arbash-meinel.com>       Sun 2005-06-26 20:32:25 -0500
      revision-id: john@arbash-meinel.com-20050627013225-32dd044f10d23948
      Updated revision.py and xml.py to include SubElement.

  768 John Arbash Meinel <john@arbash-meinel.com>       Sun 2005-06-26 20:03:56 -0500
      revision-id: john@arbash-meinel.com-20050627010356-ee66919e1c377faf
      Minor typo

  767 John Arbash Meinel <john@arbash-meinel.com>       Sun 2005-06-26 20:03:13 -0500
      revision-id: john@arbash-meinel.com-20050627010312-40d024007eb85051
      Caching the import

  766 John Arbash Meinel <john@arbash-meinel.com>       Sun 2005-06-26 19:51:47 -0500
      revision-id: john@arbash-meinel.com-20050627005147-5281c99e48ed1834
      Created wrapper functions for lazy import of ElementTree

  765 John Arbash Meinel <john@arbash-meinel.com>       Sun 2005-06-26 19:46:37 -0500
      revision-id: john@arbash-meinel.com-20050627004636-bf432902004a94c5
      Removed all of the test imports of cElementTree

  764 John Arbash Meinel <john@arbash-meinel.com>       Sun 2005-06-26 19:43:59 -0500
      revision-id: john@arbash-meinel.com-20050627004358-d137fbe9570dd71b
      Trying to make bzr startup faster.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
2
 
#
 
1
#! /usr/bin/env python
 
2
# -*- coding: UTF-8 -*-
 
3
 
3
4
# This program is free software; you can redistribute it and/or modify
4
5
# it under the terms of the GNU General Public License as published by
5
6
# the Free Software Foundation; either version 2 of the License, or
6
7
# (at your option) any later version.
7
 
#
 
8
 
8
9
# This program is distributed in the hope that it will be useful,
9
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
12
# GNU General Public License for more details.
12
 
#
 
13
 
13
14
# You should have received a copy of the GNU General Public License
14
15
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
 
17
18
"""XML externalization support."""
18
19
 
19
20
# "XML is like violence: if it doesn't solve your problem, you aren't
20
21
# using enough of it." -- various
21
22
 
22
 
# importing this module is fairly slow because it has to load several
23
 
# ElementTree bits
24
 
 
25
 
from bzrlib.serializer import Serializer
26
 
from bzrlib.trace import mutter
27
 
 
28
 
try:
29
 
    try:
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
34
 
    except ImportError:
35
 
        from cElementTree import (ElementTree, SubElement, Element,
36
 
                                  XMLTreeBuilder, fromstring, tostring)
37
 
        import elementtree.ElementTree
38
 
    ParseError = SyntaxError
39
 
except ImportError:
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,
45
 
                                              fromstring, tostring)
46
 
    import util.elementtree as elementtree
47
 
    from xml.parsers.expat import ExpatError as ParseError
48
 
 
49
 
from bzrlib import errors
50
 
 
51
 
 
52
 
class XMLSerializer(Serializer):
53
 
    """Abstract XML object serialize/deserialize"""
54
 
 
55
 
    squashes_xml_invalid_characters = True
56
 
 
57
 
    def read_inventory_from_string(self, xml_string, revision_id=None,
58
 
                                   entry_cache=None, return_from_cache=False):
59
 
        """Read xml_string into an inventory object.
60
 
 
61
 
        :param xml_string: The xml to read.
62
 
        :param revision_id: If not-None, the expected revision id of the
63
 
            inventory. Some serialisers use this to set the results' root
64
 
            revision. This should be supplied for deserialising all
65
 
            from-repository inventories so that xml5 inventories that were
66
 
            serialised without a revision identifier can be given the right
67
 
            revision id (but not for working tree inventories where users can
68
 
            edit the data without triggering checksum errors or anything).
69
 
        :param entry_cache: An optional cache of InventoryEntry objects. If
70
 
            supplied we will look up entries via (file_id, revision_id) which
71
 
            should map to a valid InventoryEntry (File/Directory/etc) object.
72
 
        :param return_from_cache: Return entries directly from the cache,
73
 
            rather than copying them first. This is only safe if the caller
74
 
            promises not to mutate the returned inventory entries, but it can
75
 
            make some operations significantly faster.
76
 
        """
77
 
        try:
78
 
            return self._unpack_inventory(fromstring(xml_string), revision_id,
79
 
                                          entry_cache=entry_cache,
80
 
                                          return_from_cache=return_from_cache)
81
 
        except ParseError, e:
82
 
            raise errors.UnexpectedInventoryFormat(e)
83
 
 
84
 
    def read_inventory(self, f, revision_id=None):
85
 
        try:
86
 
            return self._unpack_inventory(self._read_element(f),
87
 
                revision_id=None)
88
 
        except ParseError, e:
89
 
            raise errors.UnexpectedInventoryFormat(e)
90
 
 
91
 
    def write_revision(self, rev, f):
92
 
        self._write_element(self._pack_revision(rev), f)
93
 
 
94
 
    def write_revision_to_string(self, rev):
95
 
        return tostring(self._pack_revision(rev)) + '\n'
96
 
 
97
 
    def read_revision(self, f):
98
 
        return self._unpack_revision(self._read_element(f))
99
 
 
100
 
    def read_revision_from_string(self, xml_string):
101
 
        return self._unpack_revision(fromstring(xml_string))
102
 
 
103
 
    def _write_element(self, elt, f):
104
 
        ElementTree(elt).write(f, 'utf-8')
 
23
 
 
24
__copyright__ = "Copyright (C) 2005 Canonical Ltd."
 
25
__author__ = "Martin Pool <mbp@canonical.com>"
 
26
 
 
27
_ElementTree = None
 
28
def ElementTree(*args, **kwargs):
 
29
    global _ElementTree
 
30
    if _ElementTree is None:
 
31
        try:
 
32
            from cElementTree import ElementTree
 
33
        except ImportError:
 
34
            from elementtree.ElementTree import ElementTree
 
35
        _ElementTree = ElementTree
 
36
    return _ElementTree(*args, **kwargs)
 
37
 
 
38
_Element = None
 
39
def Element(*args, **kwargs):
 
40
    global _Element
 
41
    if _Element is None:
 
42
        try:
 
43
            from cElementTree import Element
 
44
        except ImportError:
 
45
            from elementtree.ElementTree import Element
 
46
        _Element = Element
 
47
    return _Element(*args, **kwargs)
 
48
 
 
49
 
 
50
_SubElement = None
 
51
def SubElement(*args, **kwargs):
 
52
    global _SubElement
 
53
    if _SubElement is None:
 
54
        try:
 
55
            from cElementTree import SubElement
 
56
        except ImportError:
 
57
            from elementtree.ElementTree import SubElement
 
58
        _SubElement = SubElement
 
59
    return _SubElement(*args, **kwargs)
 
60
 
 
61
 
 
62
import os, time
 
63
from trace import mutter
 
64
 
 
65
class XMLMixin:
 
66
    def to_element(self):
 
67
        raise Exception("XMLMixin.to_element must be overridden in concrete classes")
 
68
    
 
69
    def write_xml(self, f):
 
70
        ElementTree(self.to_element()).write(f, 'utf-8')
105
71
        f.write('\n')
106
72
 
107
 
    def _read_element(self, f):
108
 
        return ElementTree().parse(f)
109
 
 
110
 
 
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.
114
 
import re
115
 
escape_re = re.compile("[&'\"<>]")
116
 
escape_map = {
117
 
    "&":'&amp;',
118
 
    "'":"&apos;", # FIXME: overkill
119
 
    "\"":"&quot;",
120
 
    "<":"&lt;",
121
 
    ">":"&gt;",
122
 
    }
123
 
def _escape_replace(match, map=escape_map):
124
 
    return map[match.group()]
125
 
 
126
 
def _escape_attrib(text, encoding=None, replace=None):
127
 
    # escape attribute value
128
 
    try:
129
 
        if encoding:
130
 
            try:
131
 
                text = elementtree.ElementTree._encode(text, encoding)
132
 
            except UnicodeError:
133
 
                return elementtree.ElementTree._encode_entity(text)
134
 
        if replace is None:
135
 
            return escape_re.sub(_escape_replace, text)
136
 
        else:
137
 
            text = replace(text, "&", "&amp;")
138
 
            text = replace(text, "'", "&apos;") # FIXME: overkill
139
 
            text = replace(text, "\"", "&quot;")
140
 
            text = replace(text, "<", "&lt;")
141
 
            text = replace(text, ">", "&gt;")
142
 
            return text
143
 
    except (TypeError, AttributeError):
144
 
        elementtree.ElementTree._raise_serialization_error(text)
145
 
 
146
 
elementtree.ElementTree._escape_attrib = _escape_attrib
147
 
 
148
 
escape_cdata_re = re.compile("[&<>]")
149
 
escape_cdata_map = {
150
 
    "&":'&amp;',
151
 
    "<":"&lt;",
152
 
    ">":"&gt;",
153
 
    }
154
 
def _escape_cdata_replace(match, map=escape_cdata_map):
155
 
    return map[match.group()]
156
 
 
157
 
def _escape_cdata(text, encoding=None, replace=None):
158
 
    # escape character data
159
 
    try:
160
 
        if encoding:
161
 
            try:
162
 
                text = elementtree.ElementTree._encode(text, encoding)
163
 
            except UnicodeError:
164
 
                return elementtree.ElementTree._encode_entity(text)
165
 
        if replace is None:
166
 
            return escape_cdata_re.sub(_escape_cdata_replace, text)
167
 
        else:
168
 
            text = replace(text, "&", "&amp;")
169
 
            text = replace(text, "<", "&lt;")
170
 
            text = replace(text, ">", "&gt;")
171
 
            return text
172
 
    except (TypeError, AttributeError):
173
 
        elementtree.ElementTree._raise_serialization_error(text)
174
 
 
175
 
elementtree.ElementTree._escape_cdata = _escape_cdata
176
 
 
177
 
 
178
 
def escape_invalid_chars(message):
179
 
    """Escape the XML-invalid characters in a commit message.
180
 
 
181
 
    :param message: Commit message to escape
182
 
    :return: tuple with escaped message and number of characters escaped
183
 
    """
184
 
    if message is None:
185
 
        return None, 0
186
 
    # Python strings can include characters that can't be
187
 
    # represented in well-formed XML; escape characters that
188
 
    # aren't listed in the XML specification
189
 
    # (http://www.w3.org/TR/REC-xml/#NT-Char).
190
 
    return re.subn(u'[^\x09\x0A\x0D\u0020-\uD7FF\uE000-\uFFFD]+',
191
 
            lambda match: match.group(0).encode('unicode_escape'),
192
 
            message)
 
73
    def read_xml(cls, f):
 
74
        return cls.from_element(ElementTree().parse(f))
 
75
 
 
76
    read_xml = classmethod(read_xml)
 
77