~bzr-pqm/bzr/bzr.dev

2052.3.2 by John Arbash Meinel
Change Copyright .. by Canonical to Copyright ... Canonical
1
# Copyright (C) 2006 Canonical Ltd
1711.3.2 by John Arbash Meinel
Add the read_bundle_from_url command, which handles lots of exceptions
2
#
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.
7
#
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.
12
#
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1711.3.2 by John Arbash Meinel
Add the read_bundle_from_url command, which handles lots of exceptions
16
17
"""Read in a bundle stream, and process it into a BundleReader object."""
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
18
1185.82.96 by Aaron Bentley
Got first binary test passing
19
import base64
1185.82.78 by Aaron Bentley
Cleanups
20
from cStringIO import StringIO
0.5.115 by John Arbash Meinel
Getting closer to being able to read back the changesets, still broken, though.
21
import os
22
import pprint
23
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
24
from bzrlib import (
25
    osutils,
2520.4.33 by Aaron Bentley
remove test dependencies on serialization minutia
26
    timestamp,
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
27
    )
1711.3.2 by John Arbash Meinel
Add the read_bundle_from_url command, which handles lots of exceptions
28
import bzrlib.errors
1551.14.4 by Aaron Bentley
Change bundle reader and merge directive to both be 'mergeables'
29
from bzrlib.bundle import apply_bundle
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
30
from bzrlib.errors import (TestamentMismatch, BzrError,
1185.82.139 by Aaron Bentley
Raise NotABundle when a non-bundle is supplied
31
                           MalformedHeader, MalformedPatches, NotABundle)
0.5.116 by John Arbash Meinel
Fixed a bug based on the new InventoryEntry separation.
32
from bzrlib.inventory import (Inventory, InventoryEntry,
33
                              InventoryDirectory, InventoryFile,
1731.1.55 by Aaron Bentley
Fix bundle handling
34
                              InventoryLink)
1711.4.19 by John Arbash Meinel
Bundles were still using os.path.join to compute paths rather than osutils.pathjoin
35
from bzrlib.osutils import sha_file, sha_string, pathjoin
1185.82.78 by Aaron Bentley
Cleanups
36
from bzrlib.revision import Revision, NULL_REVISION
1185.82.116 by Aaron Bentley
Introduce StrictTestament, get test failing for the right reasons
37
from bzrlib.testament import StrictTestament
1185.82.78 by Aaron Bentley
Cleanups
38
from bzrlib.trace import mutter, warning
1711.3.2 by John Arbash Meinel
Add the read_bundle_from_url command, which handles lots of exceptions
39
import bzrlib.transport
1185.82.78 by Aaron Bentley
Cleanups
40
from bzrlib.tree import Tree
1711.3.2 by John Arbash Meinel
Add the read_bundle_from_url command, which handles lots of exceptions
41
import bzrlib.urlutils
1185.82.78 by Aaron Bentley
Cleanups
42
from bzrlib.xml5 import serializer_v5
0.5.115 by John Arbash Meinel
Getting closer to being able to read back the changesets, still broken, though.
43
0.5.57 by John Arbash Meinel
Simplified the header, only output base if it is not the expected one.
44
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
45
class RevisionInfo(object):
46
    """Gets filled out for each revision object that is read.
47
    """
0.5.115 by John Arbash Meinel
Getting closer to being able to read back the changesets, still broken, though.
48
    def __init__(self, revision_id):
49
        self.revision_id = revision_id
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
50
        self.sha1 = None
51
        self.committer = None
0.5.39 by John Arbash Meinel
(broken) Working on changing the processing to use a ChangesetTree.
52
        self.date = None
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
53
        self.timestamp = None
54
        self.timezone = None
55
        self.inventory_sha1 = None
56
1185.82.27 by Aaron Bentley
Fixed most revision attribute handling
57
        self.parent_ids = None
1185.82.74 by Aaron Bentley
Allow custom base for any revision
58
        self.base_id = None
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
59
        self.message = None
1185.82.27 by Aaron Bentley
Fixed most revision attribute handling
60
        self.properties = None
1185.82.77 by Aaron Bentley
Move tree actions to RevisionInfo
61
        self.tree_actions = None
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
62
63
    def __str__(self):
64
        return pprint.pformat(self.__dict__)
65
0.5.37 by John Arbash Meinel
Made read_changeset able to spit out 'Revision' entities.
66
    def as_revision(self):
0.5.115 by John Arbash Meinel
Getting closer to being able to read back the changesets, still broken, though.
67
        rev = Revision(revision_id=self.revision_id,
0.5.37 by John Arbash Meinel
Made read_changeset able to spit out 'Revision' entities.
68
            committer=self.committer,
69
            timestamp=float(self.timestamp),
70
            timezone=int(self.timezone),
71
            inventory_sha1=self.inventory_sha1,
72
            message='\n'.join(self.message))
73
1185.82.28 by Aaron Bentley
Got parent_id handling working
74
        if self.parent_ids:
75
            rev.parent_ids.extend(self.parent_ids)
1185.82.35 by Aaron Bentley
Read revision properties
76
1185.82.59 by Aaron Bentley
Behave properly when there are no properties in a revision
77
        if self.properties:
78
            for property in self.properties:
79
                key_end = property.find(': ')
2447.1.2 by John Arbash Meinel
Add tests that we handle empty values whether they end in ': \n' or ':\n'.
80
                if key_end == -1:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
81
                    if not property.endswith(':'):
82
                        raise ValueError(property)
2447.1.2 by John Arbash Meinel
Add tests that we handle empty values whether they end in ': \n' or ':\n'.
83
                    key = str(property[:-1])
84
                    value = ''
85
                else:
2447.1.4 by John Arbash Meinel
Add a test that we properly round-trip unicode properties.
86
                    key = str(property[:key_end])
87
                    value = property[key_end+2:]
1185.82.59 by Aaron Bentley
Behave properly when there are no properties in a revision
88
                rev.properties[key] = value
1185.82.35 by Aaron Bentley
Read revision properties
89
0.5.37 by John Arbash Meinel
Made read_changeset able to spit out 'Revision' entities.
90
        return rev
91
2520.4.33 by Aaron Bentley
remove test dependencies on serialization minutia
92
    @staticmethod
93
    def from_revision(revision):
94
        revision_info = RevisionInfo(revision.revision_id)
95
        date = timestamp.format_highres_date(revision.timestamp,
96
                                             revision.timezone)
97
        revision_info.date = date
98
        revision_info.timezone = revision.timezone
99
        revision_info.timestamp = revision.timestamp
100
        revision_info.message = revision.message.split('\n')
101
        revision_info.properties = [': '.join(p) for p in
102
                                    revision.properties.iteritems()]
103
        return revision_info
104
1185.82.123 by Aaron Bentley
Cleanups to prepare for review
105
1185.82.130 by Aaron Bentley
Rename changesets to revision bundles
106
class BundleInfo(object):
0.5.55 by John Arbash Meinel
Lots of updates. Using a minimized annotations for changesets.
107
    """This contains the meta information. Stuff that allows you to
108
    recreate the revision or inventory XML.
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
109
    """
2520.4.35 by Aaron Bentley
zap obsolete changeset commands, add bundle-info command
110
    def __init__(self, bundle_format=None):
111
        self.bundle_format = None
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
112
        self.committer = None
113
        self.date = None
0.5.17 by John Arbash Meinel
adding apply-changset, plus more meta information.
114
        self.message = None
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
115
0.5.39 by John Arbash Meinel
(broken) Working on changing the processing to use a ChangesetTree.
116
        # A list of RevisionInfo objects
0.5.36 by John Arbash Meinel
Updated so that read_changeset is able to parse the output
117
        self.revisions = []
0.5.56 by John Arbash Meinel
A couple more fixups, it seems actually capable now of writing out a changeset, and reading it back.
118
119
        # The next entries are created during complete_info() and
120
        # other post-read functions.
121
122
        # A list of real Revision objects
123
        self.real_revisions = []
0.5.55 by John Arbash Meinel
Lots of updates. Using a minimized annotations for changesets.
124
125
        self.timestamp = None
126
        self.timezone = None
0.5.15 by John Arbash Meinel
Created an apply-changeset function, and modified output for better parsing.
127
2476.2.1 by John Arbash Meinel
Vastly improve bundle install performance by only validating the bundle one time
128
        # Have we checked the repository yet?
129
        self._validated_revisions_against_repo = False
130
0.5.7 by John Arbash Meinel
Added a bunch more information about changesets. Can now read back in all of the meta information.
131
    def __str__(self):
132
        return pprint.pformat(self.__dict__)
133
0.5.39 by John Arbash Meinel
(broken) Working on changing the processing to use a ChangesetTree.
134
    def complete_info(self):
135
        """This makes sure that all information is properly
136
        split up, based on the assumptions that can be made
137
        when information is missing.
138
        """
1551.12.29 by Aaron Bentley
Copy and extend patch date formatting code, add patch-date parsing
139
        from bzrlib.timestamp import unpack_highres_date
0.5.56 by John Arbash Meinel
A couple more fixups, it seems actually capable now of writing out a changeset, and reading it back.
140
        # Put in all of the guessable information.
0.5.55 by John Arbash Meinel
Lots of updates. Using a minimized annotations for changesets.
141
        if not self.timestamp and self.date:
0.5.81 by John Arbash Meinel
Cleaning up from pychecker.
142
            self.timestamp, self.timezone = unpack_highres_date(self.date)
0.5.55 by John Arbash Meinel
Lots of updates. Using a minimized annotations for changesets.
143
0.5.56 by John Arbash Meinel
A couple more fixups, it seems actually capable now of writing out a changeset, and reading it back.
144
        self.real_revisions = []
0.5.39 by John Arbash Meinel
(broken) Working on changing the processing to use a ChangesetTree.
145
        for rev in self.revisions:
0.5.60 by John Arbash Meinel
read_changeset now parses the date: subheader of revisions correctly.
146
            if rev.timestamp is None:
147
                if rev.date is not None:
148
                    rev.timestamp, rev.timezone = \
0.5.81 by John Arbash Meinel
Cleaning up from pychecker.
149
                            unpack_highres_date(rev.date)
0.5.60 by John Arbash Meinel
read_changeset now parses the date: subheader of revisions correctly.
150
                else:
151
                    rev.timestamp = self.timestamp
152
                    rev.timezone = self.timezone
0.5.55 by John Arbash Meinel
Lots of updates. Using a minimized annotations for changesets.
153
            if rev.message is None and self.message:
154
                rev.message = self.message
155
            if rev.committer is None and self.committer:
156
                rev.committer = self.committer
0.5.56 by John Arbash Meinel
A couple more fixups, it seems actually capable now of writing out a changeset, and reading it back.
157
            self.real_revisions.append(rev.as_revision())
158
1185.82.48 by Aaron Bentley
Inching closer to supporting multiple revisions per changeset
159
    def get_base(self, revision):
1185.82.74 by Aaron Bentley
Allow custom base for any revision
160
        revision_info = self.get_revision_info(revision.revision_id)
161
        if revision_info.base_id is not None:
3668.5.4 by Jelmer Vernooij
Eliminate more uses of Repository.revision_tree(None).
162
            return revision_info.base_id
1185.82.48 by Aaron Bentley
Inching closer to supporting multiple revisions per changeset
163
        if len(revision.parent_ids) == 0:
164
            # There is no base listed, and
165
            # the lowest revision doesn't have a parent
166
            # so this is probably against the empty tree
3668.5.4 by Jelmer Vernooij
Eliminate more uses of Repository.revision_tree(None).
167
            # and thus base truly is NULL_REVISION
168
            return NULL_REVISION
1185.82.48 by Aaron Bentley
Inching closer to supporting multiple revisions per changeset
169
        else:
1185.82.73 by Aaron Bentley
Use rightmost parent always
170
            return revision.parent_ids[-1]
0.5.56 by John Arbash Meinel
A couple more fixups, it seems actually capable now of writing out a changeset, and reading it back.
171
0.5.67 by John Arbash Meinel
Working on apply_changeset
172
    def _get_target(self):
0.5.81 by John Arbash Meinel
Cleaning up from pychecker.
173
        """Return the target revision."""
0.5.67 by John Arbash Meinel
Working on apply_changeset
174
        if len(self.real_revisions) > 0:
1185.82.48 by Aaron Bentley
Inching closer to supporting multiple revisions per changeset
175
            return self.real_revisions[0].revision_id
0.5.67 by John Arbash Meinel
Working on apply_changeset
176
        elif len(self.revisions) > 0:
1185.82.48 by Aaron Bentley
Inching closer to supporting multiple revisions per changeset
177
            return self.revisions[0].revision_id
0.5.67 by John Arbash Meinel
Working on apply_changeset
178
        return None
179
180
    target = property(_get_target, doc='The target revision id')
181
1185.82.49 by Aaron Bentley
SPOT fixes, fix inventory validation
182
    def get_revision(self, revision_id):
183
        for r in self.real_revisions:
184
            if r.revision_id == revision_id:
185
                return r
186
        raise KeyError(revision_id)
187
188
    def get_revision_info(self, revision_id):
189
        for r in self.revisions:
190
            if r.revision_id == revision_id:
191
                return r
192
        raise KeyError(revision_id)
193
1793.2.1 by Aaron Bentley
Move revision_tree into BundleInfo
194
    def revision_tree(self, repository, revision_id, base=None):
195
        revision = self.get_revision(revision_id)
196
        base = self.get_base(revision)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
197
        if base == revision_id:
198
            raise AssertionError()
2476.2.1 by John Arbash Meinel
Vastly improve bundle install performance by only validating the bundle one time
199
        if not self._validated_revisions_against_repo:
200
            self._validate_references_from_repository(repository)
1793.2.1 by Aaron Bentley
Move revision_tree into BundleInfo
201
        revision_info = self.get_revision_info(revision_id)
202
        inventory_revision_id = revision_id
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
203
        bundle_tree = BundleTree(repository.revision_tree(base),
1793.2.1 by Aaron Bentley
Move revision_tree into BundleInfo
204
                                  inventory_revision_id)
205
        self._update_tree(bundle_tree, revision_id)
206
207
        inv = bundle_tree.inventory
208
        self._validate_inventory(inv, revision_id)
209
        self._validate_revision(inv, revision_id)
210
211
        return bundle_tree
0.5.62 by John Arbash Meinel
Doing some internal validation before allowing processing to continue, additional checks at the command level.
212
1185.82.15 by Aaron Bentley
Disabled validate_revisions (needs info it doesn't have), updated API to repos
213
    def _validate_references_from_repository(self, repository):
214
        """Now that we have a repository which should have some of the
0.5.63 by John Arbash Meinel
Moving the validation into part of the reading.
215
        revisions we care about, go through and validate all of them
216
        that we can.
217
        """
218
        rev_to_sha = {}
0.5.64 by John Arbash Meinel
SUCCESS, we now are able to validate the inventory XML.
219
        inv_to_sha = {}
0.5.115 by John Arbash Meinel
Getting closer to being able to read back the changesets, still broken, though.
220
        def add_sha(d, revision_id, sha1):
221
            if revision_id is None:
0.5.63 by John Arbash Meinel
Moving the validation into part of the reading.
222
                if sha1 is not None:
223
                    raise BzrError('A Null revision should always'
224
                        'have a null sha1 hash')
225
                return
0.5.115 by John Arbash Meinel
Getting closer to being able to read back the changesets, still broken, though.
226
            if revision_id in d:
0.5.63 by John Arbash Meinel
Moving the validation into part of the reading.
227
                # This really should have been validated as part
228
                # of _validate_revisions but lets do it again
0.5.115 by John Arbash Meinel
Getting closer to being able to read back the changesets, still broken, though.
229
                if sha1 != d[revision_id]:
0.5.63 by John Arbash Meinel
Moving the validation into part of the reading.
230
                    raise BzrError('** Revision %r referenced with 2 different'
0.5.115 by John Arbash Meinel
Getting closer to being able to read back the changesets, still broken, though.
231
                            ' sha hashes %s != %s' % (revision_id,
232
                                sha1, d[revision_id]))
0.5.63 by John Arbash Meinel
Moving the validation into part of the reading.
233
            else:
0.5.115 by John Arbash Meinel
Getting closer to being able to read back the changesets, still broken, though.
234
                d[revision_id] = sha1
0.5.63 by John Arbash Meinel
Moving the validation into part of the reading.
235
236
        # All of the contained revisions were checked
237
        # in _validate_revisions
238
        checked = {}
1793.2.1 by Aaron Bentley
Move revision_tree into BundleInfo
239
        for rev_info in self.revisions:
0.5.115 by John Arbash Meinel
Getting closer to being able to read back the changesets, still broken, though.
240
            checked[rev_info.revision_id] = True
241
            add_sha(rev_to_sha, rev_info.revision_id, rev_info.sha1)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
242
1793.2.1 by Aaron Bentley
Move revision_tree into BundleInfo
243
        for (rev, rev_info) in zip(self.real_revisions, self.revisions):
0.5.115 by John Arbash Meinel
Getting closer to being able to read back the changesets, still broken, though.
244
            add_sha(inv_to_sha, rev_info.revision_id, rev_info.inventory_sha1)
0.5.63 by John Arbash Meinel
Moving the validation into part of the reading.
245
0.5.64 by John Arbash Meinel
SUCCESS, we now are able to validate the inventory XML.
246
        count = 0
0.5.63 by John Arbash Meinel
Moving the validation into part of the reading.
247
        missing = {}
0.5.115 by John Arbash Meinel
Getting closer to being able to read back the changesets, still broken, though.
248
        for revision_id, sha1 in rev_to_sha.iteritems():
1185.82.15 by Aaron Bentley
Disabled validate_revisions (needs info it doesn't have), updated API to repos
249
            if repository.has_revision(revision_id):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
250
                testament = StrictTestament.from_revision(repository,
1185.82.121 by Aaron Bentley
Move calculation of Testament sha1s to Testament
251
                                                          revision_id)
1910.2.55 by Aaron Bentley
Bundle 0.9 uses Testament 3 strict
252
                local_sha1 = self._testament_sha1_from_revision(repository,
253
                                                                revision_id)
0.5.63 by John Arbash Meinel
Moving the validation into part of the reading.
254
                if sha1 != local_sha1:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
255
                    raise BzrError('sha1 mismatch. For revision id {%s}'
1185.82.130 by Aaron Bentley
Rename changesets to revision bundles
256
                            'local: %s, bundle: %s' % (revision_id, local_sha1, sha1))
0.5.64 by John Arbash Meinel
SUCCESS, we now are able to validate the inventory XML.
257
                else:
258
                    count += 1
0.5.115 by John Arbash Meinel
Getting closer to being able to read back the changesets, still broken, though.
259
            elif revision_id not in checked:
260
                missing[revision_id] = sha1
0.5.63 by John Arbash Meinel
Moving the validation into part of the reading.
261
262
        if len(missing) > 0:
263
            # I don't know if this is an error yet
264
            warning('Not all revision hashes could be validated.'
265
                    ' Unable validate %d hashes' % len(missing))
1185.82.130 by Aaron Bentley
Rename changesets to revision bundles
266
        mutter('Verified %d sha hashes for the bundle.' % count)
2476.2.1 by John Arbash Meinel
Vastly improve bundle install performance by only validating the bundle one time
267
        self._validated_revisions_against_repo = True
0.5.64 by John Arbash Meinel
SUCCESS, we now are able to validate the inventory XML.
268
1185.82.49 by Aaron Bentley
SPOT fixes, fix inventory validation
269
    def _validate_inventory(self, inv, revision_id):
1185.82.130 by Aaron Bentley
Rename changesets to revision bundles
270
        """At this point we should have generated the BundleTree,
0.5.63 by John Arbash Meinel
Moving the validation into part of the reading.
271
        so build up an inventory, and make sure the hashes match.
272
        """
0.5.64 by John Arbash Meinel
SUCCESS, we now are able to validate the inventory XML.
273
        # Now we should have a complete inventory entry.
0.5.117 by John Arbash Meinel
Almost there. Just need to track down a few remaining bugs.
274
        s = serializer_v5.write_inventory_to_string(inv)
275
        sha1 = sha_string(s)
0.5.64 by John Arbash Meinel
SUCCESS, we now are able to validate the inventory XML.
276
        # Target revision is the last entry in the real_revisions list
1793.2.1 by Aaron Bentley
Move revision_tree into BundleInfo
277
        rev = self.get_revision(revision_id)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
278
        if rev.revision_id != revision_id:
279
            raise AssertionError()
0.5.64 by John Arbash Meinel
SUCCESS, we now are able to validate the inventory XML.
280
        if sha1 != rev.inventory_sha1:
0.5.117 by John Arbash Meinel
Almost there. Just need to track down a few remaining bugs.
281
            open(',,bogus-inv', 'wb').write(s)
1185.82.61 by Aaron Bentley
Downgrade inventory mismatch to warning (source can be inaccurate)
282
            warning('Inventory sha hash mismatch for revision %s. %s'
283
                    ' != %s' % (revision_id, sha1, rev.inventory_sha1))
0.5.64 by John Arbash Meinel
SUCCESS, we now are able to validate the inventory XML.
284
1793.2.1 by Aaron Bentley
Move revision_tree into BundleInfo
285
    def _validate_revision(self, inventory, revision_id):
286
        """Make sure all revision entries match their checksum."""
287
288
        # This is a mapping from each revision id to it's sha hash
289
        rev_to_sha1 = {}
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
290
1793.2.1 by Aaron Bentley
Move revision_tree into BundleInfo
291
        rev = self.get_revision(revision_id)
292
        rev_info = self.get_revision_info(revision_id)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
293
        if not (rev.revision_id == rev_info.revision_id):
294
            raise AssertionError()
295
        if not (rev.revision_id == revision_id):
296
            raise AssertionError()
1910.2.55 by Aaron Bentley
Bundle 0.9 uses Testament 3 strict
297
        sha1 = self._testament_sha1(rev, inventory)
1793.2.1 by Aaron Bentley
Move revision_tree into BundleInfo
298
        if sha1 != rev_info.sha1:
299
            raise TestamentMismatch(rev.revision_id, rev_info.sha1, sha1)
1963.2.1 by Robey Pointer
remove usage of has_key()
300
        if rev.revision_id in rev_to_sha1:
1793.2.1 by Aaron Bentley
Move revision_tree into BundleInfo
301
            raise BzrError('Revision {%s} given twice in the list'
302
                    % (rev.revision_id))
303
        rev_to_sha1[rev.revision_id] = sha1
304
305
    def _update_tree(self, bundle_tree, revision_id):
306
        """This fills out a BundleTree based on the information
307
        that was read in.
308
309
        :param bundle_tree: A BundleTree to update with the new information.
310
        """
311
312
        def get_rev_id(last_changed, path, kind):
313
            if last_changed is not None:
2309.4.5 by John Arbash Meinel
Change bundle_data to use the sanitizing form of safe_*_id
314
                # last_changed will be a Unicode string because of how it was
315
                # read. Convert it back to utf8.
316
                changed_revision_id = osutils.safe_revision_id(last_changed,
317
                                                               warn=False)
1793.2.1 by Aaron Bentley
Move revision_tree into BundleInfo
318
            else:
319
                changed_revision_id = revision_id
320
            bundle_tree.note_last_changed(path, changed_revision_id)
321
            return changed_revision_id
322
323
        def extra_info(info, new_path):
324
            last_changed = None
325
            encoding = None
326
            for info_item in info:
327
                try:
328
                    name, value = info_item.split(':', 1)
329
                except ValueError:
330
                    raise 'Value %r has no colon' % info_item
331
                if name == 'last-changed':
332
                    last_changed = value
333
                elif name == 'executable':
334
                    val = (value == 'yes')
335
                    bundle_tree.note_executable(new_path, val)
336
                elif name == 'target':
337
                    bundle_tree.note_target(new_path, value)
338
                elif name == 'encoding':
339
                    encoding = value
340
            return last_changed, encoding
341
342
        def do_patch(path, lines, encoding):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
343
            if encoding == 'base64':
1793.2.1 by Aaron Bentley
Move revision_tree into BundleInfo
344
                patch = base64.decodestring(''.join(lines))
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
345
            elif encoding is None:
1793.2.1 by Aaron Bentley
Move revision_tree into BundleInfo
346
                patch =  ''.join(lines)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
347
            else:
348
                raise ValueError(encoding)
1793.2.1 by Aaron Bentley
Move revision_tree into BundleInfo
349
            bundle_tree.note_patch(path, patch)
350
351
        def renamed(kind, extra, lines):
352
            info = extra.split(' // ')
353
            if len(info) < 2:
354
                raise BzrError('renamed action lines need both a from and to'
355
                        ': %r' % extra)
356
            old_path = info[0]
357
            if info[1].startswith('=> '):
358
                new_path = info[1][3:]
359
            else:
360
                new_path = info[1]
361
362
            bundle_tree.note_rename(old_path, new_path)
363
            last_modified, encoding = extra_info(info[2:], new_path)
364
            revision = get_rev_id(last_modified, new_path, kind)
365
            if lines:
366
                do_patch(new_path, lines, encoding)
367
368
        def removed(kind, extra, lines):
369
            info = extra.split(' // ')
370
            if len(info) > 1:
371
                # TODO: in the future we might allow file ids to be
372
                # given for removed entries
373
                raise BzrError('removed action lines should only have the path'
374
                        ': %r' % extra)
375
            path = info[0]
376
            bundle_tree.note_deletion(path)
377
378
        def added(kind, extra, lines):
379
            info = extra.split(' // ')
380
            if len(info) <= 1:
381
                raise BzrError('add action lines require the path and file id'
382
                        ': %r' % extra)
383
            elif len(info) > 5:
384
                raise BzrError('add action lines have fewer than 5 entries.'
385
                        ': %r' % extra)
386
            path = info[0]
387
            if not info[1].startswith('file-id:'):
388
                raise BzrError('The file-id should follow the path for an add'
389
                        ': %r' % extra)
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
390
            # This will be Unicode because of how the stream is read. Turn it
391
            # back into a utf8 file_id
2309.4.5 by John Arbash Meinel
Change bundle_data to use the sanitizing form of safe_*_id
392
            file_id = osutils.safe_file_id(info[1][8:], warn=False)
1793.2.1 by Aaron Bentley
Move revision_tree into BundleInfo
393
394
            bundle_tree.note_id(file_id, path, kind)
395
            # this will be overridden in extra_info if executable is specified.
396
            bundle_tree.note_executable(path, False)
397
            last_changed, encoding = extra_info(info[2:], path)
398
            revision = get_rev_id(last_changed, path, kind)
399
            if kind == 'directory':
400
                return
401
            do_patch(path, lines, encoding)
402
403
        def modified(kind, extra, lines):
404
            info = extra.split(' // ')
405
            if len(info) < 1:
406
                raise BzrError('modified action lines have at least'
407
                        'the path in them: %r' % extra)
408
            path = info[0]
409
410
            last_modified, encoding = extra_info(info[1:], path)
411
            revision = get_rev_id(last_modified, path, kind)
412
            if lines:
413
                do_patch(path, lines, encoding)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
414
1793.2.1 by Aaron Bentley
Move revision_tree into BundleInfo
415
        valid_actions = {
416
            'renamed':renamed,
417
            'removed':removed,
418
            'added':added,
419
            'modified':modified
420
        }
421
        for action_line, lines in \
422
            self.get_revision_info(revision_id).tree_actions:
423
            first = action_line.find(' ')
424
            if first == -1:
425
                raise BzrError('Bogus action line'
426
                        ' (no opening space): %r' % action_line)
427
            second = action_line.find(' ', first+1)
428
            if second == -1:
429
                raise BzrError('Bogus action line'
430
                        ' (missing second space): %r' % action_line)
431
            action = action_line[:first]
432
            kind = action_line[first+1:second]
433
            if kind not in ('file', 'directory', 'symlink'):
434
                raise BzrError('Bogus action line'
435
                        ' (invalid object kind %r): %r' % (kind, action_line))
436
            extra = action_line[second+1:]
437
438
            if action not in valid_actions:
439
                raise BzrError('Bogus action line'
440
                        ' (unrecognized action): %r' % action_line)
441
            valid_actions[action](kind, extra, lines)
442
2520.4.148 by Aaron Bentley
Updates from review
443
    def install_revisions(self, target_repo, stream_input=True):
444
        """Install revisions and return the target revision
445
446
        :param target_repo: The repository to install into
447
        :param stream_input: Ignored by this implementation.
448
        """
1551.14.4 by Aaron Bentley
Change bundle reader and merge directive to both be 'mergeables'
449
        apply_bundle.install_bundle(target_repo, self)
450
        return self.target
451
2520.4.109 by Aaron Bentley
start work on directive cherry-picking
452
    def get_merge_request(self, target_repo):
453
        """Provide data for performing a merge
454
455
        Returns suggested base, suggested target, and patch verification status
456
        """
457
        return None, self.target, 'inapplicable'
458
1551.14.4 by Aaron Bentley
Change bundle reader and merge directive to both be 'mergeables'
459
1185.82.130 by Aaron Bentley
Rename changesets to revision bundles
460
class BundleTree(Tree):
1185.82.16 by Aaron Bentley
Ensured revision ID is stored in ChangesetTree inventories
461
    def __init__(self, base_tree, revision_id):
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
462
        self.base_tree = base_tree
0.5.55 by John Arbash Meinel
Lots of updates. Using a minimized annotations for changesets.
463
        self._renamed = {} # Mapping from old_path => new_path
464
        self._renamed_r = {} # new_path => old_path
465
        self._new_id = {} # new_path => new_id
466
        self._new_id_r = {} # new_id => new_path
0.5.64 by John Arbash Meinel
SUCCESS, we now are able to validate the inventory XML.
467
        self._kinds = {} # new_id => kind
0.5.118 by John Arbash Meinel
Got most of test_changeset to work. Still needs work for Aaron's test code.
468
        self._last_changed = {} # new_id => revision_id
1185.82.66 by Aaron Bentley
Handle new executable files
469
        self._executable = {} # new_id => executable value
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
470
        self.patches = {}
1185.82.87 by Aaron Bentley
Got symlink adding working
471
        self._targets = {} # new path => new symlink target
0.5.48 by aaron.bentley at utoronto
Implemented deletion for ChangesetTrees
472
        self.deleted = []
0.5.52 by aaron.bentley at utoronto
Make contents-addressing configurable
473
        self.contents_by_id = True
1185.82.16 by Aaron Bentley
Ensured revision ID is stored in ChangesetTree inventories
474
        self.revision_id = revision_id
0.5.82 by John Arbash Meinel
Lots of changes, changing separators, updating tests, updated ChangesetTree to include text_ids
475
        self._inventory = None
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
476
0.5.55 by John Arbash Meinel
Lots of updates. Using a minimized annotations for changesets.
477
    def __str__(self):
478
        return pprint.pformat(self.__dict__)
479
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
480
    def note_rename(self, old_path, new_path):
0.5.55 by John Arbash Meinel
Lots of updates. Using a minimized annotations for changesets.
481
        """A file/directory has been renamed from old_path => new_path"""
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
482
        if new_path in self._renamed:
483
            raise AssertionError(new_path)
484
        if old_path in self._renamed_r:
485
            raise AssertionError(old_path)
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
486
        self._renamed[new_path] = old_path
487
        self._renamed_r[old_path] = new_path
488
0.5.64 by John Arbash Meinel
SUCCESS, we now are able to validate the inventory XML.
489
    def note_id(self, new_id, new_path, kind='file'):
0.5.55 by John Arbash Meinel
Lots of updates. Using a minimized annotations for changesets.
490
        """Files that don't exist in base need a new id."""
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
491
        self._new_id[new_path] = new_id
492
        self._new_id_r[new_id] = new_path
0.5.64 by John Arbash Meinel
SUCCESS, we now are able to validate the inventory XML.
493
        self._kinds[new_id] = kind
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
494
0.5.115 by John Arbash Meinel
Getting closer to being able to read back the changesets, still broken, though.
495
    def note_last_changed(self, file_id, revision_id):
1963.2.1 by Robey Pointer
remove usage of has_key()
496
        if (file_id in self._last_changed
0.5.118 by John Arbash Meinel
Got most of test_changeset to work. Still needs work for Aaron's test code.
497
                and self._last_changed[file_id] != revision_id):
0.5.115 by John Arbash Meinel
Getting closer to being able to read back the changesets, still broken, though.
498
            raise BzrError('Mismatched last-changed revision for file_id {%s}'
0.5.82 by John Arbash Meinel
Lots of changes, changing separators, updating tests, updated ChangesetTree to include text_ids
499
                    ': %s != %s' % (file_id,
0.5.118 by John Arbash Meinel
Got most of test_changeset to work. Still needs work for Aaron's test code.
500
                                    self._last_changed[file_id],
0.5.115 by John Arbash Meinel
Getting closer to being able to read back the changesets, still broken, though.
501
                                    revision_id))
0.5.118 by John Arbash Meinel
Got most of test_changeset to work. Still needs work for Aaron's test code.
502
        self._last_changed[file_id] = revision_id
0.5.82 by John Arbash Meinel
Lots of changes, changing separators, updating tests, updated ChangesetTree to include text_ids
503
0.5.44 by aaron.bentley at utoronto
Got get_file working for new files
504
    def note_patch(self, new_path, patch):
0.5.55 by John Arbash Meinel
Lots of updates. Using a minimized annotations for changesets.
505
        """There is a patch for a given filename."""
1731.1.55 by Aaron Bentley
Fix bundle handling
506
        self.patches[new_path] = patch
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
507
1185.82.87 by Aaron Bentley
Got symlink adding working
508
    def note_target(self, new_path, target):
509
        """The symlink at the new path has the given target"""
1731.1.55 by Aaron Bentley
Fix bundle handling
510
        self._targets[new_path] = target
1185.82.87 by Aaron Bentley
Got symlink adding working
511
0.5.48 by aaron.bentley at utoronto
Implemented deletion for ChangesetTrees
512
    def note_deletion(self, old_path):
0.5.55 by John Arbash Meinel
Lots of updates. Using a minimized annotations for changesets.
513
        """The file at old_path has been deleted."""
1731.1.55 by Aaron Bentley
Fix bundle handling
514
        self.deleted.append(old_path)
0.5.48 by aaron.bentley at utoronto
Implemented deletion for ChangesetTrees
515
1185.82.66 by Aaron Bentley
Handle new executable files
516
    def note_executable(self, new_path, executable):
1731.1.55 by Aaron Bentley
Fix bundle handling
517
        self._executable[new_path] = executable
1185.82.66 by Aaron Bentley
Handle new executable files
518
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
519
    def old_path(self, new_path):
0.5.55 by John Arbash Meinel
Lots of updates. Using a minimized annotations for changesets.
520
        """Get the old_path (path in the base_tree) for the file at new_path"""
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
521
        if new_path[:1] in ('\\', '/'):
522
            raise ValueError(new_path)
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
523
        old_path = self._renamed.get(new_path)
524
        if old_path is not None:
525
            return old_path
526
        dirname,basename = os.path.split(new_path)
0.5.56 by John Arbash Meinel
A couple more fixups, it seems actually capable now of writing out a changeset, and reading it back.
527
        # dirname is not '' doesn't work, because
528
        # dirname may be a unicode entry, and is
529
        # requires the objects to be identical
530
        if dirname != '':
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
531
            old_dir = self.old_path(dirname)
532
            if old_dir is None:
0.5.42 by aaron.bentley at utoronto
Improved rename handling
533
                old_path = None
534
            else:
1711.4.19 by John Arbash Meinel
Bundles were still using os.path.join to compute paths rather than osutils.pathjoin
535
                old_path = pathjoin(old_dir, basename)
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
536
        else:
0.5.42 by aaron.bentley at utoronto
Improved rename handling
537
            old_path = new_path
538
        #If the new path wasn't in renamed, the old one shouldn't be in
539
        #renamed_r
1963.2.1 by Robey Pointer
remove usage of has_key()
540
        if old_path in self._renamed_r:
0.5.42 by aaron.bentley at utoronto
Improved rename handling
541
            return None
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
542
        return old_path
0.5.42 by aaron.bentley at utoronto
Improved rename handling
543
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
544
    def new_path(self, old_path):
0.5.55 by John Arbash Meinel
Lots of updates. Using a minimized annotations for changesets.
545
        """Get the new_path (path in the target_tree) for the file at old_path
546
        in the base tree.
547
        """
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
548
        if old_path[:1] in ('\\', '/'):
549
            raise ValueError(old_path)
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
550
        new_path = self._renamed_r.get(old_path)
551
        if new_path is not None:
552
            return new_path
1963.2.1 by Robey Pointer
remove usage of has_key()
553
        if new_path in self._renamed:
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
554
            return None
555
        dirname,basename = os.path.split(old_path)
0.5.81 by John Arbash Meinel
Cleaning up from pychecker.
556
        if dirname != '':
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
557
            new_dir = self.new_path(dirname)
558
            if new_dir is None:
0.5.42 by aaron.bentley at utoronto
Improved rename handling
559
                new_path = None
560
            else:
1711.4.19 by John Arbash Meinel
Bundles were still using os.path.join to compute paths rather than osutils.pathjoin
561
                new_path = pathjoin(new_dir, basename)
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
562
        else:
0.5.42 by aaron.bentley at utoronto
Improved rename handling
563
            new_path = old_path
564
        #If the old path wasn't in renamed, the new one shouldn't be in
565
        #renamed_r
1963.2.1 by Robey Pointer
remove usage of has_key()
566
        if new_path in self._renamed:
0.5.42 by aaron.bentley at utoronto
Improved rename handling
567
            return None
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
568
        return new_path
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
569
570
    def path2id(self, path):
0.5.55 by John Arbash Meinel
Lots of updates. Using a minimized annotations for changesets.
571
        """Return the id of the file present at path in the target tree."""
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
572
        file_id = self._new_id.get(path)
573
        if file_id is not None:
574
            return file_id
0.5.43 by aaron.bentley at utoronto
Handled moves and adds properly
575
        old_path = self.old_path(path)
576
        if old_path is None:
577
            return None
0.5.48 by aaron.bentley at utoronto
Implemented deletion for ChangesetTrees
578
        if old_path in self.deleted:
579
            return None
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
580
        if getattr(self.base_tree, 'path2id', None) is not None:
0.5.66 by John Arbash Meinel
Refactoring, moving test code into test (switching back to assert is None)
581
            return self.base_tree.path2id(old_path)
582
        else:
583
            return self.base_tree.inventory.path2id(old_path)
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
584
585
    def id2path(self, file_id):
0.5.55 by John Arbash Meinel
Lots of updates. Using a minimized annotations for changesets.
586
        """Return the new path in the target tree of the file with id file_id"""
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
587
        path = self._new_id_r.get(file_id)
588
        if path is not None:
589
            return path
0.5.43 by aaron.bentley at utoronto
Handled moves and adds properly
590
        old_path = self.base_tree.id2path(file_id)
591
        if old_path is None:
592
            return None
0.5.48 by aaron.bentley at utoronto
Implemented deletion for ChangesetTrees
593
        if old_path in self.deleted:
594
            return None
0.5.43 by aaron.bentley at utoronto
Handled moves and adds properly
595
        return self.new_path(old_path)
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
596
0.5.52 by aaron.bentley at utoronto
Make contents-addressing configurable
597
    def old_contents_id(self, file_id):
1185.82.94 by Aaron Bentley
Remove old chatter
598
        """Return the id in the base_tree for the given file_id.
599
        Return None if the file did not exist in base.
0.5.55 by John Arbash Meinel
Lots of updates. Using a minimized annotations for changesets.
600
        """
0.5.52 by aaron.bentley at utoronto
Make contents-addressing configurable
601
        if self.contents_by_id:
602
            if self.base_tree.has_id(file_id):
603
                return file_id
604
            else:
605
                return None
606
        new_path = self.id2path(file_id)
607
        return self.base_tree.path2id(new_path)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
608
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
609
    def get_file(self, file_id):
0.5.55 by John Arbash Meinel
Lots of updates. Using a minimized annotations for changesets.
610
        """Return a file-like object containing the new contents of the
611
        file given by file_id.
612
613
        TODO:   It might be nice if this actually generated an entry
614
                in the text-store, so that the file contents would
615
                then be cached.
616
        """
0.5.52 by aaron.bentley at utoronto
Make contents-addressing configurable
617
        base_id = self.old_contents_id(file_id)
1910.2.64 by Aaron Bentley
Changes from review
618
        if (base_id is not None and
1910.2.58 by Aaron Bentley
Stop using get_revision_id to make bundles
619
            base_id != self.base_tree.inventory.root.file_id):
0.5.50 by aaron.bentley at utoronto
Evaluate patches against file paths, not file ids
620
            patch_original = self.base_tree.get_file(base_id)
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
621
        else:
622
            patch_original = None
0.5.52 by aaron.bentley at utoronto
Make contents-addressing configurable
623
        file_patch = self.patches.get(self.id2path(file_id))
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
624
        if file_patch is None:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
625
            if (patch_original is None and
1185.82.42 by Aaron Bentley
Handle new directories properly
626
                self.get_kind(file_id) == 'directory'):
627
                return StringIO()
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
628
            if patch_original is None:
629
                raise AssertionError("None: %s" % file_id)
0.5.44 by aaron.bentley at utoronto
Got get_file working for new files
630
            return patch_original
0.5.94 by Aaron Bentley
Switched to native patch application, added tests for terminating newlines
631
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
632
        if file_patch.startswith('\\'):
633
            raise ValueError(
634
                'Malformed patch for %s, %r' % (file_id, file_patch))
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
635
        return patched_file(file_patch, patch_original)
636
1185.82.87 by Aaron Bentley
Got symlink adding working
637
    def get_symlink_target(self, file_id):
638
        new_path = self.id2path(file_id)
639
        try:
640
            return self._targets[new_path]
641
        except KeyError:
642
            return self.base_tree.get_symlink_target(file_id)
643
0.5.64 by John Arbash Meinel
SUCCESS, we now are able to validate the inventory XML.
644
    def get_kind(self, file_id):
645
        if file_id in self._kinds:
646
            return self._kinds[file_id]
647
        return self.base_tree.inventory[file_id].kind
648
1185.82.66 by Aaron Bentley
Handle new executable files
649
    def is_executable(self, file_id):
1185.82.93 by Aaron Bentley
Code cleanup
650
        path = self.id2path(file_id)
651
        if path in self._executable:
652
            return self._executable[path]
1185.82.66 by Aaron Bentley
Handle new executable files
653
        else:
654
            return self.base_tree.inventory[file_id].executable
655
0.5.115 by John Arbash Meinel
Getting closer to being able to read back the changesets, still broken, though.
656
    def get_last_changed(self, file_id):
1185.82.95 by Aaron Bentley
Restore path-orientation of ChangesetTree
657
        path = self.id2path(file_id)
658
        if path in self._last_changed:
659
            return self._last_changed[path]
0.5.115 by John Arbash Meinel
Getting closer to being able to read back the changesets, still broken, though.
660
        return self.base_tree.inventory[file_id].revision
0.5.82 by John Arbash Meinel
Lots of changes, changing separators, updating tests, updated ChangesetTree to include text_ids
661
0.5.64 by John Arbash Meinel
SUCCESS, we now are able to validate the inventory XML.
662
    def get_size_and_sha1(self, file_id):
663
        """Return the size and sha1 hash of the given file id.
664
        If the file was not locally modified, this is extracted
665
        from the base_tree. Rather than re-reading the file.
666
        """
667
        new_path = self.id2path(file_id)
668
        if new_path is None:
669
            return None, None
670
        if new_path not in self.patches:
671
            # If the entry does not have a patch, then the
672
            # contents must be the same as in the base_tree
673
            ie = self.base_tree.inventory[file_id]
0.5.69 by John Arbash Meinel
Applying patch from Robey Pointer to clean up apply_changeset.
674
            if ie.text_size is None:
675
                return ie.text_size, ie.text_sha1
0.5.64 by John Arbash Meinel
SUCCESS, we now are able to validate the inventory XML.
676
            return int(ie.text_size), ie.text_sha1
0.5.94 by Aaron Bentley
Switched to native patch application, added tests for terminating newlines
677
        fileobj = self.get_file(file_id)
678
        content = fileobj.read()
0.5.64 by John Arbash Meinel
SUCCESS, we now are able to validate the inventory XML.
679
        return len(content), sha_string(content)
680
0.5.82 by John Arbash Meinel
Lots of changes, changing separators, updating tests, updated ChangesetTree to include text_ids
681
    def _get_inventory(self):
1185.82.130 by Aaron Bentley
Rename changesets to revision bundles
682
        """Build up the inventory entry for the BundleTree.
0.5.82 by John Arbash Meinel
Lots of changes, changing separators, updating tests, updated ChangesetTree to include text_ids
683
684
        This need to be called before ever accessing self.inventory
685
        """
686
        from os.path import dirname, basename
687
        base_inv = self.base_tree.inventory
1731.1.62 by Aaron Bentley
Changes from review comments
688
        inv = Inventory(None, self.revision_id)
0.5.82 by John Arbash Meinel
Lots of changes, changing separators, updating tests, updated ChangesetTree to include text_ids
689
690
        def add_entry(file_id):
691
            path = self.id2path(file_id)
692
            if path is None:
693
                return
1731.1.55 by Aaron Bentley
Fix bundle handling
694
            if path == '':
695
                parent_id = None
0.5.82 by John Arbash Meinel
Lots of changes, changing separators, updating tests, updated ChangesetTree to include text_ids
696
            else:
1731.1.55 by Aaron Bentley
Fix bundle handling
697
                parent_path = dirname(path)
0.5.82 by John Arbash Meinel
Lots of changes, changing separators, updating tests, updated ChangesetTree to include text_ids
698
                parent_id = self.path2id(parent_path)
699
700
            kind = self.get_kind(file_id)
0.5.115 by John Arbash Meinel
Getting closer to being able to read back the changesets, still broken, though.
701
            revision_id = self.get_last_changed(file_id)
0.5.83 by John Arbash Meinel
Tests pass. Now ChangesetTree has it's own inventory.
702
703
            name = basename(path)
0.5.116 by John Arbash Meinel
Fixed a bug based on the new InventoryEntry separation.
704
            if kind == 'directory':
705
                ie = InventoryDirectory(file_id, name, parent_id)
706
            elif kind == 'file':
707
                ie = InventoryFile(file_id, name, parent_id)
1185.82.66 by Aaron Bentley
Handle new executable files
708
                ie.executable = self.is_executable(file_id)
0.5.116 by John Arbash Meinel
Fixed a bug based on the new InventoryEntry separation.
709
            elif kind == 'symlink':
710
                ie = InventoryLink(file_id, name, parent_id)
1185.82.87 by Aaron Bentley
Got symlink adding working
711
                ie.symlink_target = self.get_symlink_target(file_id)
0.5.115 by John Arbash Meinel
Getting closer to being able to read back the changesets, still broken, though.
712
            ie.revision = revision_id
713
1185.82.88 by Aaron Bentley
Get symlink modification, renames and deletion under test
714
            if kind in ('directory', 'symlink'):
0.5.83 by John Arbash Meinel
Tests pass. Now ChangesetTree has it's own inventory.
715
                ie.text_size, ie.text_sha1 = None, None
716
            else:
717
                ie.text_size, ie.text_sha1 = self.get_size_and_sha1(file_id)
1185.82.88 by Aaron Bentley
Get symlink modification, renames and deletion under test
718
            if (ie.text_size is None) and (kind == 'file'):
0.5.82 by John Arbash Meinel
Lots of changes, changing separators, updating tests, updated ChangesetTree to include text_ids
719
                raise BzrError('Got a text_size of None for file_id %r' % file_id)
720
            inv.add(ie)
721
0.6.1 by Aaron Bentley
Fleshed out MockTree, fixed all test failures
722
        sorted_entries = self.sorted_path_id()
723
        for path, file_id in sorted_entries:
0.5.82 by John Arbash Meinel
Lots of changes, changing separators, updating tests, updated ChangesetTree to include text_ids
724
            add_entry(file_id)
725
726
        return inv
727
728
    # Have to overload the inherited inventory property
729
    # because _get_inventory is only called in the parent.
730
    # Reading the docs, property() objects do not use
731
    # overloading, they use the function as it was defined
732
    # at that instant
733
    inventory = property(_get_inventory)
0.5.64 by John Arbash Meinel
SUCCESS, we now are able to validate the inventory XML.
734
0.5.49 by aaron.bentley at utoronto
Implemented iteration over ids
735
    def __iter__(self):
0.5.82 by John Arbash Meinel
Lots of changes, changing separators, updating tests, updated ChangesetTree to include text_ids
736
        for path, entry in self.inventory.iter_entries():
0.5.69 by John Arbash Meinel
Applying patch from Robey Pointer to clean up apply_changeset.
737
            yield entry.file_id
0.5.49 by aaron.bentley at utoronto
Implemented iteration over ids
738
0.6.1 by Aaron Bentley
Fleshed out MockTree, fixed all test failures
739
    def sorted_path_id(self):
740
        paths = []
741
        for result in self._new_id.iteritems():
742
            paths.append(result)
743
        for id in self.base_tree:
744
            path = self.id2path(id)
745
            if path is None:
746
                continue
747
            paths.append((path, id))
748
        paths.sort()
749
        return paths
750
1185.82.123 by Aaron Bentley
Cleanups to prepare for review
751
0.5.41 by aaron.bentley at utoronto
Added non-working ChangesetTree
752
def patched_file(file_patch, original):
0.5.94 by Aaron Bentley
Switched to native patch application, added tests for terminating newlines
753
    """Produce a file-like object with the patched version of a text"""
1185.82.13 by Aaron Bentley
Got old changeset tests running
754
    from bzrlib.patches import iter_patched
755
    from bzrlib.iterablefile import IterableFile
0.5.94 by Aaron Bentley
Switched to native patch application, added tests for terminating newlines
756
    if file_patch == "":
757
        return IterableFile(())
1848.1.1 by John Arbash Meinel
fix bug in bundle handling of binary files with just '\r' in them.
758
    # string.splitlines(True) also splits on '\r', but the iter_patched code
759
    # only expects to iterate over '\n' style lines
760
    return IterableFile(iter_patched(original,
761
                StringIO(file_patch).readlines()))