/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1 by mbp at sourcefrog
import from baz patch-364
1
#! /usr/bin/env python
2
# -*- coding: UTF-8 -*-
3
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
8
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17
18
"""XML externalization support."""
19
48 by Martin Pool
witty comment
20
# "XML is like violence: if it doesn't solve your problem, you aren't
21
# using enough of it." -- various
22
1180 by Martin Pool
- start splitting code for xml (de)serialization away from objects
23
# importing this module is fairly slow because it has to load several
24
# ElementTree bits
25
802 by Martin Pool
- Remove XMLMixin class in favour of simple pack_xml, unpack_xml functions
26
try:
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
27
    from util.cElementTree import ElementTree, SubElement, Element
802 by Martin Pool
- Remove XMLMixin class in favour of simple pack_xml, unpack_xml functions
28
except ImportError:
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
29
    from util.elementtree.ElementTree import ElementTree, SubElement, Element
802 by Martin Pool
- Remove XMLMixin class in favour of simple pack_xml, unpack_xml functions
30
1180 by Martin Pool
- start splitting code for xml (de)serialization away from objects
31
from bzrlib.inventory import ROOT_ID, Inventory, InventoryEntry
1182 by Martin Pool
- more disentangling of xml storage format from objects
32
from bzrlib.revision import Revision, RevisionReference        
1180 by Martin Pool
- start splitting code for xml (de)serialization away from objects
33
34
35
class Serializer(object):
36
    """Abstract object serialize/deserialize"""
37
    def write_inventory(self, inv, f):
38
        """Write inventory to a file"""
39
        elt = self._pack_inventory(inv)
40
        self._write_element(elt, f)
41
42
    def read_inventory(self, f):
43
        return self._unpack_inventory(self._read_element(f))
44
1182 by Martin Pool
- more disentangling of xml storage format from objects
45
    def write_revision(self, rev, f):
46
        self._write_element(self._pack_revision(rev), f)
47
48
    def read_revision(self, f):
49
        return self._unpack_revision(self._read_element(f))
50
1180 by Martin Pool
- start splitting code for xml (de)serialization away from objects
51
    def _write_element(self, elt, f):
52
        ElementTree(elt).write(f, 'utf-8')
53
        f.write('\n')
54
55
    def _read_element(self, f):
56
        return ElementTree().parse(f)
57
58
59
60
class _Serializer_v4(Serializer):
61
    """Version 0.0.4 serializer"""
62
    
63
    __slots__ = []
64
    
65
    def _pack_inventory(self, inv):
66
        """Convert to XML Element"""
67
        e = Element('inventory')
68
        e.text = '\n'
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))
73
        return e
74
75
76
    def _pack_entry(self, ie):
77
        """Convert InventoryEntry to XML element"""
78
        e = Element('entry')
79
        e.set('name', ie.name)
80
        e.set('file_id', ie.file_id)
81
        e.set('kind', ie.kind)
82
83
        if ie.text_size != None:
84
            e.set('text_size', '%d' % ie.text_size)
85
86
        for f in ['text_id', 'text_sha1']:
87
            v = getattr(ie, f)
88
            if v != None:
89
                e.set(f, v)
90
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)
97
98
        e.tail = '\n'
99
100
        return e
101
102
103
    def _unpack_inventory(self, elt):
104
        """Construct from XML Element
105
        """
106
        assert elt.tag == 'inventory'
107
        root_id = elt.get('file_id') or ROOT_ID
108
        inv = Inventory(root_id)
109
        for e in elt:
110
            ie = self._unpack_entry(e)
111
            if ie.parent_id == ROOT_ID:
112
                ie.parent_id = root_id
113
            inv.add(ie)
114
        return inv
115
116
117
    def _unpack_entry(self, elt):
118
        assert elt.tag == 'entry'
119
120
        ## original format inventories don't have a parent_id for
121
        ## nodes in the root directory, but it's cleaner to use one
122
        ## internally.
123
        parent_id = elt.get('parent_id')
124
        if parent_id == None:
125
            parent_id = ROOT_ID
126
127
        ie = InventoryEntry(elt.get('file_id'),
128
                              elt.get('name'),
129
                              elt.get('kind'),
130
                              parent_id)
131
        ie.text_id = elt.get('text_id')
132
        ie.text_sha1 = elt.get('text_sha1')
133
134
        ## mutter("read inventoryentry: %r" % (elt.attrib))
135
136
        v = elt.get('text_size')
137
        ie.text_size = v and int(v)
138
139
        return ie
140
141
1182 by Martin Pool
- more disentangling of xml storage format from objects
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,
150
                       )
151
        if rev.timezone:
152
            root.set('timezone', str(rev.timezone))
153
        root.text = '\n'
154
155
        msg = SubElement(root, 'message')
156
        msg.text = rev.message
157
        msg.tail = '\n'
158
159
        if rev.parents:
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')
165
                p.tail = '\n'
166
                assert rr.revision_id
167
                p.set('revision_id', rr.revision_id)
168
                if rr.revision_sha1:
169
                    p.set('revision_sha1', rr.revision_sha1)
170
171
        return root
172
173
    
174
    def _unpack_revision(self, elt):
175
        """XML Element -> Revision object"""
176
        
177
        # <changeset> is deprecated...
178
        if elt.tag not in ('revision', 'changeset'):
179
            raise bzrlib.errors.BzrError("unexpected tag in revision file: %r" % elt)
180
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')
186
                       )
187
188
        precursor = elt.get('precursor')
189
        precursor_sha1 = elt.get('precursor_sha1')
190
191
        pelts = elt.find('parents')
192
193
        if pelts:
194
            for p in pelts:
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)
200
201
            if precursor:
202
                # must be consistent
203
                prec_parent = rev.parents[0].revision_id
204
                assert prec_parent == precursor
205
        elif 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)
210
211
        v = elt.get('timezone')
212
        rev.timezone = v and int(v)
213
214
        rev.message = elt.findtext('message') # text of <message>
215
        return rev
216
217
218
1180 by Martin Pool
- start splitting code for xml (de)serialization away from objects
219
"""singleton instance"""
220
serializer_v4 = _Serializer_v4()