~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/inventory.py

  • Committer: Vincent Ladeuil
  • Date: 2009-07-10 08:33:11 UTC
  • mfrom: (4503.1.3 tree-has-changes)
  • mto: This revision was merged to the branch mainline in revision 4525.
  • Revision ID: v.ladeuil+lp@free.fr-20090710083311-ulnr2ic6lvevjr3a
Quicker check for changes in mutable trees

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
31
31
lazy_import(globals(), """
32
32
import collections
33
33
import copy
 
34
import os
34
35
import re
35
36
import tarfile
36
37
 
 
38
import bzrlib
37
39
from bzrlib import (
38
40
    chk_map,
39
41
    errors,
40
42
    generate_ids,
41
43
    osutils,
 
44
    symbol_versioning,
42
45
    )
43
46
""")
44
47
 
45
 
from bzrlib import (
46
 
    lazy_regex,
47
 
    trace,
48
 
    )
49
 
 
50
 
from bzrlib.static_tuple import StaticTuple
51
 
from bzrlib.symbol_versioning import (
52
 
    deprecated_in,
53
 
    deprecated_method,
54
 
    )
 
48
from bzrlib.errors import (
 
49
    BzrCheckError,
 
50
    BzrError,
 
51
    )
 
52
from bzrlib.symbol_versioning import deprecated_in, deprecated_method
 
53
from bzrlib.trace import mutter
55
54
 
56
55
 
57
56
class InventoryEntry(object):
104
103
    InventoryDirectory('2325', 'wibble', parent_id='123', revision=None)
105
104
    >>> i.path2id('src/wibble')
106
105
    '2325'
 
106
    >>> '2325' in i
 
107
    True
107
108
    >>> i.add(InventoryFile('2326', 'wibble.c', '2325'))
108
109
    InventoryFile('2326', 'wibble.c', parent_id='2325', sha1=None, len=None, revision=None)
109
110
    >>> i['2326']
129
130
    RENAMED = 'renamed'
130
131
    MODIFIED_AND_RENAMED = 'modified and renamed'
131
132
 
132
 
    __slots__ = ['file_id', 'revision', 'parent_id', 'name']
133
 
 
134
 
    # Attributes that all InventoryEntry instances are expected to have, but
135
 
    # that don't vary for all kinds of entry.  (e.g. symlink_target is only
136
 
    # relevant to InventoryLink, so there's no reason to make every
137
 
    # InventoryFile instance allocate space to hold a value for it.)
138
 
    # Attributes that only vary for files: executable, text_sha1, text_size,
139
 
    # text_id
140
 
    executable = False
141
 
    text_sha1 = None
142
 
    text_size = None
143
 
    text_id = None
144
 
    # Attributes that only vary for symlinks: symlink_target
145
 
    symlink_target = None
146
 
    # Attributes that only vary for tree-references: reference_revision
147
 
    reference_revision = None
148
 
 
 
133
    __slots__ = []
149
134
 
150
135
    def detect_changes(self, old_entry):
151
136
        """Return a (text_modified, meta_modified) from this to old_entry.
172
157
        candidates = {}
173
158
        # identify candidate head revision ids.
174
159
        for inv in previous_inventories:
175
 
            if inv.has_id(self.file_id):
 
160
            if self.file_id in inv:
176
161
                ie = inv[self.file_id]
177
162
                if ie.revision in candidates:
178
163
                    # same revision value in two different inventories:
190
175
                    candidates[ie.revision] = ie
191
176
        return candidates
192
177
 
 
178
    @deprecated_method(deprecated_in((1, 6, 0)))
 
179
    def get_tar_item(self, root, dp, now, tree):
 
180
        """Get a tarfile item and a file stream for its content."""
 
181
        item = tarfile.TarInfo(osutils.pathjoin(root, dp).encode('utf8'))
 
182
        # TODO: would be cool to actually set it to the timestamp of the
 
183
        # revision it was last changed
 
184
        item.mtime = now
 
185
        fileobj = self._put_in_tar(item, tree)
 
186
        return item, fileobj
 
187
 
193
188
    def has_text(self):
194
189
        """Return true if the object this entry represents has textual data.
195
190
 
201
196
        """
202
197
        return False
203
198
 
204
 
    def __init__(self, file_id, name, parent_id):
 
199
    def __init__(self, file_id, name, parent_id, text_id=None):
205
200
        """Create an InventoryEntry
206
201
 
207
202
        The filename must be a single component, relative to the
218
213
        """
219
214
        if '/' in name or '\\' in name:
220
215
            raise errors.InvalidEntryName(name=name)
 
216
        self.executable = False
 
217
        self.revision = None
 
218
        self.text_sha1 = None
 
219
        self.text_size = None
221
220
        self.file_id = file_id
222
 
        self.revision = None
223
221
        self.name = name
 
222
        self.text_id = text_id
224
223
        self.parent_id = parent_id
 
224
        self.symlink_target = None
 
225
        self.reference_revision = None
225
226
 
226
227
    def kind_character(self):
227
228
        """Return a short kind indicator useful for appending to names."""
228
 
        raise errors.BzrError('unknown kind %r' % self.kind)
 
229
        raise BzrError('unknown kind %r' % self.kind)
229
230
 
230
231
    known_kinds = ('file', 'directory', 'symlink')
231
232
 
 
233
    def _put_in_tar(self, item, tree):
 
234
        """populate item for stashing in a tar, and return the content stream.
 
235
 
 
236
        If no content is available, return None.
 
237
        """
 
238
        raise BzrError("don't know how to export {%s} of kind %r" %
 
239
                       (self.file_id, self.kind))
 
240
 
 
241
    @deprecated_method(deprecated_in((1, 6, 0)))
 
242
    def put_on_disk(self, dest, dp, tree):
 
243
        """Create a representation of self on disk in the prefix dest.
 
244
 
 
245
        This is a template method - implement _put_on_disk in subclasses.
 
246
        """
 
247
        fullpath = osutils.pathjoin(dest, dp)
 
248
        self._put_on_disk(fullpath, tree)
 
249
        # mutter("  export {%s} kind %s to %s", self.file_id,
 
250
        #         self.kind, fullpath)
 
251
 
 
252
    def _put_on_disk(self, fullpath, tree):
 
253
        """Put this entry onto disk at fullpath, from tree tree."""
 
254
        raise BzrError("don't know how to export {%s} of kind %r" % (self.file_id, self.kind))
 
255
 
232
256
    def sorted_children(self):
233
257
        return sorted(self.children.items())
234
258
 
236
260
    def versionable_kind(kind):
237
261
        return (kind in ('file', 'directory', 'symlink', 'tree-reference'))
238
262
 
239
 
    def check(self, checker, rev_id, inv):
 
263
    def check(self, checker, rev_id, inv, tree):
240
264
        """Check this inventory entry is intact.
241
265
 
242
266
        This is a template method, override _check for kind specific
248
272
        :param rev_id: Revision id from which this InventoryEntry was loaded.
249
273
             Not necessarily the last-changed revision for this file.
250
274
        :param inv: Inventory from which the entry was loaded.
 
275
        :param tree: RevisionTree for this entry.
251
276
        """
252
277
        if self.parent_id is not None:
253
278
            if not inv.has_id(self.parent_id):
254
 
                raise errors.BzrCheckError(
255
 
                    'missing parent {%s} in inventory for revision {%s}' % (
256
 
                        self.parent_id, rev_id))
257
 
        checker._add_entry_to_text_key_references(inv, self)
258
 
        self._check(checker, rev_id)
 
279
                raise BzrCheckError('missing parent {%s} in inventory for revision {%s}'
 
280
                        % (self.parent_id, rev_id))
 
281
        self._check(checker, rev_id, tree)
259
282
 
260
 
    def _check(self, checker, rev_id):
 
283
    def _check(self, checker, rev_id, tree):
261
284
        """Check this inventory entry for kind specific errors."""
262
 
        checker._report_items.append(
263
 
            'unknown entry kind %r in revision {%s}' % (self.kind, rev_id))
 
285
        raise BzrCheckError('unknown entry kind %r in revision {%s}' %
 
286
                            (self.kind, rev_id))
264
287
 
265
288
    def copy(self):
266
289
        """Clone this inventory entry."""
373
396
        pass
374
397
 
375
398
 
 
399
class RootEntry(InventoryEntry):
 
400
 
 
401
    __slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
 
402
                 'text_id', 'parent_id', 'children', 'executable',
 
403
                 'revision', 'symlink_target', 'reference_revision']
 
404
 
 
405
    def _check(self, checker, rev_id, tree):
 
406
        """See InventoryEntry._check"""
 
407
 
 
408
    def __init__(self, file_id):
 
409
        self.file_id = file_id
 
410
        self.children = {}
 
411
        self.kind = 'directory'
 
412
        self.parent_id = None
 
413
        self.name = u''
 
414
        self.revision = None
 
415
        symbol_versioning.warn('RootEntry is deprecated as of bzr 0.10.'
 
416
                               '  Please use InventoryDirectory instead.',
 
417
                               DeprecationWarning, stacklevel=2)
 
418
 
 
419
    def __eq__(self, other):
 
420
        if not isinstance(other, RootEntry):
 
421
            return NotImplemented
 
422
 
 
423
        return (self.file_id == other.file_id) \
 
424
               and (self.children == other.children)
 
425
 
 
426
 
376
427
class InventoryDirectory(InventoryEntry):
377
428
    """A directory in an inventory."""
378
429
 
379
 
    __slots__ = ['children']
380
 
 
381
 
    kind = 'directory'
382
 
 
383
 
    def _check(self, checker, rev_id):
 
430
    __slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
 
431
                 'text_id', 'parent_id', 'children', 'executable',
 
432
                 'revision', 'symlink_target', 'reference_revision']
 
433
 
 
434
    def _check(self, checker, rev_id, tree):
384
435
        """See InventoryEntry._check"""
385
 
        # In non rich root repositories we do not expect a file graph for the
386
 
        # root.
387
 
        if self.name == '' and not checker.rich_roots:
388
 
            return
389
 
        # Directories are stored as an empty file, but the file should exist
390
 
        # to provide a per-fileid log. The hash of every directory content is
391
 
        # "da..." below (the sha1sum of '').
392
 
        checker.add_pending_item(rev_id,
393
 
            ('texts', self.file_id, self.revision), 'text',
394
 
             'da39a3ee5e6b4b0d3255bfef95601890afd80709')
 
436
        if self.text_sha1 is not None or self.text_size is not None or self.text_id is not None:
 
437
            raise BzrCheckError('directory {%s} has text in revision {%s}'
 
438
                                % (self.file_id, rev_id))
395
439
 
396
440
    def copy(self):
397
441
        other = InventoryDirectory(self.file_id, self.name, self.parent_id)
403
447
    def __init__(self, file_id, name, parent_id):
404
448
        super(InventoryDirectory, self).__init__(file_id, name, parent_id)
405
449
        self.children = {}
 
450
        self.kind = 'directory'
406
451
 
407
452
    def kind_character(self):
408
453
        """See InventoryEntry.kind_character."""
409
454
        return '/'
410
455
 
 
456
    def _put_in_tar(self, item, tree):
 
457
        """See InventoryEntry._put_in_tar."""
 
458
        item.type = tarfile.DIRTYPE
 
459
        fileobj = None
 
460
        item.name += '/'
 
461
        item.size = 0
 
462
        item.mode = 0755
 
463
        return fileobj
 
464
 
 
465
    def _put_on_disk(self, fullpath, tree):
 
466
        """See InventoryEntry._put_on_disk."""
 
467
        os.mkdir(fullpath)
 
468
 
411
469
 
412
470
class InventoryFile(InventoryEntry):
413
471
    """A file in an inventory."""
414
472
 
415
 
    __slots__ = ['text_sha1', 'text_size', 'text_id', 'executable']
416
 
 
417
 
    kind = 'file'
418
 
 
419
 
    def __init__(self, file_id, name, parent_id):
420
 
        super(InventoryFile, self).__init__(file_id, name, parent_id)
421
 
        self.text_sha1 = None
422
 
        self.text_size = None
423
 
        self.text_id = None
424
 
        self.executable = False
425
 
 
426
 
    def _check(self, checker, tree_revision_id):
 
473
    __slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
 
474
                 'text_id', 'parent_id', 'children', 'executable',
 
475
                 'revision', 'symlink_target', 'reference_revision']
 
476
 
 
477
    def _check(self, checker, tree_revision_id, tree):
427
478
        """See InventoryEntry._check"""
428
 
        # TODO: check size too.
429
 
        checker.add_pending_item(tree_revision_id,
430
 
            ('texts', self.file_id, self.revision), 'text',
431
 
             self.text_sha1)
432
 
        if self.text_size is None:
433
 
            checker._report_items.append(
434
 
                'fileid {%s} in {%s} has None for text_size' % (self.file_id,
435
 
                tree_revision_id))
 
479
        key = (self.file_id, self.revision)
 
480
        if key in checker.checked_texts:
 
481
            prev_sha = checker.checked_texts[key]
 
482
            if prev_sha != self.text_sha1:
 
483
                raise BzrCheckError(
 
484
                    'mismatched sha1 on {%s} in {%s} (%s != %s) %r' %
 
485
                    (self.file_id, tree_revision_id, prev_sha, self.text_sha1,
 
486
                     t))
 
487
            else:
 
488
                checker.repeated_text_cnt += 1
 
489
                return
 
490
 
 
491
        checker.checked_text_cnt += 1
 
492
        # We can't check the length, because Weave doesn't store that
 
493
        # information, and the whole point of looking at the weave's
 
494
        # sha1sum is that we don't have to extract the text.
 
495
        if (self.text_sha1 != tree._repository.texts.get_sha1s([key])[key]):
 
496
            raise BzrCheckError('text {%s} version {%s} wrong sha1' % key)
 
497
        checker.checked_texts[key] = self.text_sha1
436
498
 
437
499
    def copy(self):
438
500
        other = InventoryFile(self.file_id, self.name, self.parent_id)
470
532
        """See InventoryEntry.has_text."""
471
533
        return True
472
534
 
 
535
    def __init__(self, file_id, name, parent_id):
 
536
        super(InventoryFile, self).__init__(file_id, name, parent_id)
 
537
        self.kind = 'file'
 
538
 
473
539
    def kind_character(self):
474
540
        """See InventoryEntry.kind_character."""
475
541
        return ''
476
542
 
 
543
    def _put_in_tar(self, item, tree):
 
544
        """See InventoryEntry._put_in_tar."""
 
545
        item.type = tarfile.REGTYPE
 
546
        fileobj = tree.get_file(self.file_id)
 
547
        item.size = self.text_size
 
548
        if tree.is_executable(self.file_id):
 
549
            item.mode = 0755
 
550
        else:
 
551
            item.mode = 0644
 
552
        return fileobj
 
553
 
 
554
    def _put_on_disk(self, fullpath, tree):
 
555
        """See InventoryEntry._put_on_disk."""
 
556
        osutils.pumpfile(tree.get_file(self.file_id), file(fullpath, 'wb'))
 
557
        if tree.is_executable(self.file_id):
 
558
            os.chmod(fullpath, 0755)
 
559
 
477
560
    def _read_tree_state(self, path, work_tree):
478
561
        """See InventoryEntry._read_tree_state."""
479
562
        self.text_sha1 = work_tree.get_file_sha1(self.file_id, path=path)
511
594
class InventoryLink(InventoryEntry):
512
595
    """A file in an inventory."""
513
596
 
514
 
    __slots__ = ['symlink_target']
515
 
 
516
 
    kind = 'symlink'
517
 
 
518
 
    def __init__(self, file_id, name, parent_id):
519
 
        super(InventoryLink, self).__init__(file_id, name, parent_id)
520
 
        self.symlink_target = None
521
 
 
522
 
    def _check(self, checker, tree_revision_id):
 
597
    __slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
 
598
                 'text_id', 'parent_id', 'children', 'executable',
 
599
                 'revision', 'symlink_target', 'reference_revision']
 
600
 
 
601
    def _check(self, checker, rev_id, tree):
523
602
        """See InventoryEntry._check"""
 
603
        if self.text_sha1 is not None or self.text_size is not None or self.text_id is not None:
 
604
            raise BzrCheckError('symlink {%s} has text in revision {%s}'
 
605
                    % (self.file_id, rev_id))
524
606
        if self.symlink_target is None:
525
 
            checker._report_items.append(
526
 
                'symlink {%s} has no target in revision {%s}'
527
 
                    % (self.file_id, tree_revision_id))
528
 
        # Symlinks are stored as ''
529
 
        checker.add_pending_item(tree_revision_id,
530
 
            ('texts', self.file_id, self.revision), 'text',
531
 
             'da39a3ee5e6b4b0d3255bfef95601890afd80709')
 
607
            raise BzrCheckError('symlink {%s} has no target in revision {%s}'
 
608
                    % (self.file_id, rev_id))
532
609
 
533
610
    def copy(self):
534
611
        other = InventoryLink(self.file_id, self.name, self.parent_id)
541
618
        # FIXME: which _modified field should we use ? RBC 20051003
542
619
        text_modified = (self.symlink_target != old_entry.symlink_target)
543
620
        if text_modified:
544
 
            trace.mutter("    symlink target changed")
 
621
            mutter("    symlink target changed")
545
622
        meta_modified = False
546
623
        return text_modified, meta_modified
547
624
 
564
641
        differ = DiffSymlink(old_tree, new_tree, output_to)
565
642
        return differ.diff_symlink(old_target, new_target)
566
643
 
 
644
    def __init__(self, file_id, name, parent_id):
 
645
        super(InventoryLink, self).__init__(file_id, name, parent_id)
 
646
        self.kind = 'symlink'
 
647
 
567
648
    def kind_character(self):
568
649
        """See InventoryEntry.kind_character."""
569
650
        return ''
570
651
 
 
652
    def _put_in_tar(self, item, tree):
 
653
        """See InventoryEntry._put_in_tar."""
 
654
        item.type = tarfile.SYMTYPE
 
655
        fileobj = None
 
656
        item.size = 0
 
657
        item.mode = 0755
 
658
        item.linkname = self.symlink_target
 
659
        return fileobj
 
660
 
 
661
    def _put_on_disk(self, fullpath, tree):
 
662
        """See InventoryEntry._put_on_disk."""
 
663
        try:
 
664
            os.symlink(self.symlink_target, fullpath)
 
665
        except OSError,e:
 
666
            raise BzrError("Failed to create symlink %r -> %r, error: %s" % (fullpath, self.symlink_target, e))
 
667
 
571
668
    def _read_tree_state(self, path, work_tree):
572
669
        """See InventoryEntry._read_tree_state."""
573
670
        self.symlink_target = work_tree.get_symlink_target(self.file_id)
585
682
 
586
683
class TreeReference(InventoryEntry):
587
684
 
588
 
    __slots__ = ['reference_revision']
589
 
 
590
685
    kind = 'tree-reference'
591
686
 
592
687
    def __init__(self, file_id, name, parent_id, revision=None,
631
726
    inserted, other than through the Inventory API.
632
727
    """
633
728
 
634
 
    @deprecated_method(deprecated_in((2, 4, 0)))
635
729
    def __contains__(self, file_id):
636
730
        """True if this entry contains a file with given id.
637
731
 
638
732
        >>> inv = Inventory()
639
733
        >>> inv.add(InventoryFile('123', 'foo.c', ROOT_ID))
640
734
        InventoryFile('123', 'foo.c', parent_id='TREE_ROOT', sha1=None, len=None, revision=None)
641
 
        >>> inv.has_id('123')
 
735
        >>> '123' in inv
642
736
        True
643
 
        >>> inv.has_id('456')
 
737
        >>> '456' in inv
644
738
        False
645
739
 
646
740
        Note that this method along with __iter__ are not encouraged for use as
649
743
        """
650
744
        return self.has_id(file_id)
651
745
 
652
 
    def has_filename(self, filename):
653
 
        return bool(self.path2id(filename))
654
 
 
655
746
    def id2path(self, file_id):
656
747
        """Return as a string the path to file_id.
657
748
 
660
751
        >>> e = i.add(InventoryFile('foo-id', 'foo.c', parent_id='src-id'))
661
752
        >>> print i.id2path('foo-id')
662
753
        src/foo.c
663
 
 
664
 
        :raises NoSuchId: If file_id is not present in the inventory.
665
754
        """
666
755
        # get all names, skipping root
667
756
        return '/'.join(reversed(
721
810
                # if we finished all children, pop it off the stack
722
811
                stack.pop()
723
812
 
724
 
    def _preload_cache(self):
725
 
        """Populate any caches, we are about to access all items.
726
 
        
727
 
        The default implementation does nothing, because CommonInventory doesn't
728
 
        have a cache.
729
 
        """
730
 
        pass
731
 
    
732
813
    def iter_entries_by_dir(self, from_dir=None, specific_file_ids=None,
733
814
        yield_parents=False):
734
815
        """Iterate over the entries in a directory first order.
747
828
            specific_file_ids = set(specific_file_ids)
748
829
        # TODO? Perhaps this should return the from_dir so that the root is
749
830
        # yielded? or maybe an option?
750
 
        if from_dir is None and specific_file_ids is None:
751
 
            # They are iterating from the root, and have not specified any
752
 
            # specific entries to look at. All current callers fully consume the
753
 
            # iterator, so we can safely assume we are accessing all entries
754
 
            self._preload_cache()
755
831
        if from_dir is None:
756
832
            if self.root is None:
757
833
                return
759
835
            if (not yield_parents and specific_file_ids is not None and
760
836
                len(specific_file_ids) == 1):
761
837
                file_id = list(specific_file_ids)[0]
762
 
                if self.has_id(file_id):
 
838
                if file_id in self:
763
839
                    yield self.id2path(file_id), self[file_id]
764
840
                return
765
841
            from_dir = self.root
775
851
            parents = set()
776
852
            byid = self
777
853
            def add_ancestors(file_id):
778
 
                if not byid.has_id(file_id):
 
854
                if file_id not in byid:
779
855
                    return
780
856
                parent_id = byid[file_id].parent_id
781
857
                if parent_id is None:
825
901
                    file_id, self[file_id]))
826
902
        return delta
827
903
 
 
904
    def _get_mutable_inventory(self):
 
905
        """Returns a mutable copy of the object.
 
906
 
 
907
        Some inventories are immutable, yet working trees, for example, needs
 
908
        to mutate exisiting inventories instead of creating a new one.
 
909
        """
 
910
        raise NotImplementedError(self._get_mutable_inventory)
 
911
 
828
912
    def make_entry(self, kind, name, parent_id, file_id=None):
829
913
        """Simple thunk to bzrlib.inventory.make_entry."""
830
914
        return make_entry(kind, name, parent_id, file_id)
844
928
                if ie.kind == 'directory':
845
929
                    descend(ie, child_path)
846
930
 
847
 
        if self.root is not None:
848
 
            descend(self.root, u'')
 
931
        descend(self.root, u'')
849
932
        return accum
850
933
 
851
934
    def directories(self):
864
947
        descend(self.root, u'')
865
948
        return accum
866
949
 
867
 
    def path2id(self, relpath):
 
950
    def path2id(self, name):
868
951
        """Walk down through directories to return entry of last component.
869
952
 
870
 
        :param relpath: may be either a list of path components, or a single
871
 
            string, in which case it is automatically split.
 
953
        names may be either a list of path components, or a single
 
954
        string, in which case it is automatically split.
872
955
 
873
956
        This returns the entry of the last component in the path,
874
957
        which may be either a file or a directory.
875
958
 
876
959
        Returns None IFF the path is not found.
877
960
        """
878
 
        if isinstance(relpath, basestring):
879
 
            names = osutils.splitpath(relpath)
880
 
        else:
881
 
            names = relpath
 
961
        if isinstance(name, basestring):
 
962
            name = osutils.splitpath(name)
 
963
 
 
964
        # mutter("lookup path %r" % name)
882
965
 
883
966
        try:
884
967
            parent = self.root
887
970
            return None
888
971
        if parent is None:
889
972
            return None
890
 
        for f in names:
 
973
        for f in name:
891
974
            try:
892
975
                children = getattr(parent, 'children', None)
893
976
                if children is None:
965
1048
 
966
1049
    >>> inv.path2id('hello.c')
967
1050
    '123-123'
968
 
    >>> inv.has_id('123-123')
 
1051
    >>> '123-123' in inv
969
1052
    True
970
1053
 
971
1054
    There are iterators over the contents:
1006
1089
        See the inventory developers documentation for the theory behind
1007
1090
        inventory deltas.
1008
1091
 
1009
 
        If delta application fails the inventory is left in an indeterminate
1010
 
        state and must not be used.
1011
 
 
1012
1092
        :param delta: A list of changes to apply. After all the changes are
1013
1093
            applied the final inventory must be internally consistent, but it
1014
1094
            is ok to supply changes which, if only half-applied would have an
1049
1129
        # facility.
1050
1130
        list(_check_delta_unique_ids(_check_delta_unique_new_paths(
1051
1131
            _check_delta_unique_old_paths(_check_delta_ids_match_entry(
1052
 
            _check_delta_ids_are_valid(
1053
 
            _check_delta_new_path_entry_both_or_None(
1054
 
            delta)))))))
 
1132
            delta)))))
1055
1133
 
1056
1134
        children = {}
1057
1135
        # Remove all affected items which were in the original inventory,
1060
1138
        # modified children remaining by the time we examine it.
1061
1139
        for old_path, file_id in sorted(((op, f) for op, np, f, e in delta
1062
1140
                                        if op is not None), reverse=True):
 
1141
            if file_id not in self:
 
1142
                # adds come later
 
1143
                continue
1063
1144
            # Preserve unaltered children of file_id for later reinsertion.
1064
1145
            file_id_children = getattr(self[file_id], 'children', {})
1065
1146
            if len(file_id_children):
1066
1147
                children[file_id] = file_id_children
1067
 
            if self.id2path(file_id) != old_path:
1068
 
                raise errors.InconsistentDelta(old_path, file_id,
1069
 
                    "Entry was at wrong other path %r." % self.id2path(file_id))
1070
1148
            # Remove file_id and the unaltered children. If file_id is not
1071
1149
            # being deleted it will be reinserted back later.
1072
1150
            self.remove_recursive_id(file_id)
1075
1153
        # longest, ensuring that items which were modified and whose parents in
1076
1154
        # the resulting inventory were also modified, are inserted after their
1077
1155
        # parents.
1078
 
        for new_path, f, new_entry in sorted((np, f, e) for op, np, f, e in
 
1156
        for new_path, new_entry in sorted((np, e) for op, np, f, e in
1079
1157
                                          delta if np is not None):
1080
1158
            if new_entry.kind == 'directory':
1081
1159
                # Pop the child which to allow detection of children whose
1088
1166
                new_entry = replacement
1089
1167
            try:
1090
1168
                self.add(new_entry)
1091
 
            except errors.DuplicateFileId:
1092
 
                raise errors.InconsistentDelta(new_path, new_entry.file_id,
1093
 
                    "New id is already present in target.")
1094
1169
            except AttributeError:
1095
1170
                raise errors.InconsistentDelta(new_path, new_entry.file_id,
1096
1171
                    "Parent is not a directory.")
1097
 
            if self.id2path(new_entry.file_id) != new_path:
1098
 
                raise errors.InconsistentDelta(new_path, new_entry.file_id,
1099
 
                    "New path is not consistent with parent path.")
1100
1172
        if len(children):
1101
1173
            # Get the parent id that was deleted
1102
1174
            parent_id, children = children.popitem()
1103
1175
            raise errors.InconsistentDelta("<deleted>", parent_id,
1104
1176
                "The file id was deleted but its children were not deleted.")
1105
1177
 
1106
 
    def create_by_apply_delta(self, inventory_delta, new_revision_id,
1107
 
                              propagate_caches=False):
1108
 
        """See CHKInventory.create_by_apply_delta()"""
1109
 
        new_inv = self.copy()
1110
 
        new_inv.apply_delta(inventory_delta)
1111
 
        new_inv.revision_id = new_revision_id
1112
 
        return new_inv
1113
 
 
1114
1178
    def _set_root(self, ie):
1115
1179
        self.root = ie
1116
1180
        self._byid = {self.root.file_id: self.root}
1128
1192
            other.add(entry.copy())
1129
1193
        return other
1130
1194
 
 
1195
    def _get_mutable_inventory(self):
 
1196
        """See CommonInventory._get_mutable_inventory."""
 
1197
        return copy.deepcopy(self)
 
1198
 
1131
1199
    def __iter__(self):
1132
1200
        """Iterate over all file-ids."""
1133
1201
        return iter(self._byid)
1173
1241
    def _add_child(self, entry):
1174
1242
        """Add an entry to the inventory, without adding it to its parent"""
1175
1243
        if entry.file_id in self._byid:
1176
 
            raise errors.BzrError(
1177
 
                "inventory already contains entry with id {%s}" %
1178
 
                entry.file_id)
 
1244
            raise BzrError("inventory already contains entry with id {%s}" %
 
1245
                           entry.file_id)
1179
1246
        self._byid[entry.file_id] = entry
1180
1247
        for child in getattr(entry, 'children', {}).itervalues():
1181
1248
            self._add_child(child)
1184
1251
    def add(self, entry):
1185
1252
        """Add entry to inventory.
1186
1253
 
1187
 
        :return: entry
 
1254
        To add  a file to a branch ready to be committed, use Branch.add,
 
1255
        which calls this.
 
1256
 
 
1257
        Returns the new entry object.
1188
1258
        """
1189
1259
        if entry.file_id in self._byid:
1190
1260
            raise errors.DuplicateFileId(entry.file_id,
1191
1261
                                         self._byid[entry.file_id])
 
1262
 
1192
1263
        if entry.parent_id is None:
1193
1264
            self.root = entry
1194
1265
        else:
1234
1305
        >>> inv = Inventory()
1235
1306
        >>> inv.add(InventoryFile('123', 'foo.c', ROOT_ID))
1236
1307
        InventoryFile('123', 'foo.c', parent_id='TREE_ROOT', sha1=None, len=None, revision=None)
1237
 
        >>> inv.has_id('123')
 
1308
        >>> '123' in inv
1238
1309
        True
1239
1310
        >>> del inv['123']
1240
 
        >>> inv.has_id('123')
 
1311
        >>> '123' in inv
1241
1312
        False
1242
1313
        """
1243
1314
        ie = self[file_id]
1282
1353
            yield ie
1283
1354
            file_id = ie.parent_id
1284
1355
 
 
1356
    def has_filename(self, filename):
 
1357
        return bool(self.path2id(filename))
 
1358
 
1285
1359
    def has_id(self, file_id):
1286
1360
        return (file_id in self._byid)
1287
1361
 
1345
1419
        """
1346
1420
        new_name = ensure_normalized_name(new_name)
1347
1421
        if not is_valid_name(new_name):
1348
 
            raise errors.BzrError("not an acceptable filename: %r" % new_name)
 
1422
            raise BzrError("not an acceptable filename: %r" % new_name)
1349
1423
 
1350
1424
        new_parent = self._byid[new_parent_id]
1351
1425
        if new_name in new_parent.children:
1352
 
            raise errors.BzrError("%r already exists in %r" %
1353
 
                (new_name, self.id2path(new_parent_id)))
 
1426
            raise BzrError("%r already exists in %r" % (new_name, self.id2path(new_parent_id)))
1354
1427
 
1355
1428
        new_parent_idpath = self.get_idpath(new_parent_id)
1356
1429
        if file_id in new_parent_idpath:
1357
 
            raise errors.BzrError(
1358
 
                "cannot move directory %r into a subdirectory of itself, %r"
 
1430
            raise BzrError("cannot move directory %r into a subdirectory of itself, %r"
1359
1431
                    % (self.id2path(file_id), self.id2path(new_parent_id)))
1360
1432
 
1361
1433
        file_ie = self._byid[file_id]
1397
1469
    def __init__(self, search_key_name):
1398
1470
        CommonInventory.__init__(self)
1399
1471
        self._fileid_to_entry_cache = {}
1400
 
        self._fully_cached = False
1401
1472
        self._path_to_fileid_cache = {}
1402
1473
        self._search_key_name = search_key_name
1403
 
        self.root_id = None
1404
1474
 
1405
1475
    def __eq__(self, other):
1406
1476
        """Compare two sets by comparing their contents."""
1457
1527
        else:
1458
1528
            raise ValueError("unknown kind %r" % entry.kind)
1459
1529
 
1460
 
    def _expand_fileids_to_parents_and_children(self, file_ids):
1461
 
        """Give a more wholistic view starting with the given file_ids.
1462
 
 
1463
 
        For any file_id which maps to a directory, we will include all children
1464
 
        of that directory. We will also include all directories which are
1465
 
        parents of the given file_ids, but we will not include their children.
1466
 
 
1467
 
        eg:
1468
 
          /     # TREE_ROOT
1469
 
          foo/  # foo-id
1470
 
            baz # baz-id
1471
 
            frob/ # frob-id
1472
 
              fringle # fringle-id
1473
 
          bar/  # bar-id
1474
 
            bing # bing-id
1475
 
 
1476
 
        if given [foo-id] we will include
1477
 
            TREE_ROOT as interesting parents
1478
 
        and 
1479
 
            foo-id, baz-id, frob-id, fringle-id
1480
 
        As interesting ids.
1481
 
        """
1482
 
        interesting = set()
1483
 
        # TODO: Pre-pass over the list of fileids to see if anything is already
1484
 
        #       deserialized in self._fileid_to_entry_cache
1485
 
 
1486
 
        directories_to_expand = set()
1487
 
        children_of_parent_id = {}
1488
 
        # It is okay if some of the fileids are missing
1489
 
        for entry in self._getitems(file_ids):
1490
 
            if entry.kind == 'directory':
1491
 
                directories_to_expand.add(entry.file_id)
1492
 
            interesting.add(entry.parent_id)
1493
 
            children_of_parent_id.setdefault(entry.parent_id, set()
1494
 
                                             ).add(entry.file_id)
1495
 
 
1496
 
        # Now, interesting has all of the direct parents, but not the
1497
 
        # parents of those parents. It also may have some duplicates with
1498
 
        # specific_fileids
1499
 
        remaining_parents = interesting.difference(file_ids)
1500
 
        # When we hit the TREE_ROOT, we'll get an interesting parent of None,
1501
 
        # but we don't actually want to recurse into that
1502
 
        interesting.add(None) # this will auto-filter it in the loop
1503
 
        remaining_parents.discard(None) 
1504
 
        while remaining_parents:
1505
 
            next_parents = set()
1506
 
            for entry in self._getitems(remaining_parents):
1507
 
                next_parents.add(entry.parent_id)
1508
 
                children_of_parent_id.setdefault(entry.parent_id, set()
1509
 
                                                 ).add(entry.file_id)
1510
 
            # Remove any search tips we've already processed
1511
 
            remaining_parents = next_parents.difference(interesting)
1512
 
            interesting.update(remaining_parents)
1513
 
            # We should probably also .difference(directories_to_expand)
1514
 
        interesting.update(file_ids)
1515
 
        interesting.discard(None)
1516
 
        while directories_to_expand:
1517
 
            # Expand directories by looking in the
1518
 
            # parent_id_basename_to_file_id map
1519
 
            keys = [StaticTuple(f,).intern() for f in directories_to_expand]
1520
 
            directories_to_expand = set()
1521
 
            items = self.parent_id_basename_to_file_id.iteritems(keys)
1522
 
            next_file_ids = set([item[1] for item in items])
1523
 
            next_file_ids = next_file_ids.difference(interesting)
1524
 
            interesting.update(next_file_ids)
1525
 
            for entry in self._getitems(next_file_ids):
1526
 
                if entry.kind == 'directory':
1527
 
                    directories_to_expand.add(entry.file_id)
1528
 
                children_of_parent_id.setdefault(entry.parent_id, set()
1529
 
                                                 ).add(entry.file_id)
1530
 
        return interesting, children_of_parent_id
1531
 
 
1532
 
    def filter(self, specific_fileids):
1533
 
        """Get an inventory view filtered against a set of file-ids.
1534
 
 
1535
 
        Children of directories and parents are included.
1536
 
 
1537
 
        The result may or may not reference the underlying inventory
1538
 
        so it should be treated as immutable.
1539
 
        """
1540
 
        (interesting,
1541
 
         parent_to_children) = self._expand_fileids_to_parents_and_children(
1542
 
                                specific_fileids)
1543
 
        # There is some overlap here, but we assume that all interesting items
1544
 
        # are in the _fileid_to_entry_cache because we had to read them to
1545
 
        # determine if they were a dir we wanted to recurse, or just a file
1546
 
        # This should give us all the entries we'll want to add, so start
1547
 
        # adding
1548
 
        other = Inventory(self.root_id)
1549
 
        other.root.revision = self.root.revision
1550
 
        other.revision_id = self.revision_id
1551
 
        if not interesting or not parent_to_children:
1552
 
            # empty filter, or filtering entrys that don't exist
1553
 
            # (if even 1 existed, then we would have populated
1554
 
            # parent_to_children with at least the tree root.)
1555
 
            return other
1556
 
        cache = self._fileid_to_entry_cache
1557
 
        remaining_children = collections.deque(parent_to_children[self.root_id])
1558
 
        while remaining_children:
1559
 
            file_id = remaining_children.popleft()
1560
 
            ie = cache[file_id]
1561
 
            if ie.kind == 'directory':
1562
 
                ie = ie.copy() # We create a copy to depopulate the .children attribute
1563
 
            # TODO: depending on the uses of 'other' we should probably alwyas
1564
 
            #       '.copy()' to prevent someone from mutating other and
1565
 
            #       invaliding our internal cache
1566
 
            other.add(ie)
1567
 
            if file_id in parent_to_children:
1568
 
                remaining_children.extend(parent_to_children[file_id])
1569
 
        return other
1570
 
 
1571
1530
    @staticmethod
1572
1531
    def _bytes_to_utf8name_key(bytes):
1573
1532
        """Get the file_id, revision_id key out of bytes."""
1575
1534
        # to filter out empty names because of non rich-root...
1576
1535
        sections = bytes.split('\n')
1577
1536
        kind, file_id = sections[0].split(': ')
1578
 
        return (sections[2], intern(file_id), intern(sections[3]))
 
1537
        return (sections[2], file_id, sections[3])
1579
1538
 
1580
1539
    def _bytes_to_entry(self, bytes):
1581
1540
        """Deserialise a serialised entry."""
1603
1562
            result.reference_revision = sections[4]
1604
1563
        else:
1605
1564
            raise ValueError("Not a serialised entry %r" % bytes)
1606
 
        result.file_id = intern(result.file_id)
1607
 
        result.revision = intern(sections[3])
 
1565
        result.revision = sections[3]
1608
1566
        if result.parent_id == '':
1609
1567
            result.parent_id = None
1610
1568
        self._fileid_to_entry_cache[result.file_id] = result
1611
1569
        return result
1612
1570
 
 
1571
    def _get_mutable_inventory(self):
 
1572
        """See CommonInventory._get_mutable_inventory."""
 
1573
        entries = self.iter_entries()
 
1574
        inv = Inventory(None, self.revision_id)
 
1575
        for path, inv_entry in entries:
 
1576
            inv.add(inv_entry.copy())
 
1577
        return inv
 
1578
 
1613
1579
    def create_by_apply_delta(self, inventory_delta, new_revision_id,
1614
1580
        propagate_caches=False):
1615
1581
        """Create a new CHKInventory by applying inventory_delta to this one.
1624
1590
          copied to and updated for the result.
1625
1591
        :return: The new CHKInventory.
1626
1592
        """
1627
 
        split = osutils.split
1628
1593
        result = CHKInventory(self._search_key_name)
1629
1594
        if propagate_caches:
1630
1595
            # Just propagate the path-to-fileid cache for now
1639
1604
            search_key_func=search_key_func)
1640
1605
        result.id_to_entry._ensure_root()
1641
1606
        result.id_to_entry._root_node.set_maximum_size(maximum_size)
1642
 
        # Change to apply to the parent_id_basename delta. The dict maps
1643
 
        # (parent_id, basename) -> (old_key, new_value). We use a dict because
1644
 
        # when a path has its id replaced (e.g. the root is changed, or someone
1645
 
        # does bzr mv a b, bzr mv c a, we should output a single change to this
1646
 
        # map rather than two.
1647
 
        parent_id_basename_delta = {}
 
1607
        parent_id_basename_delta = []
1648
1608
        if self.parent_id_basename_to_file_id is not None:
1649
1609
            result.parent_id_basename_to_file_id = chk_map.CHKMap(
1650
1610
                self.parent_id_basename_to_file_id._store,
1670
1630
        inventory_delta = _check_delta_unique_new_paths(inventory_delta)
1671
1631
        # Check for entries that don't match the fileid
1672
1632
        inventory_delta = _check_delta_ids_match_entry(inventory_delta)
1673
 
        # Check for nonsense fileids
1674
 
        inventory_delta = _check_delta_ids_are_valid(inventory_delta)
1675
 
        # Check for new_path <-> entry consistency
1676
 
        inventory_delta = _check_delta_new_path_entry_both_or_None(
1677
 
            inventory_delta)
1678
 
        # All changed entries need to have their parents be directories and be
1679
 
        # at the right path. This set contains (path, id) tuples.
 
1633
        # All changed entries need to have their parents be directories.
1680
1634
        parents = set()
1681
 
        # When we delete an item, all the children of it must be either deleted
1682
 
        # or altered in their own right. As we batch process the change via
1683
 
        # CHKMap.apply_delta, we build a set of things to use to validate the
1684
 
        # delta.
1685
 
        deletes = set()
1686
 
        altered = set()
1687
1635
        for old_path, new_path, file_id, entry in inventory_delta:
1688
1636
            # file id changes
1689
1637
            if new_path == '':
1698
1646
                        del result._path_to_fileid_cache[old_path]
1699
1647
                    except KeyError:
1700
1648
                        pass
1701
 
                deletes.add(file_id)
1702
1649
            else:
1703
 
                new_key = StaticTuple(file_id,)
 
1650
                new_key = (file_id,)
1704
1651
                new_value = result._entry_to_bytes(entry)
1705
1652
                # Update caches. It's worth doing this whether
1706
1653
                # we're propagating the old caches or not.
1707
1654
                result._path_to_fileid_cache[new_path] = file_id
1708
 
                parents.add((split(new_path)[0], entry.parent_id))
 
1655
                parents.add(entry.parent_id)
1709
1656
            if old_path is None:
1710
1657
                old_key = None
1711
1658
            else:
1712
 
                old_key = StaticTuple(file_id,)
1713
 
                if self.id2path(file_id) != old_path:
1714
 
                    raise errors.InconsistentDelta(old_path, file_id,
1715
 
                        "Entry was at wrong other path %r." %
1716
 
                        self.id2path(file_id))
1717
 
                altered.add(file_id)
1718
 
            id_to_entry_delta.append(StaticTuple(old_key, new_key, new_value))
 
1659
                old_key = (file_id,)
 
1660
            id_to_entry_delta.append((old_key, new_key, new_value))
1719
1661
            if result.parent_id_basename_to_file_id is not None:
1720
1662
                # parent_id, basename changes
1721
1663
                if old_path is None:
1729
1671
                else:
1730
1672
                    new_key = self._parent_id_basename_key(entry)
1731
1673
                    new_value = file_id
1732
 
                # If the two keys are the same, the value will be unchanged
1733
 
                # as its always the file id for this entry.
1734
1674
                if old_key != new_key:
1735
 
                    # Transform a change into explicit delete/add preserving
1736
 
                    # a possible match on the key from a different file id.
1737
 
                    if old_key is not None:
1738
 
                        parent_id_basename_delta.setdefault(
1739
 
                            old_key, [None, None])[0] = old_key
1740
 
                    if new_key is not None:
1741
 
                        parent_id_basename_delta.setdefault(
1742
 
                            new_key, [None, None])[1] = new_value
1743
 
        # validate that deletes are complete.
1744
 
        for file_id in deletes:
1745
 
            entry = self[file_id]
1746
 
            if entry.kind != 'directory':
1747
 
                continue
1748
 
            # This loop could potentially be better by using the id_basename
1749
 
            # map to just get the child file ids.
1750
 
            for child in entry.children.values():
1751
 
                if child.file_id not in altered:
1752
 
                    raise errors.InconsistentDelta(self.id2path(child.file_id),
1753
 
                        child.file_id, "Child not deleted or reparented when "
1754
 
                        "parent deleted.")
 
1675
                    # If the two keys are the same, the value will be unchanged
 
1676
                    # as its always the file id.
 
1677
                    parent_id_basename_delta.append((old_key, new_key, new_value))
1755
1678
        result.id_to_entry.apply_delta(id_to_entry_delta)
1756
1679
        if parent_id_basename_delta:
1757
 
            # Transform the parent_id_basename delta data into a linear delta
1758
 
            # with only one record for a given key. Optimally this would allow
1759
 
            # re-keying, but its simpler to just output that as a delete+add
1760
 
            # to spend less time calculating the delta.
1761
 
            delta_list = []
1762
 
            for key, (old_key, value) in parent_id_basename_delta.iteritems():
1763
 
                if value is not None:
1764
 
                    delta_list.append((old_key, key, value))
1765
 
                else:
1766
 
                    delta_list.append((old_key, None, None))
1767
 
            result.parent_id_basename_to_file_id.apply_delta(delta_list)
1768
 
        parents.discard(('', None))
1769
 
        for parent_path, parent in parents:
 
1680
            result.parent_id_basename_to_file_id.apply_delta(parent_id_basename_delta)
 
1681
        parents.discard(None)
 
1682
        for parent in parents:
1770
1683
            try:
1771
1684
                if result[parent].kind != 'directory':
1772
1685
                    raise errors.InconsistentDelta(result.id2path(parent), parent,
1774
1687
            except errors.NoSuchId:
1775
1688
                raise errors.InconsistentDelta("<unknown>", parent,
1776
1689
                    "Parent is not present in resulting inventory.")
1777
 
            if result.path2id(parent_path) != parent:
1778
 
                raise errors.InconsistentDelta(parent_path, parent,
1779
 
                    "Parent has wrong path %r." % result.path2id(parent_path))
1780
1690
        return result
1781
1691
 
1782
1692
    @classmethod
1808
1718
                raise errors.BzrError('Duplicate key in inventory: %r\n%r'
1809
1719
                                      % (key, bytes))
1810
1720
            info[key] = value
1811
 
        revision_id = intern(info['revision_id'])
1812
 
        root_id = intern(info['root_id'])
1813
 
        search_key_name = intern(info.get('search_key_name', 'plain'))
1814
 
        parent_id_basename_to_file_id = intern(info.get(
1815
 
            'parent_id_basename_to_file_id', None))
1816
 
        if not parent_id_basename_to_file_id.startswith('sha1:'):
1817
 
            raise ValueError('parent_id_basename_to_file_id should be a sha1'
1818
 
                             ' key not %r' % (parent_id_basename_to_file_id,))
 
1721
        revision_id = info['revision_id']
 
1722
        root_id = info['root_id']
 
1723
        search_key_name = info.get('search_key_name', 'plain')
 
1724
        parent_id_basename_to_file_id = info.get(
 
1725
            'parent_id_basename_to_file_id', None)
1819
1726
        id_to_entry = info['id_to_entry']
1820
 
        if not id_to_entry.startswith('sha1:'):
1821
 
            raise ValueError('id_to_entry should be a sha1'
1822
 
                             ' key not %r' % (id_to_entry,))
1823
1727
 
1824
1728
        result = CHKInventory(search_key_name)
1825
1729
        result.revision_id = revision_id
1828
1732
                            result._search_key_name)
1829
1733
        if parent_id_basename_to_file_id is not None:
1830
1734
            result.parent_id_basename_to_file_id = chk_map.CHKMap(
1831
 
                chk_store, StaticTuple(parent_id_basename_to_file_id,),
 
1735
                chk_store, (parent_id_basename_to_file_id,),
1832
1736
                search_key_func=search_key_func)
1833
1737
        else:
1834
1738
            result.parent_id_basename_to_file_id = None
1835
1739
 
1836
 
        result.id_to_entry = chk_map.CHKMap(chk_store,
1837
 
                                            StaticTuple(id_to_entry,),
 
1740
        result.id_to_entry = chk_map.CHKMap(chk_store, (id_to_entry,),
1838
1741
                                            search_key_func=search_key_func)
1839
1742
        if (result.revision_id,) != expected_revision_id:
1840
1743
            raise ValueError("Mismatched revision id and expected: %r, %r" %
1862
1765
        id_to_entry_dict = {}
1863
1766
        parent_id_basename_dict = {}
1864
1767
        for path, entry in inventory.iter_entries():
1865
 
            key = StaticTuple(entry.file_id,).intern()
1866
 
            id_to_entry_dict[key] = entry_to_bytes(entry)
 
1768
            id_to_entry_dict[(entry.file_id,)] = entry_to_bytes(entry)
1867
1769
            p_id_key = parent_id_basename_key(entry)
1868
1770
            parent_id_basename_dict[p_id_key] = entry.file_id
1869
1771
 
1892
1794
            parent_id = entry.parent_id
1893
1795
        else:
1894
1796
            parent_id = ''
1895
 
        return StaticTuple(parent_id, entry.name.encode('utf8')).intern()
 
1797
        return parent_id, entry.name.encode('utf8')
1896
1798
 
1897
1799
    def __getitem__(self, file_id):
1898
1800
        """map a single file_id -> InventoryEntry."""
1903
1805
            return result
1904
1806
        try:
1905
1807
            return self._bytes_to_entry(
1906
 
                self.id_to_entry.iteritems([StaticTuple(file_id,)]).next()[1])
 
1808
                self.id_to_entry.iteritems([(file_id,)]).next()[1])
1907
1809
        except StopIteration:
1908
1810
            # really we're passing an inventory, not a tree...
1909
1811
            raise errors.NoSuchId(self, file_id)
1910
1812
 
1911
 
    def _getitems(self, file_ids):
1912
 
        """Similar to __getitem__, but lets you query for multiple.
1913
 
        
1914
 
        The returned order is undefined. And currently if an item doesn't
1915
 
        exist, it isn't included in the output.
1916
 
        """
1917
 
        result = []
1918
 
        remaining = []
1919
 
        for file_id in file_ids:
1920
 
            entry = self._fileid_to_entry_cache.get(file_id, None)
1921
 
            if entry is None:
1922
 
                remaining.append(file_id)
1923
 
            else:
1924
 
                result.append(entry)
1925
 
        file_keys = [StaticTuple(f,).intern() for f in remaining]
1926
 
        for file_key, value in self.id_to_entry.iteritems(file_keys):
1927
 
            entry = self._bytes_to_entry(value)
1928
 
            result.append(entry)
1929
 
            self._fileid_to_entry_cache[entry.file_id] = entry
1930
 
        return result
1931
 
 
1932
1813
    def has_id(self, file_id):
1933
1814
        # Perhaps have an explicit 'contains' method on CHKMap ?
1934
1815
        if self._fileid_to_entry_cache.get(file_id, None) is not None:
1935
1816
            return True
1936
 
        return len(list(
1937
 
            self.id_to_entry.iteritems([StaticTuple(file_id,)]))) == 1
 
1817
        return len(list(self.id_to_entry.iteritems([(file_id,)]))) == 1
1938
1818
 
1939
1819
    def is_root(self, file_id):
1940
1820
        return file_id == self.root_id
1956
1836
 
1957
1837
    def iter_just_entries(self):
1958
1838
        """Iterate over all entries.
1959
 
 
 
1839
        
1960
1840
        Unlike iter_entries(), just the entries are returned (not (path, ie))
1961
1841
        and the order of entries is undefined.
1962
1842
 
1970
1850
                self._fileid_to_entry_cache[file_id] = ie
1971
1851
            yield ie
1972
1852
 
1973
 
    def _preload_cache(self):
1974
 
        """Make sure all file-ids are in _fileid_to_entry_cache"""
1975
 
        if self._fully_cached:
1976
 
            return # No need to do it again
1977
 
        # The optimal sort order is to use iteritems() directly
1978
 
        cache = self._fileid_to_entry_cache
1979
 
        for key, entry in self.id_to_entry.iteritems():
1980
 
            file_id = key[0]
1981
 
            if file_id not in cache:
1982
 
                ie = self._bytes_to_entry(entry)
1983
 
                cache[file_id] = ie
1984
 
            else:
1985
 
                ie = cache[file_id]
1986
 
        last_parent_id = last_parent_ie = None
1987
 
        pid_items = self.parent_id_basename_to_file_id.iteritems()
1988
 
        for key, child_file_id in pid_items:
1989
 
            if key == ('', ''): # This is the root
1990
 
                if child_file_id != self.root_id:
1991
 
                    raise ValueError('Data inconsistency detected.'
1992
 
                        ' We expected data with key ("","") to match'
1993
 
                        ' the root id, but %s != %s'
1994
 
                        % (child_file_id, self.root_id))
1995
 
                continue
1996
 
            parent_id, basename = key
1997
 
            ie = cache[child_file_id]
1998
 
            if parent_id == last_parent_id:
1999
 
                parent_ie = last_parent_ie
2000
 
            else:
2001
 
                parent_ie = cache[parent_id]
2002
 
            if parent_ie.kind != 'directory':
2003
 
                raise ValueError('Data inconsistency detected.'
2004
 
                    ' An entry in the parent_id_basename_to_file_id map'
2005
 
                    ' has parent_id {%s} but the kind of that object'
2006
 
                    ' is %r not "directory"' % (parent_id, parent_ie.kind))
2007
 
            if parent_ie._children is None:
2008
 
                parent_ie._children = {}
2009
 
            basename = basename.decode('utf-8')
2010
 
            if basename in parent_ie._children:
2011
 
                existing_ie = parent_ie._children[basename]
2012
 
                if existing_ie != ie:
2013
 
                    raise ValueError('Data inconsistency detected.'
2014
 
                        ' Two entries with basename %r were found'
2015
 
                        ' in the parent entry {%s}'
2016
 
                        % (basename, parent_id))
2017
 
            if basename != ie.name:
2018
 
                raise ValueError('Data inconsistency detected.'
2019
 
                    ' In the parent_id_basename_to_file_id map, file_id'
2020
 
                    ' {%s} is listed as having basename %r, but in the'
2021
 
                    ' id_to_entry map it is %r'
2022
 
                    % (child_file_id, basename, ie.name))
2023
 
            parent_ie._children[basename] = ie
2024
 
        self._fully_cached = True
2025
 
 
2026
1853
    def iter_changes(self, basis):
2027
1854
        """Generate a Tree.iter_changes change list between this and basis.
2028
1855
 
2122
1949
            delta.append((old_path, new_path, file_id, entry))
2123
1950
        return delta
2124
1951
 
2125
 
    def path2id(self, relpath):
 
1952
    def path2id(self, name):
2126
1953
        """See CommonInventory.path2id()."""
2127
 
        # TODO: perhaps support negative hits?
2128
 
        result = self._path_to_fileid_cache.get(relpath, None)
2129
 
        if result is not None:
2130
 
            return result
2131
 
        if isinstance(relpath, basestring):
2132
 
            names = osutils.splitpath(relpath)
2133
 
        else:
2134
 
            names = relpath
2135
 
        current_id = self.root_id
2136
 
        if current_id is None:
2137
 
            return None
2138
 
        parent_id_index = self.parent_id_basename_to_file_id
2139
 
        cur_path = None
2140
 
        for basename in names:
2141
 
            if cur_path is None:
2142
 
                cur_path = basename
2143
 
            else:
2144
 
                cur_path = cur_path + '/' + basename
2145
 
            basename_utf8 = basename.encode('utf8')
2146
 
            file_id = self._path_to_fileid_cache.get(cur_path, None)
2147
 
            if file_id is None:
2148
 
                key_filter = [StaticTuple(current_id, basename_utf8)]
2149
 
                items = parent_id_index.iteritems(key_filter)
2150
 
                for (parent_id, name_utf8), file_id in items:
2151
 
                    if parent_id != current_id or name_utf8 != basename_utf8:
2152
 
                        raise errors.BzrError("corrupt inventory lookup! "
2153
 
                            "%r %r %r %r" % (parent_id, current_id, name_utf8,
2154
 
                            basename_utf8))
2155
 
                if file_id is None:
2156
 
                    return None
2157
 
                else:
2158
 
                    self._path_to_fileid_cache[cur_path] = file_id
2159
 
            current_id = file_id
2160
 
        return current_id
 
1954
        result = self._path_to_fileid_cache.get(name, None)
 
1955
        if result is None:
 
1956
            result = CommonInventory.path2id(self, name)
 
1957
            self._path_to_fileid_cache[name] = result
 
1958
        return result
2161
1959
 
2162
1960
    def to_lines(self):
2163
1961
        """Serialise the inventory to lines."""
2167
1965
            lines.append('search_key_name: %s\n' % (self._search_key_name,))
2168
1966
            lines.append("root_id: %s\n" % self.root_id)
2169
1967
            lines.append('parent_id_basename_to_file_id: %s\n' %
2170
 
                (self.parent_id_basename_to_file_id.key()[0],))
 
1968
                self.parent_id_basename_to_file_id.key())
2171
1969
            lines.append("revision_id: %s\n" % self.revision_id)
2172
 
            lines.append("id_to_entry: %s\n" % (self.id_to_entry.key()[0],))
 
1970
            lines.append("id_to_entry: %s\n" % self.id_to_entry.key())
2173
1971
        else:
2174
1972
            lines.append("revision_id: %s\n" % self.revision_id)
2175
1973
            lines.append("root_id: %s\n" % self.root_id)
2176
1974
            if self.parent_id_basename_to_file_id is not None:
2177
1975
                lines.append('parent_id_basename_to_file_id: %s\n' %
2178
 
                    (self.parent_id_basename_to_file_id.key()[0],))
2179
 
            lines.append("id_to_entry: %s\n" % (self.id_to_entry.key()[0],))
 
1976
                    self.parent_id_basename_to_file_id.key())
 
1977
            lines.append("id_to_entry: %s\n" % self.id_to_entry.key())
2180
1978
        return lines
2181
1979
 
2182
1980
    @property
2188
1986
class CHKInventoryDirectory(InventoryDirectory):
2189
1987
    """A directory in an inventory."""
2190
1988
 
2191
 
    __slots__ = ['_children', '_chk_inventory']
 
1989
    __slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
 
1990
                 'text_id', 'parent_id', '_children', 'executable',
 
1991
                 'revision', 'symlink_target', 'reference_revision',
 
1992
                 '_chk_inventory']
2192
1993
 
2193
1994
    def __init__(self, file_id, name, parent_id, chk_inventory):
2194
1995
        # Don't call InventoryDirectory.__init__ - it isn't right for this
2195
1996
        # class.
2196
1997
        InventoryEntry.__init__(self, file_id, name, parent_id)
2197
1998
        self._children = None
 
1999
        self.kind = 'directory'
2198
2000
        self._chk_inventory = chk_inventory
2199
2001
 
2200
2002
    @property
2219
2021
        parent_id_index = self._chk_inventory.parent_id_basename_to_file_id
2220
2022
        child_keys = set()
2221
2023
        for (parent_id, name_utf8), file_id in parent_id_index.iteritems(
2222
 
            key_filter=[StaticTuple(self.file_id,)]):
2223
 
            child_keys.add(StaticTuple(file_id,))
 
2024
            key_filter=[(self.file_id,)]):
 
2025
            child_keys.add((file_id,))
2224
2026
        cached = set()
2225
2027
        for file_id_key in child_keys:
2226
2028
            entry = self._chk_inventory._fileid_to_entry_cache.get(
2259
2061
    try:
2260
2062
        factory = entry_factory[kind]
2261
2063
    except KeyError:
2262
 
        raise errors.BadFileKindError(name, kind)
 
2064
        raise BzrError("unknown kind %r" % kind)
2263
2065
    return factory(file_id, name, parent_id)
2264
2066
 
2265
2067
 
2285
2087
    return name
2286
2088
 
2287
2089
 
2288
 
_NAME_RE = lazy_regex.lazy_compile(r'^[^/\\]+$')
 
2090
_NAME_RE = None
2289
2091
 
2290
2092
def is_valid_name(name):
 
2093
    global _NAME_RE
 
2094
    if _NAME_RE is None:
 
2095
        _NAME_RE = re.compile(r'^[^/\\]+$')
 
2096
 
2291
2097
    return bool(_NAME_RE.match(name))
2292
2098
 
2293
2099
 
2338
2144
        yield item
2339
2145
 
2340
2146
 
2341
 
def _check_delta_ids_are_valid(delta):
2342
 
    """Decorate a delta and check that the ids in it are valid.
2343
 
 
2344
 
    :return: A generator over delta.
2345
 
    """
2346
 
    for item in delta:
2347
 
        entry = item[3]
2348
 
        if item[2] is None:
2349
 
            raise errors.InconsistentDelta(item[0] or item[1], item[2],
2350
 
                "entry with file_id None %r" % entry)
2351
 
        if type(item[2]) != str:
2352
 
            raise errors.InconsistentDelta(item[0] or item[1], item[2],
2353
 
                "entry with non bytes file_id %r" % entry)
2354
 
        yield item
2355
 
 
2356
 
 
2357
2147
def _check_delta_ids_match_entry(delta):
2358
2148
    """Decorate a delta and check that the ids in it match the entry.file_id.
2359
2149
 
2366
2156
                raise errors.InconsistentDelta(item[0] or item[1], item[2],
2367
2157
                    "mismatched id with %r" % entry)
2368
2158
        yield item
2369
 
 
2370
 
 
2371
 
def _check_delta_new_path_entry_both_or_None(delta):
2372
 
    """Decorate a delta and check that the new_path and entry are paired.
2373
 
 
2374
 
    :return: A generator over delta.
2375
 
    """
2376
 
    for item in delta:
2377
 
        new_path = item[1]
2378
 
        entry = item[3]
2379
 
        if new_path is None and entry is not None:
2380
 
            raise errors.InconsistentDelta(item[0], item[1],
2381
 
                "Entry with no new_path")
2382
 
        if new_path is not None and entry is None:
2383
 
            raise errors.InconsistentDelta(new_path, item[1],
2384
 
                "new_path with no entry")
2385
 
        yield item
2386
 
 
2387
 
 
2388
 
def mutable_inventory_from_tree(tree):
2389
 
    """Create a new inventory that has the same contents as a specified tree.
2390
 
 
2391
 
    :param tree: Revision tree to create inventory from
2392
 
    """
2393
 
    entries = tree.iter_entries_by_dir()
2394
 
    inv = Inventory(None, tree.get_revision_id())
2395
 
    for path, inv_entry in entries:
2396
 
        inv.add(inv_entry.copy())
2397
 
    return inv