/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: Marius Kruger
  • Date: 2010-07-10 21:28:56 UTC
  • mto: (5384.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 5385.
  • Revision ID: marius.kruger@enerweb.co.za-20100710212856-uq4ji3go0u5se7hx
* Update documentation
* add NEWS

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
"""Read in a bundle stream, and process it into a BundleReader object."""
18
18
 
19
 
from __future__ import absolute_import
20
 
 
21
19
import base64
22
 
from io import BytesIO
 
20
from cStringIO import StringIO
23
21
import os
24
22
import pprint
25
23
 
26
 
from ... import (
27
 
    cache_utf8,
 
24
from bzrlib import (
28
25
    osutils,
29
26
    timestamp,
30
27
    )
31
 
from . import apply_bundle
32
 
from ...errors import (
33
 
    TestamentMismatch,
34
 
    BzrError,
35
 
    NoSuchId,
36
 
    )
37
 
from ..inventory import (
38
 
    Inventory,
39
 
    InventoryDirectory,
40
 
    InventoryFile,
41
 
    InventoryLink,
42
 
    )
43
 
from ...osutils import sha_string, sha_strings, pathjoin
44
 
from ...revision import Revision, NULL_REVISION
45
 
from ...sixish import (
46
 
    viewitems,
47
 
    )
48
 
from ..testament import StrictTestament
49
 
from ...trace import mutter, warning
50
 
from ...tree import (
51
 
    InterTree,
52
 
    Tree,
53
 
    )
54
 
from ..xml5 import serializer_v5
 
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
55
43
 
56
44
 
57
45
class RevisionInfo(object):
58
46
    """Gets filled out for each revision object that is read.
59
47
    """
60
 
 
61
48
    def __init__(self, revision_id):
62
49
        self.revision_id = revision_id
63
50
        self.sha1 = None
78
65
 
79
66
    def as_revision(self):
80
67
        rev = Revision(revision_id=self.revision_id,
81
 
                       committer=self.committer,
82
 
                       timestamp=float(self.timestamp),
83
 
                       timezone=int(self.timezone),
84
 
                       inventory_sha1=self.inventory_sha1,
85
 
                       message='\n'.join(self.message))
 
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))
86
73
 
87
74
        if self.parent_ids:
88
75
            rev.parent_ids.extend(self.parent_ids)
97
84
                    value = ''
98
85
                else:
99
86
                    key = str(property[:key_end])
100
 
                    value = property[key_end + 2:]
 
87
                    value = property[key_end+2:]
101
88
                rev.properties[key] = value
102
89
 
103
90
        return rev
112
99
        revision_info.timestamp = revision.timestamp
113
100
        revision_info.message = revision.message.split('\n')
114
101
        revision_info.properties = [': '.join(p) for p in
115
 
                                    viewitems(revision.properties)]
 
102
                                    revision.properties.iteritems()]
116
103
        return revision_info
117
104
 
118
105
 
120
107
    """This contains the meta information. Stuff that allows you to
121
108
    recreate the revision or inventory XML.
122
109
    """
123
 
 
124
110
    def __init__(self, bundle_format=None):
125
111
        self.bundle_format = None
126
112
        self.committer = None
150
136
        split up, based on the assumptions that can be made
151
137
        when information is missing.
152
138
        """
153
 
        from breezy.timestamp import unpack_highres_date
 
139
        from bzrlib.timestamp import unpack_highres_date
154
140
        # Put in all of the guessable information.
155
141
        if not self.timestamp and self.date:
156
142
            self.timestamp, self.timezone = unpack_highres_date(self.date)
160
146
            if rev.timestamp is None:
161
147
                if rev.date is not None:
162
148
                    rev.timestamp, rev.timezone = \
163
 
                        unpack_highres_date(rev.date)
 
149
                            unpack_highres_date(rev.date)
164
150
                else:
165
151
                    rev.timestamp = self.timestamp
166
152
                    rev.timezone = self.timezone
215
201
        revision_info = self.get_revision_info(revision_id)
216
202
        inventory_revision_id = revision_id
217
203
        bundle_tree = BundleTree(repository.revision_tree(base),
218
 
                                 inventory_revision_id)
 
204
                                  inventory_revision_id)
219
205
        self._update_tree(bundle_tree, revision_id)
220
206
 
221
207
        inv = bundle_tree.inventory
222
208
        self._validate_inventory(inv, revision_id)
223
 
        self._validate_revision(bundle_tree, revision_id)
 
209
        self._validate_revision(inv, revision_id)
224
210
 
225
211
        return bundle_tree
226
212
 
231
217
        """
232
218
        rev_to_sha = {}
233
219
        inv_to_sha = {}
234
 
 
235
220
        def add_sha(d, revision_id, sha1):
236
221
            if revision_id is None:
237
222
                if sha1 is not None:
238
223
                    raise BzrError('A Null revision should always'
239
 
                                   'have a null sha1 hash')
 
224
                        'have a null sha1 hash')
240
225
                return
241
226
            if revision_id in d:
242
227
                # This really should have been validated as part
243
228
                # of _validate_revisions but lets do it again
244
229
                if sha1 != d[revision_id]:
245
230
                    raise BzrError('** Revision %r referenced with 2 different'
246
 
                                   ' sha hashes %s != %s' % (revision_id,
247
 
                                                             sha1, d[revision_id]))
 
231
                            ' sha hashes %s != %s' % (revision_id,
 
232
                                sha1, d[revision_id]))
248
233
            else:
249
234
                d[revision_id] = sha1
250
235
 
260
245
 
261
246
        count = 0
262
247
        missing = {}
263
 
        for revision_id, sha1 in viewitems(rev_to_sha):
 
248
        for revision_id, sha1 in rev_to_sha.iteritems():
264
249
            if repository.has_revision(revision_id):
265
250
                testament = StrictTestament.from_revision(repository,
266
251
                                                          revision_id)
268
253
                                                                revision_id)
269
254
                if sha1 != local_sha1:
270
255
                    raise BzrError('sha1 mismatch. For revision id {%s}'
271
 
                                   'local: %s, bundle: %s' % (revision_id, local_sha1, sha1))
 
256
                            'local: %s, bundle: %s' % (revision_id, local_sha1, sha1))
272
257
                else:
273
258
                    count += 1
274
259
            elif revision_id not in checked:
286
271
        so build up an inventory, and make sure the hashes match.
287
272
        """
288
273
        # Now we should have a complete inventory entry.
289
 
        cs = serializer_v5.write_inventory_to_chunks(inv)
290
 
        sha1 = sha_strings(cs)
 
274
        s = serializer_v5.write_inventory_to_string(inv)
 
275
        sha1 = sha_string(s)
291
276
        # Target revision is the last entry in the real_revisions list
292
277
        rev = self.get_revision(revision_id)
293
278
        if rev.revision_id != revision_id:
294
279
            raise AssertionError()
295
280
        if sha1 != rev.inventory_sha1:
296
 
            with open(',,bogus-inv', 'wb') as f:
297
 
                f.writelines(cs)
 
281
            f = open(',,bogus-inv', 'wb')
 
282
            try:
 
283
                f.write(s)
 
284
            finally:
 
285
                f.close()
298
286
            warning('Inventory sha hash mismatch for revision %s. %s'
299
287
                    ' != %s' % (revision_id, sha1, rev.inventory_sha1))
300
288
 
301
 
    def _testament(self, revision, tree):
302
 
        raise NotImplementedError(self._testament)
303
 
 
304
 
    def _validate_revision(self, tree, revision_id):
 
289
    def _validate_revision(self, inventory, revision_id):
305
290
        """Make sure all revision entries match their checksum."""
306
291
 
307
 
        # This is a mapping from each revision id to its sha hash
 
292
        # This is a mapping from each revision id to it's sha hash
308
293
        rev_to_sha1 = {}
309
294
 
310
295
        rev = self.get_revision(revision_id)
313
298
            raise AssertionError()
314
299
        if not (rev.revision_id == revision_id):
315
300
            raise AssertionError()
316
 
        testament = self._testament(rev, tree)
317
 
        sha1 = testament.as_sha1()
 
301
        sha1 = self._testament_sha1(rev, inventory)
318
302
        if sha1 != rev_info.sha1:
319
303
            raise TestamentMismatch(rev.revision_id, rev_info.sha1, sha1)
320
304
        if rev.revision_id in rev_to_sha1:
321
305
            raise BzrError('Revision {%s} given twice in the list'
322
 
                           % (rev.revision_id))
 
306
                    % (rev.revision_id))
323
307
        rev_to_sha1[rev.revision_id] = sha1
324
308
 
325
309
    def _update_tree(self, bundle_tree, revision_id):
333
317
            if last_changed is not None:
334
318
                # last_changed will be a Unicode string because of how it was
335
319
                # read. Convert it back to utf8.
336
 
                changed_revision_id = cache_utf8.encode(last_changed)
 
320
                changed_revision_id = osutils.safe_revision_id(last_changed,
 
321
                                                               warn=False)
337
322
            else:
338
323
                changed_revision_id = revision_id
339
324
            bundle_tree.note_last_changed(path, changed_revision_id)
360
345
 
361
346
        def do_patch(path, lines, encoding):
362
347
            if encoding == 'base64':
363
 
                patch = base64.b64decode(b''.join(lines))
 
348
                patch = base64.decodestring(''.join(lines))
364
349
            elif encoding is None:
365
 
                patch = b''.join(lines)
 
350
                patch =  ''.join(lines)
366
351
            else:
367
352
                raise ValueError(encoding)
368
353
            bundle_tree.note_patch(path, patch)
371
356
            info = extra.split(' // ')
372
357
            if len(info) < 2:
373
358
                raise BzrError('renamed action lines need both a from and to'
374
 
                               ': %r' % extra)
 
359
                        ': %r' % extra)
375
360
            old_path = info[0]
376
361
            if info[1].startswith('=> '):
377
362
                new_path = info[1][3:]
390
375
                # TODO: in the future we might allow file ids to be
391
376
                # given for removed entries
392
377
                raise BzrError('removed action lines should only have the path'
393
 
                               ': %r' % extra)
 
378
                        ': %r' % extra)
394
379
            path = info[0]
395
380
            bundle_tree.note_deletion(path)
396
381
 
398
383
            info = extra.split(' // ')
399
384
            if len(info) <= 1:
400
385
                raise BzrError('add action lines require the path and file id'
401
 
                               ': %r' % extra)
 
386
                        ': %r' % extra)
402
387
            elif len(info) > 5:
403
388
                raise BzrError('add action lines have fewer than 5 entries.'
404
 
                               ': %r' % extra)
 
389
                        ': %r' % extra)
405
390
            path = info[0]
406
391
            if not info[1].startswith('file-id:'):
407
392
                raise BzrError('The file-id should follow the path for an add'
408
 
                               ': %r' % extra)
 
393
                        ': %r' % extra)
409
394
            # This will be Unicode because of how the stream is read. Turn it
410
395
            # back into a utf8 file_id
411
 
            file_id = cache_utf8.encode(info[1][8:])
 
396
            file_id = osutils.safe_file_id(info[1][8:], warn=False)
412
397
 
413
398
            bundle_tree.note_id(file_id, path, kind)
414
399
            # this will be overridden in extra_info if executable is specified.
423
408
            info = extra.split(' // ')
424
409
            if len(info) < 1:
425
410
                raise BzrError('modified action lines have at least'
426
 
                               'the path in them: %r' % extra)
 
411
                        'the path in them: %r' % extra)
427
412
            path = info[0]
428
413
 
429
414
            last_modified, encoding = extra_info(info[1:], path)
432
417
                do_patch(path, lines, encoding)
433
418
 
434
419
        valid_actions = {
435
 
            'renamed': renamed,
436
 
            'removed': removed,
437
 
            'added': added,
438
 
            'modified': modified
 
420
            'renamed':renamed,
 
421
            'removed':removed,
 
422
            'added':added,
 
423
            'modified':modified
439
424
        }
440
425
        for action_line, lines in \
441
 
                self.get_revision_info(revision_id).tree_actions:
 
426
            self.get_revision_info(revision_id).tree_actions:
442
427
            first = action_line.find(' ')
443
428
            if first == -1:
444
429
                raise BzrError('Bogus action line'
445
 
                               ' (no opening space): %r' % action_line)
446
 
            second = action_line.find(' ', first + 1)
 
430
                        ' (no opening space): %r' % action_line)
 
431
            second = action_line.find(' ', first+1)
447
432
            if second == -1:
448
433
                raise BzrError('Bogus action line'
449
 
                               ' (missing second space): %r' % action_line)
 
434
                        ' (missing second space): %r' % action_line)
450
435
            action = action_line[:first]
451
 
            kind = action_line[first + 1:second]
 
436
            kind = action_line[first+1:second]
452
437
            if kind not in ('file', 'directory', 'symlink'):
453
438
                raise BzrError('Bogus action line'
454
 
                               ' (invalid object kind %r): %r' % (kind, action_line))
455
 
            extra = action_line[second + 1:]
 
439
                        ' (invalid object kind %r): %r' % (kind, action_line))
 
440
            extra = action_line[second+1:]
456
441
 
457
442
            if action not in valid_actions:
458
443
                raise BzrError('Bogus action line'
459
 
                               ' (unrecognized action): %r' % action_line)
 
444
                        ' (unrecognized action): %r' % action_line)
460
445
            valid_actions[action](kind, extra, lines)
461
446
 
462
447
    def install_revisions(self, target_repo, stream_input=True):
477
462
 
478
463
 
479
464
class BundleTree(Tree):
480
 
 
481
465
    def __init__(self, base_tree, revision_id):
482
466
        self.base_tree = base_tree
483
 
        self._renamed = {}  # Mapping from old_path => new_path
484
 
        self._renamed_r = {}  # new_path => old_path
485
 
        self._new_id = {}  # new_path => new_id
486
 
        self._new_id_r = {}  # new_id => new_path
487
 
        self._kinds = {}  # new_path => kind
488
 
        self._last_changed = {}  # new_id => revision_id
489
 
        self._executable = {}  # new_id => executable value
 
467
        self._renamed = {} # Mapping from old_path => new_path
 
468
        self._renamed_r = {} # new_path => old_path
 
469
        self._new_id = {} # new_path => new_id
 
470
        self._new_id_r = {} # new_id => new_path
 
471
        self._kinds = {} # new_id => kind
 
472
        self._last_changed = {} # new_id => revision_id
 
473
        self._executable = {} # new_id => executable value
490
474
        self.patches = {}
491
 
        self._targets = {}  # new path => new symlink target
 
475
        self._targets = {} # new path => new symlink target
492
476
        self.deleted = []
 
477
        self.contents_by_id = True
493
478
        self.revision_id = revision_id
494
479
        self._inventory = None
495
 
        self._base_inter = InterTree.get(self.base_tree, self)
496
480
 
497
481
    def __str__(self):
498
482
        return pprint.pformat(self.__dict__)
510
494
        """Files that don't exist in base need a new id."""
511
495
        self._new_id[new_path] = new_id
512
496
        self._new_id_r[new_id] = new_path
513
 
        self._kinds[new_path] = kind
 
497
        self._kinds[new_id] = kind
514
498
 
515
499
    def note_last_changed(self, file_id, revision_id):
516
500
        if (file_id in self._last_changed
517
501
                and self._last_changed[file_id] != revision_id):
518
502
            raise BzrError('Mismatched last-changed revision for file_id {%s}'
519
 
                           ': %s != %s' % (file_id,
520
 
                                           self._last_changed[file_id],
521
 
                                           revision_id))
 
503
                    ': %s != %s' % (file_id,
 
504
                                    self._last_changed[file_id],
 
505
                                    revision_id))
522
506
        self._last_changed[file_id] = revision_id
523
507
 
524
508
    def note_patch(self, new_path, patch):
543
527
        old_path = self._renamed.get(new_path)
544
528
        if old_path is not None:
545
529
            return old_path
546
 
        dirname, basename = os.path.split(new_path)
 
530
        dirname,basename = os.path.split(new_path)
547
531
        # dirname is not '' doesn't work, because
548
532
        # dirname may be a unicode entry, and is
549
533
        # requires the objects to be identical
555
539
                old_path = pathjoin(old_dir, basename)
556
540
        else:
557
541
            old_path = new_path
558
 
        # If the new path wasn't in renamed, the old one shouldn't be in
559
 
        # renamed_r
 
542
        #If the new path wasn't in renamed, the old one shouldn't be in
 
543
        #renamed_r
560
544
        if old_path in self._renamed_r:
561
545
            return None
562
546
        return old_path
572
556
            return new_path
573
557
        if new_path in self._renamed:
574
558
            return None
575
 
        dirname, basename = os.path.split(old_path)
 
559
        dirname,basename = os.path.split(old_path)
576
560
        if dirname != '':
577
561
            new_dir = self.new_path(dirname)
578
562
            if new_dir is None:
581
565
                new_path = pathjoin(new_dir, basename)
582
566
        else:
583
567
            new_path = old_path
584
 
        # If the old path wasn't in renamed, the new one shouldn't be in
585
 
        # renamed_r
 
568
        #If the old path wasn't in renamed, the new one shouldn't be in
 
569
        #renamed_r
586
570
        if new_path in self._renamed:
587
571
            return None
588
572
        return new_path
597
581
            return None
598
582
        if old_path in self.deleted:
599
583
            return None
600
 
        return self.base_tree.path2id(old_path)
 
584
        if getattr(self.base_tree, 'path2id', None) is not None:
 
585
            return self.base_tree.path2id(old_path)
 
586
        else:
 
587
            return self.base_tree.inventory.path2id(old_path)
601
588
 
602
 
    def id2path(self, file_id, recurse='down'):
 
589
    def id2path(self, file_id):
603
590
        """Return the new path in the target tree of the file with id file_id"""
604
591
        path = self._new_id_r.get(file_id)
605
592
        if path is not None:
606
593
            return path
607
 
        old_path = self.base_tree.id2path(file_id, recurse)
 
594
        old_path = self.base_tree.id2path(file_id)
608
595
        if old_path is None:
609
 
            raise NoSuchId(file_id, self)
 
596
            return None
610
597
        if old_path in self.deleted:
611
 
            raise NoSuchId(file_id, self)
612
 
        new_path = self.new_path(old_path)
613
 
        if new_path is None:
614
 
            raise NoSuchId(file_id, self)
615
 
        return new_path
616
 
 
617
 
    def get_file(self, path):
 
598
            return None
 
599
        return self.new_path(old_path)
 
600
 
 
601
    def old_contents_id(self, file_id):
 
602
        """Return the id in the base_tree for the given file_id.
 
603
        Return None if the file did not exist in base.
 
604
        """
 
605
        if self.contents_by_id:
 
606
            if self.base_tree.has_id(file_id):
 
607
                return file_id
 
608
            else:
 
609
                return None
 
610
        new_path = self.id2path(file_id)
 
611
        return self.base_tree.path2id(new_path)
 
612
 
 
613
    def get_file(self, file_id):
618
614
        """Return a file-like object containing the new contents of the
619
615
        file given by file_id.
620
616
 
622
618
                in the text-store, so that the file contents would
623
619
                then be cached.
624
620
        """
625
 
        old_path = self._base_inter.find_source_path(path)
626
 
        if old_path is None:
 
621
        base_id = self.old_contents_id(file_id)
 
622
        if (base_id is not None and
 
623
            base_id != self.base_tree.inventory.root.file_id):
 
624
            patch_original = self.base_tree.get_file(base_id)
 
625
        else:
627
626
            patch_original = None
628
 
        else:
629
 
            patch_original = self.base_tree.get_file(old_path)
630
 
        file_patch = self.patches.get(path)
 
627
        file_patch = self.patches.get(self.id2path(file_id))
631
628
        if file_patch is None:
632
629
            if (patch_original is None and
633
 
                    self.kind(path) == 'directory'):
634
 
                return BytesIO()
 
630
                self.get_kind(file_id) == 'directory'):
 
631
                return StringIO()
635
632
            if patch_original is None:
636
633
                raise AssertionError("None: %s" % file_id)
637
634
            return patch_original
638
635
 
639
 
        if file_patch.startswith(b'\\'):
 
636
        if file_patch.startswith('\\'):
640
637
            raise ValueError(
641
638
                'Malformed patch for %s, %r' % (file_id, file_patch))
642
639
        return patched_file(file_patch, patch_original)
643
640
 
644
 
    def get_symlink_target(self, path):
645
 
        try:
646
 
            return self._targets[path]
647
 
        except KeyError:
648
 
            old_path = self.old_path(path)
649
 
            return self.base_tree.get_symlink_target(old_path)
650
 
 
651
 
    def kind(self, path):
652
 
        try:
653
 
            return self._kinds[path]
654
 
        except KeyError:
655
 
            old_path = self.old_path(path)
656
 
            return self.base_tree.kind(old_path)
657
 
 
658
 
    def get_file_revision(self, path):
659
 
        if path in self._last_changed:
660
 
            return self._last_changed[path]
661
 
        else:
662
 
            old_path = self.old_path(path)
663
 
            return self.base_tree.get_file_revision(old_path)
664
 
 
665
 
    def is_executable(self, path):
 
641
    def get_symlink_target(self, file_id):
 
642
        new_path = self.id2path(file_id)
 
643
        try:
 
644
            return self._targets[new_path]
 
645
        except KeyError:
 
646
            return self.base_tree.get_symlink_target(file_id)
 
647
 
 
648
    def get_kind(self, file_id):
 
649
        if file_id in self._kinds:
 
650
            return self._kinds[file_id]
 
651
        return self.base_tree.inventory[file_id].kind
 
652
 
 
653
    def is_executable(self, file_id):
 
654
        path = self.id2path(file_id)
666
655
        if path in self._executable:
667
656
            return self._executable[path]
668
657
        else:
669
 
            old_path = self.old_path(path)
670
 
            return self.base_tree.is_executable(old_path)
 
658
            return self.base_tree.inventory[file_id].executable
671
659
 
672
 
    def get_last_changed(self, path):
 
660
    def get_last_changed(self, file_id):
 
661
        path = self.id2path(file_id)
673
662
        if path in self._last_changed:
674
663
            return self._last_changed[path]
675
 
        old_path = self.old_path(path)
676
 
        return self.base_tree.get_file_revision(old_path)
 
664
        return self.base_tree.inventory[file_id].revision
677
665
 
678
 
    def get_size_and_sha1(self, new_path):
 
666
    def get_size_and_sha1(self, file_id):
679
667
        """Return the size and sha1 hash of the given file id.
680
668
        If the file was not locally modified, this is extracted
681
669
        from the base_tree. Rather than re-reading the file.
682
670
        """
 
671
        new_path = self.id2path(file_id)
683
672
        if new_path is None:
684
673
            return None, None
685
674
        if new_path not in self.patches:
686
675
            # If the entry does not have a patch, then the
687
676
            # contents must be the same as in the base_tree
688
 
            base_path = self.old_path(new_path)
689
 
            text_size = self.base_tree.get_file_size(base_path)
690
 
            text_sha1 = self.base_tree.get_file_sha1(base_path)
691
 
            return text_size, text_sha1
692
 
        fileobj = self.get_file(new_path)
 
677
            ie = self.base_tree.inventory[file_id]
 
678
            if ie.text_size is None:
 
679
                return ie.text_size, ie.text_sha1
 
680
            return int(ie.text_size), ie.text_sha1
 
681
        fileobj = self.get_file(file_id)
693
682
        content = fileobj.read()
694
683
        return len(content), sha_string(content)
695
684
 
699
688
        This need to be called before ever accessing self.inventory
700
689
        """
701
690
        from os.path import dirname, basename
 
691
        base_inv = self.base_tree.inventory
702
692
        inv = Inventory(None, self.revision_id)
703
693
 
704
 
        def add_entry(path, file_id):
 
694
        def add_entry(file_id):
 
695
            path = self.id2path(file_id)
 
696
            if path is None:
 
697
                return
705
698
            if path == '':
706
699
                parent_id = None
707
700
            else:
708
701
                parent_path = dirname(path)
709
702
                parent_id = self.path2id(parent_path)
710
703
 
711
 
            kind = self.kind(path)
712
 
            revision_id = self.get_last_changed(path)
 
704
            kind = self.get_kind(file_id)
 
705
            revision_id = self.get_last_changed(file_id)
713
706
 
714
707
            name = basename(path)
715
708
            if kind == 'directory':
716
709
                ie = InventoryDirectory(file_id, name, parent_id)
717
710
            elif kind == 'file':
718
711
                ie = InventoryFile(file_id, name, parent_id)
719
 
                ie.executable = self.is_executable(path)
 
712
                ie.executable = self.is_executable(file_id)
720
713
            elif kind == 'symlink':
721
714
                ie = InventoryLink(file_id, name, parent_id)
722
 
                ie.symlink_target = self.get_symlink_target(path)
 
715
                ie.symlink_target = self.get_symlink_target(file_id)
723
716
            ie.revision = revision_id
724
717
 
725
 
            if kind == 'file':
726
 
                ie.text_size, ie.text_sha1 = self.get_size_and_sha1(path)
727
 
                if ie.text_size is None:
728
 
                    raise BzrError(
729
 
                        'Got a text_size of None for file_id %r' % file_id)
 
718
            if kind in ('directory', 'symlink'):
 
719
                ie.text_size, ie.text_sha1 = None, None
 
720
            else:
 
721
                ie.text_size, ie.text_sha1 = self.get_size_and_sha1(file_id)
 
722
            if (ie.text_size is None) and (kind == 'file'):
 
723
                raise BzrError('Got a text_size of None for file_id %r' % file_id)
730
724
            inv.add(ie)
731
725
 
732
726
        sorted_entries = self.sorted_path_id()
733
727
        for path, file_id in sorted_entries:
734
 
            add_entry(path, file_id)
 
728
            add_entry(file_id)
735
729
 
736
730
        return inv
737
731
 
742
736
    # at that instant
743
737
    inventory = property(_get_inventory)
744
738
 
745
 
    root_inventory = property(_get_inventory)
746
 
 
747
 
    def all_file_ids(self):
748
 
        return {entry.file_id for path, entry in self.inventory.iter_entries()}
749
 
 
750
 
    def all_versioned_paths(self):
751
 
        return {path for path, entry in self.inventory.iter_entries()}
752
 
 
753
 
    def list_files(self, include_root=False, from_dir=None, recursive=True):
754
 
        # The only files returned by this are those from the version
755
 
        inv = self.inventory
756
 
        if from_dir is None:
757
 
            from_dir_id = None
758
 
        else:
759
 
            from_dir_id = inv.path2id(from_dir)
760
 
            if from_dir_id is None:
761
 
                # Directory not versioned
762
 
                return
763
 
        entries = inv.iter_entries(from_dir=from_dir_id, recursive=recursive)
764
 
        if inv.root is not None and not include_root and from_dir is None:
765
 
            # skip the root for compatibility with the current apis.
766
 
            next(entries)
767
 
        for path, entry in entries:
768
 
            yield path, 'V', entry.kind, entry
 
739
    def __iter__(self):
 
740
        for path, entry in self.inventory.iter_entries():
 
741
            yield entry.file_id
769
742
 
770
743
    def sorted_path_id(self):
771
744
        paths = []
772
 
        for result in viewitems(self._new_id):
 
745
        for result in self._new_id.iteritems():
773
746
            paths.append(result)
774
 
        for id in self.base_tree.all_file_ids():
775
 
            try:
776
 
                path = self.id2path(id, recurse='none')
777
 
            except NoSuchId:
 
747
        for id in self.base_tree:
 
748
            path = self.id2path(id)
 
749
            if path is None:
778
750
                continue
779
751
            paths.append((path, id))
780
752
        paths.sort()
783
755
 
784
756
def patched_file(file_patch, original):
785
757
    """Produce a file-like object with the patched version of a text"""
786
 
    from breezy.patches import iter_patched
787
 
    from breezy.iterablefile import IterableFile
788
 
    if file_patch == b"":
 
758
    from bzrlib.patches import iter_patched
 
759
    from bzrlib.iterablefile import IterableFile
 
760
    if file_patch == "":
789
761
        return IterableFile(())
790
762
    # string.splitlines(True) also splits on '\r', but the iter_patched code
791
763
    # only expects to iterate over '\n' style lines
792
764
    return IterableFile(iter_patched(original,
793
 
                                     BytesIO(file_patch).readlines()))
 
765
                StringIO(file_patch).readlines()))