/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/bundle/bundle_data.py

  • Committer: Martin Pool
  • Date: 2008-05-02 05:43:54 UTC
  • mfrom: (3287.15.2 1.3)
  • mto: This revision was merged to the branch mainline in revision 3403.
  • Revision ID: mbp@sourcefrog.net-20080502054354-t1ah9qqd1a156v73
merge 1.3.1 back into trunk
(news update only, the fix for #208418 was already merged)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006 Canonical Ltd
 
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
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
"""Read in a bundle stream, and process it into a BundleReader object."""
 
18
 
 
19
import base64
 
20
from cStringIO import StringIO
 
21
import os
 
22
import pprint
 
23
 
 
24
from bzrlib import (
 
25
    osutils,
 
26
    timestamp,
 
27
    )
 
28
import bzrlib.errors
 
29
from bzrlib.bundle import apply_bundle
 
30
from bzrlib.errors import (TestamentMismatch, BzrError, 
 
31
                           MalformedHeader, MalformedPatches, NotABundle)
 
32
from bzrlib.inventory import (Inventory, InventoryEntry,
 
33
                              InventoryDirectory, InventoryFile,
 
34
                              InventoryLink)
 
35
from bzrlib.osutils import sha_file, sha_string, pathjoin
 
36
from bzrlib.revision import Revision, NULL_REVISION
 
37
from bzrlib.testament import StrictTestament
 
38
from bzrlib.trace import mutter, warning
 
39
import bzrlib.transport
 
40
from bzrlib.tree import Tree
 
41
import bzrlib.urlutils
 
42
from bzrlib.xml5 import serializer_v5
 
43
 
 
44
 
 
45
class RevisionInfo(object):
 
46
    """Gets filled out for each revision object that is read.
 
47
    """
 
48
    def __init__(self, revision_id):
 
49
        self.revision_id = revision_id
 
50
        self.sha1 = None
 
51
        self.committer = None
 
52
        self.date = None
 
53
        self.timestamp = None
 
54
        self.timezone = None
 
55
        self.inventory_sha1 = None
 
56
 
 
57
        self.parent_ids = None
 
58
        self.base_id = None
 
59
        self.message = None
 
60
        self.properties = None
 
61
        self.tree_actions = None
 
62
 
 
63
    def __str__(self):
 
64
        return pprint.pformat(self.__dict__)
 
65
 
 
66
    def as_revision(self):
 
67
        rev = Revision(revision_id=self.revision_id,
 
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
 
 
74
        if self.parent_ids:
 
75
            rev.parent_ids.extend(self.parent_ids)
 
76
 
 
77
        if self.properties:
 
78
            for property in self.properties:
 
79
                key_end = property.find(': ')
 
80
                if key_end == -1:
 
81
                    assert property.endswith(':')
 
82
                    key = str(property[:-1])
 
83
                    value = ''
 
84
                else:
 
85
                    key = str(property[:key_end])
 
86
                    value = property[key_end+2:]
 
87
                rev.properties[key] = value
 
88
 
 
89
        return rev
 
90
 
 
91
    @staticmethod
 
92
    def from_revision(revision):
 
93
        revision_info = RevisionInfo(revision.revision_id)
 
94
        date = timestamp.format_highres_date(revision.timestamp,
 
95
                                             revision.timezone)
 
96
        revision_info.date = date
 
97
        revision_info.timezone = revision.timezone
 
98
        revision_info.timestamp = revision.timestamp
 
99
        revision_info.message = revision.message.split('\n')
 
100
        revision_info.properties = [': '.join(p) for p in
 
101
                                    revision.properties.iteritems()]
 
102
        return revision_info
 
103
 
 
104
 
 
105
class BundleInfo(object):
 
106
    """This contains the meta information. Stuff that allows you to
 
107
    recreate the revision or inventory XML.
 
108
    """
 
109
    def __init__(self, bundle_format=None):
 
110
        self.bundle_format = None
 
111
        self.committer = None
 
112
        self.date = None
 
113
        self.message = None
 
114
 
 
115
        # A list of RevisionInfo objects
 
116
        self.revisions = []
 
117
 
 
118
        # The next entries are created during complete_info() and
 
119
        # other post-read functions.
 
120
 
 
121
        # A list of real Revision objects
 
122
        self.real_revisions = []
 
123
 
 
124
        self.timestamp = None
 
125
        self.timezone = None
 
126
 
 
127
        # Have we checked the repository yet?
 
128
        self._validated_revisions_against_repo = False
 
129
 
 
130
    def __str__(self):
 
131
        return pprint.pformat(self.__dict__)
 
132
 
 
133
    def complete_info(self):
 
134
        """This makes sure that all information is properly
 
135
        split up, based on the assumptions that can be made
 
136
        when information is missing.
 
137
        """
 
138
        from bzrlib.timestamp import unpack_highres_date
 
139
        # Put in all of the guessable information.
 
140
        if not self.timestamp and self.date:
 
141
            self.timestamp, self.timezone = unpack_highres_date(self.date)
 
142
 
 
143
        self.real_revisions = []
 
144
        for rev in self.revisions:
 
145
            if rev.timestamp is None:
 
146
                if rev.date is not None:
 
147
                    rev.timestamp, rev.timezone = \
 
148
                            unpack_highres_date(rev.date)
 
149
                else:
 
150
                    rev.timestamp = self.timestamp
 
151
                    rev.timezone = self.timezone
 
152
            if rev.message is None and self.message:
 
153
                rev.message = self.message
 
154
            if rev.committer is None and self.committer:
 
155
                rev.committer = self.committer
 
156
            self.real_revisions.append(rev.as_revision())
 
157
 
 
158
    def get_base(self, revision):
 
159
        revision_info = self.get_revision_info(revision.revision_id)
 
160
        if revision_info.base_id is not None:
 
161
            if revision_info.base_id == NULL_REVISION:
 
162
                return None
 
163
            else:
 
164
                return revision_info.base_id
 
165
        if len(revision.parent_ids) == 0:
 
166
            # There is no base listed, and
 
167
            # the lowest revision doesn't have a parent
 
168
            # so this is probably against the empty tree
 
169
            # and thus base truly is None
 
170
            return None
 
171
        else:
 
172
            return revision.parent_ids[-1]
 
173
 
 
174
    def _get_target(self):
 
175
        """Return the target revision."""
 
176
        if len(self.real_revisions) > 0:
 
177
            return self.real_revisions[0].revision_id
 
178
        elif len(self.revisions) > 0:
 
179
            return self.revisions[0].revision_id
 
180
        return None
 
181
 
 
182
    target = property(_get_target, doc='The target revision id')
 
183
 
 
184
    def get_revision(self, revision_id):
 
185
        for r in self.real_revisions:
 
186
            if r.revision_id == revision_id:
 
187
                return r
 
188
        raise KeyError(revision_id)
 
189
 
 
190
    def get_revision_info(self, revision_id):
 
191
        for r in self.revisions:
 
192
            if r.revision_id == revision_id:
 
193
                return r
 
194
        raise KeyError(revision_id)
 
195
 
 
196
    def revision_tree(self, repository, revision_id, base=None):
 
197
        revision = self.get_revision(revision_id)
 
198
        base = self.get_base(revision)
 
199
        assert base != revision_id
 
200
        if not self._validated_revisions_against_repo:
 
201
            self._validate_references_from_repository(repository)
 
202
        revision_info = self.get_revision_info(revision_id)
 
203
        inventory_revision_id = revision_id
 
204
        bundle_tree = BundleTree(repository.revision_tree(base), 
 
205
                                  inventory_revision_id)
 
206
        self._update_tree(bundle_tree, revision_id)
 
207
 
 
208
        inv = bundle_tree.inventory
 
209
        self._validate_inventory(inv, revision_id)
 
210
        self._validate_revision(inv, revision_id)
 
211
 
 
212
        return bundle_tree
 
213
 
 
214
    def _validate_references_from_repository(self, repository):
 
215
        """Now that we have a repository which should have some of the
 
216
        revisions we care about, go through and validate all of them
 
217
        that we can.
 
218
        """
 
219
        rev_to_sha = {}
 
220
        inv_to_sha = {}
 
221
        def add_sha(d, revision_id, sha1):
 
222
            if revision_id is None:
 
223
                if sha1 is not None:
 
224
                    raise BzrError('A Null revision should always'
 
225
                        'have a null sha1 hash')
 
226
                return
 
227
            if revision_id in d:
 
228
                # This really should have been validated as part
 
229
                # of _validate_revisions but lets do it again
 
230
                if sha1 != d[revision_id]:
 
231
                    raise BzrError('** Revision %r referenced with 2 different'
 
232
                            ' sha hashes %s != %s' % (revision_id,
 
233
                                sha1, d[revision_id]))
 
234
            else:
 
235
                d[revision_id] = sha1
 
236
 
 
237
        # All of the contained revisions were checked
 
238
        # in _validate_revisions
 
239
        checked = {}
 
240
        for rev_info in self.revisions:
 
241
            checked[rev_info.revision_id] = True
 
242
            add_sha(rev_to_sha, rev_info.revision_id, rev_info.sha1)
 
243
                
 
244
        for (rev, rev_info) in zip(self.real_revisions, self.revisions):
 
245
            add_sha(inv_to_sha, rev_info.revision_id, rev_info.inventory_sha1)
 
246
 
 
247
        count = 0
 
248
        missing = {}
 
249
        for revision_id, sha1 in rev_to_sha.iteritems():
 
250
            if repository.has_revision(revision_id):
 
251
                testament = StrictTestament.from_revision(repository, 
 
252
                                                          revision_id)
 
253
                local_sha1 = self._testament_sha1_from_revision(repository,
 
254
                                                                revision_id)
 
255
                if sha1 != local_sha1:
 
256
                    raise BzrError('sha1 mismatch. For revision id {%s}' 
 
257
                            'local: %s, bundle: %s' % (revision_id, local_sha1, sha1))
 
258
                else:
 
259
                    count += 1
 
260
            elif revision_id not in checked:
 
261
                missing[revision_id] = sha1
 
262
 
 
263
        if len(missing) > 0:
 
264
            # I don't know if this is an error yet
 
265
            warning('Not all revision hashes could be validated.'
 
266
                    ' Unable validate %d hashes' % len(missing))
 
267
        mutter('Verified %d sha hashes for the bundle.' % count)
 
268
        self._validated_revisions_against_repo = True
 
269
 
 
270
    def _validate_inventory(self, inv, revision_id):
 
271
        """At this point we should have generated the BundleTree,
 
272
        so build up an inventory, and make sure the hashes match.
 
273
        """
 
274
 
 
275
        assert inv is not None
 
276
 
 
277
        # Now we should have a complete inventory entry.
 
278
        s = serializer_v5.write_inventory_to_string(inv)
 
279
        sha1 = sha_string(s)
 
280
        # Target revision is the last entry in the real_revisions list
 
281
        rev = self.get_revision(revision_id)
 
282
        assert rev.revision_id == revision_id
 
283
        if sha1 != rev.inventory_sha1:
 
284
            open(',,bogus-inv', 'wb').write(s)
 
285
            warning('Inventory sha hash mismatch for revision %s. %s'
 
286
                    ' != %s' % (revision_id, sha1, rev.inventory_sha1))
 
287
 
 
288
    def _validate_revision(self, inventory, revision_id):
 
289
        """Make sure all revision entries match their checksum."""
 
290
 
 
291
        # This is a mapping from each revision id to it's sha hash
 
292
        rev_to_sha1 = {}
 
293
        
 
294
        rev = self.get_revision(revision_id)
 
295
        rev_info = self.get_revision_info(revision_id)
 
296
        assert rev.revision_id == rev_info.revision_id
 
297
        assert rev.revision_id == revision_id
 
298
        sha1 = self._testament_sha1(rev, inventory)
 
299
        if sha1 != rev_info.sha1:
 
300
            raise TestamentMismatch(rev.revision_id, rev_info.sha1, sha1)
 
301
        if rev.revision_id in rev_to_sha1:
 
302
            raise BzrError('Revision {%s} given twice in the list'
 
303
                    % (rev.revision_id))
 
304
        rev_to_sha1[rev.revision_id] = sha1
 
305
 
 
306
    def _update_tree(self, bundle_tree, revision_id):
 
307
        """This fills out a BundleTree based on the information
 
308
        that was read in.
 
309
 
 
310
        :param bundle_tree: A BundleTree to update with the new information.
 
311
        """
 
312
 
 
313
        def get_rev_id(last_changed, path, kind):
 
314
            if last_changed is not None:
 
315
                # last_changed will be a Unicode string because of how it was
 
316
                # read. Convert it back to utf8.
 
317
                changed_revision_id = osutils.safe_revision_id(last_changed,
 
318
                                                               warn=False)
 
319
            else:
 
320
                changed_revision_id = revision_id
 
321
            bundle_tree.note_last_changed(path, changed_revision_id)
 
322
            return changed_revision_id
 
323
 
 
324
        def extra_info(info, new_path):
 
325
            last_changed = None
 
326
            encoding = None
 
327
            for info_item in info:
 
328
                try:
 
329
                    name, value = info_item.split(':', 1)
 
330
                except ValueError:
 
331
                    raise 'Value %r has no colon' % info_item
 
332
                if name == 'last-changed':
 
333
                    last_changed = value
 
334
                elif name == 'executable':
 
335
                    assert value in ('yes', 'no'), value
 
336
                    val = (value == 'yes')
 
337
                    bundle_tree.note_executable(new_path, val)
 
338
                elif name == 'target':
 
339
                    bundle_tree.note_target(new_path, value)
 
340
                elif name == 'encoding':
 
341
                    encoding = value
 
342
            return last_changed, encoding
 
343
 
 
344
        def do_patch(path, lines, encoding):
 
345
            if encoding is not None:
 
346
                assert encoding == 'base64'
 
347
                patch = base64.decodestring(''.join(lines))
 
348
            else:
 
349
                patch =  ''.join(lines)
 
350
            bundle_tree.note_patch(path, patch)
 
351
 
 
352
        def renamed(kind, extra, lines):
 
353
            info = extra.split(' // ')
 
354
            if len(info) < 2:
 
355
                raise BzrError('renamed action lines need both a from and to'
 
356
                        ': %r' % extra)
 
357
            old_path = info[0]
 
358
            if info[1].startswith('=> '):
 
359
                new_path = info[1][3:]
 
360
            else:
 
361
                new_path = info[1]
 
362
 
 
363
            bundle_tree.note_rename(old_path, new_path)
 
364
            last_modified, encoding = extra_info(info[2:], new_path)
 
365
            revision = get_rev_id(last_modified, new_path, kind)
 
366
            if lines:
 
367
                do_patch(new_path, lines, encoding)
 
368
 
 
369
        def removed(kind, extra, lines):
 
370
            info = extra.split(' // ')
 
371
            if len(info) > 1:
 
372
                # TODO: in the future we might allow file ids to be
 
373
                # given for removed entries
 
374
                raise BzrError('removed action lines should only have the path'
 
375
                        ': %r' % extra)
 
376
            path = info[0]
 
377
            bundle_tree.note_deletion(path)
 
378
 
 
379
        def added(kind, extra, lines):
 
380
            info = extra.split(' // ')
 
381
            if len(info) <= 1:
 
382
                raise BzrError('add action lines require the path and file id'
 
383
                        ': %r' % extra)
 
384
            elif len(info) > 5:
 
385
                raise BzrError('add action lines have fewer than 5 entries.'
 
386
                        ': %r' % extra)
 
387
            path = info[0]
 
388
            if not info[1].startswith('file-id:'):
 
389
                raise BzrError('The file-id should follow the path for an add'
 
390
                        ': %r' % extra)
 
391
            # This will be Unicode because of how the stream is read. Turn it
 
392
            # back into a utf8 file_id
 
393
            file_id = osutils.safe_file_id(info[1][8:], warn=False)
 
394
 
 
395
            bundle_tree.note_id(file_id, path, kind)
 
396
            # this will be overridden in extra_info if executable is specified.
 
397
            bundle_tree.note_executable(path, False)
 
398
            last_changed, encoding = extra_info(info[2:], path)
 
399
            revision = get_rev_id(last_changed, path, kind)
 
400
            if kind == 'directory':
 
401
                return
 
402
            do_patch(path, lines, encoding)
 
403
 
 
404
        def modified(kind, extra, lines):
 
405
            info = extra.split(' // ')
 
406
            if len(info) < 1:
 
407
                raise BzrError('modified action lines have at least'
 
408
                        'the path in them: %r' % extra)
 
409
            path = info[0]
 
410
 
 
411
            last_modified, encoding = extra_info(info[1:], path)
 
412
            revision = get_rev_id(last_modified, path, kind)
 
413
            if lines:
 
414
                do_patch(path, lines, encoding)
 
415
            
 
416
        valid_actions = {
 
417
            'renamed':renamed,
 
418
            'removed':removed,
 
419
            'added':added,
 
420
            'modified':modified
 
421
        }
 
422
        for action_line, lines in \
 
423
            self.get_revision_info(revision_id).tree_actions:
 
424
            first = action_line.find(' ')
 
425
            if first == -1:
 
426
                raise BzrError('Bogus action line'
 
427
                        ' (no opening space): %r' % action_line)
 
428
            second = action_line.find(' ', first+1)
 
429
            if second == -1:
 
430
                raise BzrError('Bogus action line'
 
431
                        ' (missing second space): %r' % action_line)
 
432
            action = action_line[:first]
 
433
            kind = action_line[first+1:second]
 
434
            if kind not in ('file', 'directory', 'symlink'):
 
435
                raise BzrError('Bogus action line'
 
436
                        ' (invalid object kind %r): %r' % (kind, action_line))
 
437
            extra = action_line[second+1:]
 
438
 
 
439
            if action not in valid_actions:
 
440
                raise BzrError('Bogus action line'
 
441
                        ' (unrecognized action): %r' % action_line)
 
442
            valid_actions[action](kind, extra, lines)
 
443
 
 
444
    def install_revisions(self, target_repo, stream_input=True):
 
445
        """Install revisions and return the target revision
 
446
 
 
447
        :param target_repo: The repository to install into
 
448
        :param stream_input: Ignored by this implementation.
 
449
        """
 
450
        apply_bundle.install_bundle(target_repo, self)
 
451
        return self.target
 
452
 
 
453
    def get_merge_request(self, target_repo):
 
454
        """Provide data for performing a merge
 
455
 
 
456
        Returns suggested base, suggested target, and patch verification status
 
457
        """
 
458
        return None, self.target, 'inapplicable'
 
459
 
 
460
 
 
461
class BundleTree(Tree):
 
462
    def __init__(self, base_tree, revision_id):
 
463
        self.base_tree = base_tree
 
464
        self._renamed = {} # Mapping from old_path => new_path
 
465
        self._renamed_r = {} # new_path => old_path
 
466
        self._new_id = {} # new_path => new_id
 
467
        self._new_id_r = {} # new_id => new_path
 
468
        self._kinds = {} # new_id => kind
 
469
        self._last_changed = {} # new_id => revision_id
 
470
        self._executable = {} # new_id => executable value
 
471
        self.patches = {}
 
472
        self._targets = {} # new path => new symlink target
 
473
        self.deleted = []
 
474
        self.contents_by_id = True
 
475
        self.revision_id = revision_id
 
476
        self._inventory = None
 
477
 
 
478
    def __str__(self):
 
479
        return pprint.pformat(self.__dict__)
 
480
 
 
481
    def note_rename(self, old_path, new_path):
 
482
        """A file/directory has been renamed from old_path => new_path"""
 
483
        assert new_path not in self._renamed
 
484
        assert old_path not in self._renamed_r
 
485
        self._renamed[new_path] = old_path
 
486
        self._renamed_r[old_path] = new_path
 
487
 
 
488
    def note_id(self, new_id, new_path, kind='file'):
 
489
        """Files that don't exist in base need a new id."""
 
490
        self._new_id[new_path] = new_id
 
491
        self._new_id_r[new_id] = new_path
 
492
        self._kinds[new_id] = kind
 
493
 
 
494
    def note_last_changed(self, file_id, revision_id):
 
495
        if (file_id in self._last_changed
 
496
                and self._last_changed[file_id] != revision_id):
 
497
            raise BzrError('Mismatched last-changed revision for file_id {%s}'
 
498
                    ': %s != %s' % (file_id,
 
499
                                    self._last_changed[file_id],
 
500
                                    revision_id))
 
501
        self._last_changed[file_id] = revision_id
 
502
 
 
503
    def note_patch(self, new_path, patch):
 
504
        """There is a patch for a given filename."""
 
505
        self.patches[new_path] = patch
 
506
 
 
507
    def note_target(self, new_path, target):
 
508
        """The symlink at the new path has the given target"""
 
509
        self._targets[new_path] = target
 
510
 
 
511
    def note_deletion(self, old_path):
 
512
        """The file at old_path has been deleted."""
 
513
        self.deleted.append(old_path)
 
514
 
 
515
    def note_executable(self, new_path, executable):
 
516
        self._executable[new_path] = executable
 
517
 
 
518
    def old_path(self, new_path):
 
519
        """Get the old_path (path in the base_tree) for the file at new_path"""
 
520
        assert new_path[:1] not in ('\\', '/')
 
521
        old_path = self._renamed.get(new_path)
 
522
        if old_path is not None:
 
523
            return old_path
 
524
        dirname,basename = os.path.split(new_path)
 
525
        # dirname is not '' doesn't work, because
 
526
        # dirname may be a unicode entry, and is
 
527
        # requires the objects to be identical
 
528
        if dirname != '':
 
529
            old_dir = self.old_path(dirname)
 
530
            if old_dir is None:
 
531
                old_path = None
 
532
            else:
 
533
                old_path = pathjoin(old_dir, basename)
 
534
        else:
 
535
            old_path = new_path
 
536
        #If the new path wasn't in renamed, the old one shouldn't be in
 
537
        #renamed_r
 
538
        if old_path in self._renamed_r:
 
539
            return None
 
540
        return old_path 
 
541
 
 
542
    def new_path(self, old_path):
 
543
        """Get the new_path (path in the target_tree) for the file at old_path
 
544
        in the base tree.
 
545
        """
 
546
        assert old_path[:1] not in ('\\', '/')
 
547
        new_path = self._renamed_r.get(old_path)
 
548
        if new_path is not None:
 
549
            return new_path
 
550
        if new_path in self._renamed:
 
551
            return None
 
552
        dirname,basename = os.path.split(old_path)
 
553
        if dirname != '':
 
554
            new_dir = self.new_path(dirname)
 
555
            if new_dir is None:
 
556
                new_path = None
 
557
            else:
 
558
                new_path = pathjoin(new_dir, basename)
 
559
        else:
 
560
            new_path = old_path
 
561
        #If the old path wasn't in renamed, the new one shouldn't be in
 
562
        #renamed_r
 
563
        if new_path in self._renamed:
 
564
            return None
 
565
        return new_path 
 
566
 
 
567
    def path2id(self, path):
 
568
        """Return the id of the file present at path in the target tree."""
 
569
        file_id = self._new_id.get(path)
 
570
        if file_id is not None:
 
571
            return file_id
 
572
        old_path = self.old_path(path)
 
573
        if old_path is None:
 
574
            return None
 
575
        if old_path in self.deleted:
 
576
            return None
 
577
        if getattr(self.base_tree, 'path2id', None) is not None:
 
578
            return self.base_tree.path2id(old_path)
 
579
        else:
 
580
            return self.base_tree.inventory.path2id(old_path)
 
581
 
 
582
    def id2path(self, file_id):
 
583
        """Return the new path in the target tree of the file with id file_id"""
 
584
        path = self._new_id_r.get(file_id)
 
585
        if path is not None:
 
586
            return path
 
587
        old_path = self.base_tree.id2path(file_id)
 
588
        if old_path is None:
 
589
            return None
 
590
        if old_path in self.deleted:
 
591
            return None
 
592
        return self.new_path(old_path)
 
593
 
 
594
    def old_contents_id(self, file_id):
 
595
        """Return the id in the base_tree for the given file_id.
 
596
        Return None if the file did not exist in base.
 
597
        """
 
598
        if self.contents_by_id:
 
599
            if self.base_tree.has_id(file_id):
 
600
                return file_id
 
601
            else:
 
602
                return None
 
603
        new_path = self.id2path(file_id)
 
604
        return self.base_tree.path2id(new_path)
 
605
        
 
606
    def get_file(self, file_id):
 
607
        """Return a file-like object containing the new contents of the
 
608
        file given by file_id.
 
609
 
 
610
        TODO:   It might be nice if this actually generated an entry
 
611
                in the text-store, so that the file contents would
 
612
                then be cached.
 
613
        """
 
614
        base_id = self.old_contents_id(file_id)
 
615
        if (base_id is not None and
 
616
            base_id != self.base_tree.inventory.root.file_id):
 
617
            patch_original = self.base_tree.get_file(base_id)
 
618
        else:
 
619
            patch_original = None
 
620
        file_patch = self.patches.get(self.id2path(file_id))
 
621
        if file_patch is None:
 
622
            if (patch_original is None and 
 
623
                self.get_kind(file_id) == 'directory'):
 
624
                return StringIO()
 
625
            assert patch_original is not None, "None: %s" % file_id
 
626
            return patch_original
 
627
 
 
628
        assert not file_patch.startswith('\\'), \
 
629
            'Malformed patch for %s, %r' % (file_id, file_patch)
 
630
        return patched_file(file_patch, patch_original)
 
631
 
 
632
    def get_symlink_target(self, file_id):
 
633
        new_path = self.id2path(file_id)
 
634
        try:
 
635
            return self._targets[new_path]
 
636
        except KeyError:
 
637
            return self.base_tree.get_symlink_target(file_id)
 
638
 
 
639
    def get_kind(self, file_id):
 
640
        if file_id in self._kinds:
 
641
            return self._kinds[file_id]
 
642
        return self.base_tree.inventory[file_id].kind
 
643
 
 
644
    def is_executable(self, file_id):
 
645
        path = self.id2path(file_id)
 
646
        if path in self._executable:
 
647
            return self._executable[path]
 
648
        else:
 
649
            return self.base_tree.inventory[file_id].executable
 
650
 
 
651
    def get_last_changed(self, file_id):
 
652
        path = self.id2path(file_id)
 
653
        if path in self._last_changed:
 
654
            return self._last_changed[path]
 
655
        return self.base_tree.inventory[file_id].revision
 
656
 
 
657
    def get_size_and_sha1(self, file_id):
 
658
        """Return the size and sha1 hash of the given file id.
 
659
        If the file was not locally modified, this is extracted
 
660
        from the base_tree. Rather than re-reading the file.
 
661
        """
 
662
        new_path = self.id2path(file_id)
 
663
        if new_path is None:
 
664
            return None, None
 
665
        if new_path not in self.patches:
 
666
            # If the entry does not have a patch, then the
 
667
            # contents must be the same as in the base_tree
 
668
            ie = self.base_tree.inventory[file_id]
 
669
            if ie.text_size is None:
 
670
                return ie.text_size, ie.text_sha1
 
671
            return int(ie.text_size), ie.text_sha1
 
672
        fileobj = self.get_file(file_id)
 
673
        content = fileobj.read()
 
674
        return len(content), sha_string(content)
 
675
 
 
676
    def _get_inventory(self):
 
677
        """Build up the inventory entry for the BundleTree.
 
678
 
 
679
        This need to be called before ever accessing self.inventory
 
680
        """
 
681
        from os.path import dirname, basename
 
682
 
 
683
        assert self.base_tree is not None
 
684
        base_inv = self.base_tree.inventory
 
685
        inv = Inventory(None, self.revision_id)
 
686
 
 
687
        def add_entry(file_id):
 
688
            path = self.id2path(file_id)
 
689
            if path is None:
 
690
                return
 
691
            if path == '':
 
692
                parent_id = None
 
693
            else:
 
694
                parent_path = dirname(path)
 
695
                parent_id = self.path2id(parent_path)
 
696
 
 
697
            kind = self.get_kind(file_id)
 
698
            revision_id = self.get_last_changed(file_id)
 
699
 
 
700
            name = basename(path)
 
701
            if kind == 'directory':
 
702
                ie = InventoryDirectory(file_id, name, parent_id)
 
703
            elif kind == 'file':
 
704
                ie = InventoryFile(file_id, name, parent_id)
 
705
                ie.executable = self.is_executable(file_id)
 
706
            elif kind == 'symlink':
 
707
                ie = InventoryLink(file_id, name, parent_id)
 
708
                ie.symlink_target = self.get_symlink_target(file_id)
 
709
            ie.revision = revision_id
 
710
 
 
711
            if kind in ('directory', 'symlink'):
 
712
                ie.text_size, ie.text_sha1 = None, None
 
713
            else:
 
714
                ie.text_size, ie.text_sha1 = self.get_size_and_sha1(file_id)
 
715
            if (ie.text_size is None) and (kind == 'file'):
 
716
                raise BzrError('Got a text_size of None for file_id %r' % file_id)
 
717
            inv.add(ie)
 
718
 
 
719
        sorted_entries = self.sorted_path_id()
 
720
        for path, file_id in sorted_entries:
 
721
            add_entry(file_id)
 
722
 
 
723
        return inv
 
724
 
 
725
    # Have to overload the inherited inventory property
 
726
    # because _get_inventory is only called in the parent.
 
727
    # Reading the docs, property() objects do not use
 
728
    # overloading, they use the function as it was defined
 
729
    # at that instant
 
730
    inventory = property(_get_inventory)
 
731
 
 
732
    def __iter__(self):
 
733
        for path, entry in self.inventory.iter_entries():
 
734
            yield entry.file_id
 
735
 
 
736
    def sorted_path_id(self):
 
737
        paths = []
 
738
        for result in self._new_id.iteritems():
 
739
            paths.append(result)
 
740
        for id in self.base_tree:
 
741
            path = self.id2path(id)
 
742
            if path is None:
 
743
                continue
 
744
            paths.append((path, id))
 
745
        paths.sort()
 
746
        return paths
 
747
 
 
748
 
 
749
def patched_file(file_patch, original):
 
750
    """Produce a file-like object with the patched version of a text"""
 
751
    from bzrlib.patches import iter_patched
 
752
    from bzrlib.iterablefile import IterableFile
 
753
    if file_patch == "":
 
754
        return IterableFile(())
 
755
    # string.splitlines(True) also splits on '\r', but the iter_patched code
 
756
    # only expects to iterate over '\n' style lines
 
757
    return IterableFile(iter_patched(original,
 
758
                StringIO(file_patch).readlines()))