~bzr-pqm/bzr/bzr.dev

2052.3.1 by John Arbash Meinel
Add tests to cleanup the copyright of all source files
1
# Copyright (C) 2005, 2006 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1 by mbp at sourcefrog
import from baz patch-364
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1 by mbp at sourcefrog
import from baz patch-364
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1 by mbp at sourcefrog
import from baz patch-364
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
"""XML externalization support."""
18
48 by Martin Pool
witty comment
19
# "XML is like violence: if it doesn't solve your problem, you aren't
20
# using enough of it." -- various
21
1180 by Martin Pool
- start splitting code for xml (de)serialization away from objects
22
# importing this module is fairly slow because it has to load several
23
# ElementTree bits
24
1248 by Martin Pool
- new weave based cleanup [broken]
25
from bzrlib.trace import mutter, warning
26
802 by Martin Pool
- Remove XMLMixin class in favour of simple pack_xml, unpack_xml functions
27
try:
2039.2.1 by Martin Pool
Load python2.5's ElementTree if present
28
    try:
29
        # it's in this package in python2.5
30
        from xml.etree.cElementTree import (ElementTree, SubElement, Element,
31
            XMLTreeBuilder, fromstring, tostring)
32
        import xml.etree as elementtree
33
    except ImportError:
34
        from cElementTree import (ElementTree, SubElement, Element,
35
                                  XMLTreeBuilder, fromstring, tostring)
36
        import elementtree
2029.2.1 by Marien Zwart
Handle the different exception (non-c)ElementTree raises.
37
    ParseError = SyntaxError
802 by Martin Pool
- Remove XMLMixin class in favour of simple pack_xml, unpack_xml functions
38
except ImportError:
1185.33.68 by Martin Pool
Emit warning to trace file only if using cElementTree.
39
    mutter('WARNING: using slower ElementTree; consider installing cElementTree'
40
           " and make sure it's on your PYTHONPATH")
2039.2.1 by Martin Pool
Load python2.5's ElementTree if present
41
    # this copy is shipped with bzr
1227 by Martin Pool
- methods to deserialize objects from strings
42
    from util.elementtree.ElementTree import (ElementTree, SubElement,
1248 by Martin Pool
- new weave based cleanup [broken]
43
                                              Element, XMLTreeBuilder,
44
                                              fromstring, tostring)
1772.1.1 by mbp at sourcefrog
Fix up loading of fallback ElementTree
45
    import util.elementtree as elementtree
2029.2.1 by Marien Zwart
Handle the different exception (non-c)ElementTree raises.
46
    from xml.parsers.expat import ExpatError as ParseError
802 by Martin Pool
- Remove XMLMixin class in favour of simple pack_xml, unpack_xml functions
47
1910.2.31 by Aaron Bentley
Fix bugs in basis inventory handling, change filename
48
from bzrlib import errors
1180 by Martin Pool
- start splitting code for xml (de)serialization away from objects
49
50
51
class Serializer(object):
52
    """Abstract object serialize/deserialize"""
53
    def write_inventory(self, inv, f):
54
        """Write inventory to a file"""
55
        elt = self._pack_inventory(inv)
56
        self._write_element(elt, f)
57
1248 by Martin Pool
- new weave based cleanup [broken]
58
    def write_inventory_to_string(self, inv):
1185.16.123 by Martin Pool
Fix syntax of serializer_v5.pack_revision_to_string
59
        return tostring(self._pack_inventory(inv)) + '\n'
1248 by Martin Pool
- new weave based cleanup [broken]
60
1227 by Martin Pool
- methods to deserialize objects from strings
61
    def read_inventory_from_string(self, xml_string):
1910.2.31 by Aaron Bentley
Fix bugs in basis inventory handling, change filename
62
        try:
63
            return self._unpack_inventory(fromstring(xml_string))
2029.2.1 by Marien Zwart
Handle the different exception (non-c)ElementTree raises.
64
        except ParseError, e:
1910.2.31 by Aaron Bentley
Fix bugs in basis inventory handling, change filename
65
            raise errors.UnexpectedInventoryFormat(e)
1227 by Martin Pool
- methods to deserialize objects from strings
66
1180 by Martin Pool
- start splitting code for xml (de)serialization away from objects
67
    def read_inventory(self, f):
1910.2.31 by Aaron Bentley
Fix bugs in basis inventory handling, change filename
68
        try:
69
            return self._unpack_inventory(self._read_element(f))
2029.2.1 by Marien Zwart
Handle the different exception (non-c)ElementTree raises.
70
        except ParseError, e:
1910.2.31 by Aaron Bentley
Fix bugs in basis inventory handling, change filename
71
            raise errors.UnexpectedInventoryFormat(e)
1180 by Martin Pool
- start splitting code for xml (de)serialization away from objects
72
1182 by Martin Pool
- more disentangling of xml storage format from objects
73
    def write_revision(self, rev, f):
74
        self._write_element(self._pack_revision(rev), f)
75
1248 by Martin Pool
- new weave based cleanup [broken]
76
    def write_revision_to_string(self, rev):
1185.16.123 by Martin Pool
Fix syntax of serializer_v5.pack_revision_to_string
77
        return tostring(self._pack_revision(rev)) + '\n'
1248 by Martin Pool
- new weave based cleanup [broken]
78
1182 by Martin Pool
- more disentangling of xml storage format from objects
79
    def read_revision(self, f):
80
        return self._unpack_revision(self._read_element(f))
81
1227 by Martin Pool
- methods to deserialize objects from strings
82
    def read_revision_from_string(self, xml_string):
1248 by Martin Pool
- new weave based cleanup [broken]
83
        return self._unpack_revision(fromstring(xml_string))
1227 by Martin Pool
- methods to deserialize objects from strings
84
1180 by Martin Pool
- start splitting code for xml (de)serialization away from objects
85
    def _write_element(self, elt, f):
86
        ElementTree(elt).write(f, 'utf-8')
87
        f.write('\n')
88
89
    def _read_element(self, f):
90
        return ElementTree().parse(f)
1713.1.12 by Robert Collins
Improve serialisation of xml performance by overriding elementree's escape routines.
91
92
1772.1.1 by mbp at sourcefrog
Fix up loading of fallback ElementTree
93
# performance tuning for elementree's serialiser. This should be
1713.1.14 by Robert Collins
Review feedback.
94
# sent upstream - RBC 20060523.
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
95
# the functions here are patched into elementtree at runtime.
1713.1.12 by Robert Collins
Improve serialisation of xml performance by overriding elementree's escape routines.
96
import re
1713.1.14 by Robert Collins
Review feedback.
97
escape_re = re.compile("[&'\"<>]")
1713.1.12 by Robert Collins
Improve serialisation of xml performance by overriding elementree's escape routines.
98
escape_map = {
99
    "&":'&amp;',
100
    "'":"&apos;", # FIXME: overkill
101
    "\"":"&quot;",
102
    "<":"&lt;",
103
    ">":"&gt;",
104
    }
105
def _escape_replace(match, map=escape_map):
106
    return map[match.group()]
107
 
108
def _escape_attrib(text, encoding=None, replace=None):
109
    # escape attribute value
110
    try:
111
        if encoding:
112
            try:
113
                text = elementtree.ElementTree._encode(text, encoding)
114
            except UnicodeError:
115
                return elementtree.ElementTree._encode_entity(text)
116
        if replace is None:
117
            return escape_re.sub(_escape_replace, text)
118
        else:
119
            text = replace(text, "&", "&amp;")
120
            text = replace(text, "'", "&apos;") # FIXME: overkill
121
            text = replace(text, "\"", "&quot;")
122
            text = replace(text, "<", "&lt;")
123
            text = replace(text, ">", "&gt;")
124
            return text
125
    except (TypeError, AttributeError):
126
        elementtree.ElementTree._raise_serialization_error(text)
127
128
elementtree.ElementTree._escape_attrib = _escape_attrib
129
1713.1.14 by Robert Collins
Review feedback.
130
escape_cdata_re = re.compile("[&<>]")
1713.1.12 by Robert Collins
Improve serialisation of xml performance by overriding elementree's escape routines.
131
escape_cdata_map = {
132
    "&":'&amp;',
133
    "<":"&lt;",
134
    ">":"&gt;",
135
    }
136
def _escape_cdata_replace(match, map=escape_cdata_map):
137
    return map[match.group()]
138
 
139
def _escape_cdata(text, encoding=None, replace=None):
140
    # escape character data
141
    try:
142
        if encoding:
143
            try:
144
                text = elementtree.ElementTree._encode(text, encoding)
145
            except UnicodeError:
146
                return elementtree.ElementTree._encode_entity(text)
147
        if replace is None:
148
            return escape_cdata_re.sub(_escape_cdata_replace, text)
149
        else:
150
            text = replace(text, "&", "&amp;")
151
            text = replace(text, "<", "&lt;")
152
            text = replace(text, ">", "&gt;")
153
            return text
154
    except (TypeError, AttributeError):
155
        elementtree.ElementTree._raise_serialization_error(text)
156
157
elementtree.ElementTree._escape_cdata = _escape_cdata