~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/inventory.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-08-13 14:20:03 UTC
  • mfrom: (4599.2.4 windows-installer)
  • Revision ID: pqm@pqm.ubuntu.com-20090813142003-3x748ymw3avzmme7
(jam) Updates to the windows installers.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 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
35
35
import re
36
36
import tarfile
37
37
 
 
38
import bzrlib
38
39
from bzrlib import (
39
40
    chk_map,
40
41
    errors,
41
42
    generate_ids,
42
43
    osutils,
 
44
    symbol_versioning,
43
45
    )
44
46
""")
45
47
 
47
49
    BzrCheckError,
48
50
    BzrError,
49
51
    )
 
52
from bzrlib.symbol_versioning import deprecated_in, deprecated_method
50
53
from bzrlib.trace import mutter
51
 
from bzrlib.static_tuple import StaticTuple
52
54
 
53
55
 
54
56
class InventoryEntry(object):
128
130
    RENAMED = 'renamed'
129
131
    MODIFIED_AND_RENAMED = 'modified and renamed'
130
132
 
131
 
    __slots__ = ['file_id', 'revision', 'parent_id', 'name']
132
 
 
133
 
    # Attributes that all InventoryEntry instances are expected to have, but
134
 
    # that don't vary for all kinds of entry.  (e.g. symlink_target is only
135
 
    # relevant to InventoryLink, so there's no reason to make every
136
 
    # InventoryFile instance allocate space to hold a value for it.)
137
 
    # Attributes that only vary for files: executable, text_sha1, text_size,
138
 
    # text_id
139
 
    executable = False
140
 
    text_sha1 = None
141
 
    text_size = None
142
 
    text_id = None
143
 
    # Attributes that only vary for symlinks: symlink_target
144
 
    symlink_target = None
145
 
    # Attributes that only vary for tree-references: reference_revision
146
 
    reference_revision = None
147
 
 
 
133
    __slots__ = []
148
134
 
149
135
    def detect_changes(self, old_entry):
150
136
        """Return a (text_modified, meta_modified) from this to old_entry.
189
175
                    candidates[ie.revision] = ie
190
176
        return candidates
191
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
 
192
188
    def has_text(self):
193
189
        """Return true if the object this entry represents has textual data.
194
190
 
200
196
        """
201
197
        return False
202
198
 
203
 
    def __init__(self, file_id, name, parent_id):
 
199
    def __init__(self, file_id, name, parent_id, text_id=None):
204
200
        """Create an InventoryEntry
205
201
 
206
202
        The filename must be a single component, relative to the
217
213
        """
218
214
        if '/' in name or '\\' in name:
219
215
            raise errors.InvalidEntryName(name=name)
 
216
        self.executable = False
 
217
        self.revision = None
 
218
        self.text_sha1 = None
 
219
        self.text_size = None
220
220
        self.file_id = file_id
221
 
        self.revision = None
222
221
        self.name = name
 
222
        self.text_id = text_id
223
223
        self.parent_id = parent_id
 
224
        self.symlink_target = None
 
225
        self.reference_revision = None
224
226
 
225
227
    def kind_character(self):
226
228
        """Return a short kind indicator useful for appending to names."""
228
230
 
229
231
    known_kinds = ('file', 'directory', 'symlink')
230
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
 
231
256
    def sorted_children(self):
232
257
        return sorted(self.children.items())
233
258
 
371
396
        pass
372
397
 
373
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):
 
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
 
374
427
class InventoryDirectory(InventoryEntry):
375
428
    """A directory in an inventory."""
376
429
 
377
 
    __slots__ = ['children']
378
 
 
379
 
    kind = 'directory'
 
430
    __slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
 
431
                 'text_id', 'parent_id', 'children', 'executable',
 
432
                 'revision', 'symlink_target', 'reference_revision']
380
433
 
381
434
    def _check(self, checker, rev_id):
382
435
        """See InventoryEntry._check"""
383
 
        # In non rich root repositories we do not expect a file graph for the
384
 
        # root.
385
 
        if self.name == '' and not checker.rich_roots:
386
 
            return
387
 
        # Directories are stored as an empty file, but the file should exist
388
 
        # to provide a per-fileid log. The hash of every directory content is
389
 
        # "da..." below (the sha1sum of '').
 
436
        if (self.text_sha1 is not None or self.text_size is not None or
 
437
            self.text_id is not None):
 
438
            checker._report_items.append('directory {%s} has text in revision {%s}'
 
439
                                % (self.file_id, rev_id))
 
440
        # Directories are stored as ''.
390
441
        checker.add_pending_item(rev_id,
391
442
            ('texts', self.file_id, self.revision), 'text',
392
443
             'da39a3ee5e6b4b0d3255bfef95601890afd80709')
401
452
    def __init__(self, file_id, name, parent_id):
402
453
        super(InventoryDirectory, self).__init__(file_id, name, parent_id)
403
454
        self.children = {}
 
455
        self.kind = 'directory'
404
456
 
405
457
    def kind_character(self):
406
458
        """See InventoryEntry.kind_character."""
407
459
        return '/'
408
460
 
 
461
    def _put_in_tar(self, item, tree):
 
462
        """See InventoryEntry._put_in_tar."""
 
463
        item.type = tarfile.DIRTYPE
 
464
        fileobj = None
 
465
        item.name += '/'
 
466
        item.size = 0
 
467
        item.mode = 0755
 
468
        return fileobj
 
469
 
 
470
    def _put_on_disk(self, fullpath, tree):
 
471
        """See InventoryEntry._put_on_disk."""
 
472
        os.mkdir(fullpath)
 
473
 
409
474
 
410
475
class InventoryFile(InventoryEntry):
411
476
    """A file in an inventory."""
412
477
 
413
 
    __slots__ = ['text_sha1', 'text_size', 'text_id', 'executable']
414
 
 
415
 
    kind = 'file'
416
 
 
417
 
    def __init__(self, file_id, name, parent_id):
418
 
        super(InventoryFile, self).__init__(file_id, name, parent_id)
419
 
        self.text_sha1 = None
420
 
        self.text_size = None
421
 
        self.text_id = None
422
 
        self.executable = False
 
478
    __slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
 
479
                 'text_id', 'parent_id', 'children', 'executable',
 
480
                 'revision', 'symlink_target', 'reference_revision']
423
481
 
424
482
    def _check(self, checker, tree_revision_id):
425
483
        """See InventoryEntry._check"""
468
526
        """See InventoryEntry.has_text."""
469
527
        return True
470
528
 
 
529
    def __init__(self, file_id, name, parent_id):
 
530
        super(InventoryFile, self).__init__(file_id, name, parent_id)
 
531
        self.kind = 'file'
 
532
 
471
533
    def kind_character(self):
472
534
        """See InventoryEntry.kind_character."""
473
535
        return ''
474
536
 
 
537
    def _put_in_tar(self, item, tree):
 
538
        """See InventoryEntry._put_in_tar."""
 
539
        item.type = tarfile.REGTYPE
 
540
        fileobj = tree.get_file(self.file_id)
 
541
        item.size = self.text_size
 
542
        if tree.is_executable(self.file_id):
 
543
            item.mode = 0755
 
544
        else:
 
545
            item.mode = 0644
 
546
        return fileobj
 
547
 
 
548
    def _put_on_disk(self, fullpath, tree):
 
549
        """See InventoryEntry._put_on_disk."""
 
550
        osutils.pumpfile(tree.get_file(self.file_id), file(fullpath, 'wb'))
 
551
        if tree.is_executable(self.file_id):
 
552
            os.chmod(fullpath, 0755)
 
553
 
475
554
    def _read_tree_state(self, path, work_tree):
476
555
        """See InventoryEntry._read_tree_state."""
477
556
        self.text_sha1 = work_tree.get_file_sha1(self.file_id, path=path)
509
588
class InventoryLink(InventoryEntry):
510
589
    """A file in an inventory."""
511
590
 
512
 
    __slots__ = ['symlink_target']
513
 
 
514
 
    kind = 'symlink'
515
 
 
516
 
    def __init__(self, file_id, name, parent_id):
517
 
        super(InventoryLink, self).__init__(file_id, name, parent_id)
518
 
        self.symlink_target = None
 
591
    __slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
 
592
                 'text_id', 'parent_id', 'children', 'executable',
 
593
                 'revision', 'symlink_target', 'reference_revision']
519
594
 
520
595
    def _check(self, checker, tree_revision_id):
521
596
        """See InventoryEntry._check"""
 
597
        if self.text_sha1 is not None or self.text_size is not None or self.text_id is not None:
 
598
            checker._report_items.append(
 
599
               'symlink {%s} has text in revision {%s}'
 
600
                    % (self.file_id, tree_revision_id))
522
601
        if self.symlink_target is None:
523
602
            checker._report_items.append(
524
603
                'symlink {%s} has no target in revision {%s}'
562
641
        differ = DiffSymlink(old_tree, new_tree, output_to)
563
642
        return differ.diff_symlink(old_target, new_target)
564
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
 
565
648
    def kind_character(self):
566
649
        """See InventoryEntry.kind_character."""
567
650
        return ''
568
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
 
569
668
    def _read_tree_state(self, path, work_tree):
570
669
        """See InventoryEntry._read_tree_state."""
571
670
        self.symlink_target = work_tree.get_symlink_target(self.file_id)
583
682
 
584
683
class TreeReference(InventoryEntry):
585
684
 
586
 
    __slots__ = ['reference_revision']
587
 
 
588
685
    kind = 'tree-reference'
589
686
 
590
687
    def __init__(self, file_id, name, parent_id, revision=None,
657
754
        >>> e = i.add(InventoryFile('foo-id', 'foo.c', parent_id='src-id'))
658
755
        >>> print i.id2path('foo-id')
659
756
        src/foo.c
660
 
 
661
 
        :raises NoSuchId: If file_id is not present in the inventory.
662
757
        """
663
758
        # get all names, skipping root
664
759
        return '/'.join(reversed(
855
950
        descend(self.root, u'')
856
951
        return accum
857
952
 
858
 
    def path2id(self, relpath):
 
953
    def path2id(self, name):
859
954
        """Walk down through directories to return entry of last component.
860
955
 
861
 
        :param relpath: may be either a list of path components, or a single
862
 
            string, in which case it is automatically split.
 
956
        names may be either a list of path components, or a single
 
957
        string, in which case it is automatically split.
863
958
 
864
959
        This returns the entry of the last component in the path,
865
960
        which may be either a file or a directory.
866
961
 
867
962
        Returns None IFF the path is not found.
868
963
        """
869
 
        if isinstance(relpath, basestring):
870
 
            names = osutils.splitpath(relpath)
871
 
        else:
872
 
            names = relpath
 
964
        if isinstance(name, basestring):
 
965
            name = osutils.splitpath(name)
 
966
 
 
967
        # mutter("lookup path %r" % name)
873
968
 
874
969
        try:
875
970
            parent = self.root
878
973
            return None
879
974
        if parent is None:
880
975
            return None
881
 
        for f in names:
 
976
        for f in name:
882
977
            try:
883
978
                children = getattr(parent, 'children', None)
884
979
                if children is None:
1094
1189
            raise errors.InconsistentDelta("<deleted>", parent_id,
1095
1190
                "The file id was deleted but its children were not deleted.")
1096
1191
 
1097
 
    def create_by_apply_delta(self, inventory_delta, new_revision_id,
1098
 
                              propagate_caches=False):
1099
 
        """See CHKInventory.create_by_apply_delta()"""
1100
 
        new_inv = self.copy()
1101
 
        new_inv.apply_delta(inventory_delta)
1102
 
        new_inv.revision_id = new_revision_id
1103
 
        return new_inv
1104
 
 
1105
1192
    def _set_root(self, ie):
1106
1193
        self.root = ie
1107
1194
        self._byid = {self.root.file_id: self.root}
1178
1265
    def add(self, entry):
1179
1266
        """Add entry to inventory.
1180
1267
 
 
1268
        To add  a file to a branch ready to be committed, use Branch.add,
 
1269
        which calls this.
 
1270
 
1181
1271
        :return: entry
1182
1272
        """
1183
1273
        if entry.file_id in self._byid:
1448
1538
        else:
1449
1539
            raise ValueError("unknown kind %r" % entry.kind)
1450
1540
 
1451
 
    def _expand_fileids_to_parents_and_children(self, file_ids):
1452
 
        """Give a more wholistic view starting with the given file_ids.
1453
 
 
1454
 
        For any file_id which maps to a directory, we will include all children
1455
 
        of that directory. We will also include all directories which are
1456
 
        parents of the given file_ids, but we will not include their children.
1457
 
 
1458
 
        eg:
1459
 
          /     # TREE_ROOT
1460
 
          foo/  # foo-id
1461
 
            baz # baz-id
1462
 
            frob/ # frob-id
1463
 
              fringle # fringle-id
1464
 
          bar/  # bar-id
1465
 
            bing # bing-id
1466
 
 
1467
 
        if given [foo-id] we will include
1468
 
            TREE_ROOT as interesting parents
1469
 
        and 
1470
 
            foo-id, baz-id, frob-id, fringle-id
1471
 
        As interesting ids.
1472
 
        """
1473
 
        interesting = set()
1474
 
        # TODO: Pre-pass over the list of fileids to see if anything is already
1475
 
        #       deserialized in self._fileid_to_entry_cache
1476
 
 
1477
 
        directories_to_expand = set()
1478
 
        children_of_parent_id = {}
1479
 
        # It is okay if some of the fileids are missing
1480
 
        for entry in self._getitems(file_ids):
1481
 
            if entry.kind == 'directory':
1482
 
                directories_to_expand.add(entry.file_id)
1483
 
            interesting.add(entry.parent_id)
1484
 
            children_of_parent_id.setdefault(entry.parent_id, []
1485
 
                                             ).append(entry.file_id)
1486
 
 
1487
 
        # Now, interesting has all of the direct parents, but not the
1488
 
        # parents of those parents. It also may have some duplicates with
1489
 
        # specific_fileids
1490
 
        remaining_parents = interesting.difference(file_ids)
1491
 
        # When we hit the TREE_ROOT, we'll get an interesting parent of None,
1492
 
        # but we don't actually want to recurse into that
1493
 
        interesting.add(None) # this will auto-filter it in the loop
1494
 
        remaining_parents.discard(None) 
1495
 
        while remaining_parents:
1496
 
            next_parents = set()
1497
 
            for entry in self._getitems(remaining_parents):
1498
 
                next_parents.add(entry.parent_id)
1499
 
                children_of_parent_id.setdefault(entry.parent_id, []
1500
 
                                                 ).append(entry.file_id)
1501
 
            # Remove any search tips we've already processed
1502
 
            remaining_parents = next_parents.difference(interesting)
1503
 
            interesting.update(remaining_parents)
1504
 
            # We should probably also .difference(directories_to_expand)
1505
 
        interesting.update(file_ids)
1506
 
        interesting.discard(None)
1507
 
        while directories_to_expand:
1508
 
            # Expand directories by looking in the
1509
 
            # parent_id_basename_to_file_id map
1510
 
            keys = [StaticTuple(f,).intern() for f in directories_to_expand]
1511
 
            directories_to_expand = set()
1512
 
            items = self.parent_id_basename_to_file_id.iteritems(keys)
1513
 
            next_file_ids = set([item[1] for item in items])
1514
 
            next_file_ids = next_file_ids.difference(interesting)
1515
 
            interesting.update(next_file_ids)
1516
 
            for entry in self._getitems(next_file_ids):
1517
 
                if entry.kind == 'directory':
1518
 
                    directories_to_expand.add(entry.file_id)
1519
 
                children_of_parent_id.setdefault(entry.parent_id, []
1520
 
                                                 ).append(entry.file_id)
1521
 
        return interesting, children_of_parent_id
1522
 
 
1523
 
    def filter(self, specific_fileids):
1524
 
        """Get an inventory view filtered against a set of file-ids.
1525
 
 
1526
 
        Children of directories and parents are included.
1527
 
 
1528
 
        The result may or may not reference the underlying inventory
1529
 
        so it should be treated as immutable.
1530
 
        """
1531
 
        (interesting,
1532
 
         parent_to_children) = self._expand_fileids_to_parents_and_children(
1533
 
                                specific_fileids)
1534
 
        # There is some overlap here, but we assume that all interesting items
1535
 
        # are in the _fileid_to_entry_cache because we had to read them to
1536
 
        # determine if they were a dir we wanted to recurse, or just a file
1537
 
        # This should give us all the entries we'll want to add, so start
1538
 
        # adding
1539
 
        other = Inventory(self.root_id)
1540
 
        other.root.revision = self.root.revision
1541
 
        other.revision_id = self.revision_id
1542
 
        if not interesting or not parent_to_children:
1543
 
            # empty filter, or filtering entrys that don't exist
1544
 
            # (if even 1 existed, then we would have populated
1545
 
            # parent_to_children with at least the tree root.)
1546
 
            return other
1547
 
        cache = self._fileid_to_entry_cache
1548
 
        remaining_children = collections.deque(parent_to_children[self.root_id])
1549
 
        while remaining_children:
1550
 
            file_id = remaining_children.popleft()
1551
 
            ie = cache[file_id]
1552
 
            if ie.kind == 'directory':
1553
 
                ie = ie.copy() # We create a copy to depopulate the .children attribute
1554
 
            # TODO: depending on the uses of 'other' we should probably alwyas
1555
 
            #       '.copy()' to prevent someone from mutating other and
1556
 
            #       invaliding our internal cache
1557
 
            other.add(ie)
1558
 
            if file_id in parent_to_children:
1559
 
                remaining_children.extend(parent_to_children[file_id])
1560
 
        return other
1561
 
 
1562
1541
    @staticmethod
1563
1542
    def _bytes_to_utf8name_key(bytes):
1564
1543
        """Get the file_id, revision_id key out of bytes."""
1566
1545
        # to filter out empty names because of non rich-root...
1567
1546
        sections = bytes.split('\n')
1568
1547
        kind, file_id = sections[0].split(': ')
1569
 
        return (sections[2], intern(file_id), intern(sections[3]))
 
1548
        return (sections[2], file_id, sections[3])
1570
1549
 
1571
1550
    def _bytes_to_entry(self, bytes):
1572
1551
        """Deserialise a serialised entry."""
1594
1573
            result.reference_revision = sections[4]
1595
1574
        else:
1596
1575
            raise ValueError("Not a serialised entry %r" % bytes)
1597
 
        result.file_id = intern(result.file_id)
1598
 
        result.revision = intern(sections[3])
 
1576
        result.revision = sections[3]
1599
1577
        if result.parent_id == '':
1600
1578
            result.parent_id = None
1601
1579
        self._fileid_to_entry_cache[result.file_id] = result
1699
1677
                        pass
1700
1678
                deletes.add(file_id)
1701
1679
            else:
1702
 
                new_key = StaticTuple(file_id,)
 
1680
                new_key = (file_id,)
1703
1681
                new_value = result._entry_to_bytes(entry)
1704
1682
                # Update caches. It's worth doing this whether
1705
1683
                # we're propagating the old caches or not.
1708
1686
            if old_path is None:
1709
1687
                old_key = None
1710
1688
            else:
1711
 
                old_key = StaticTuple(file_id,)
 
1689
                old_key = (file_id,)
1712
1690
                if self.id2path(file_id) != old_path:
1713
1691
                    raise errors.InconsistentDelta(old_path, file_id,
1714
1692
                        "Entry was at wrong other path %r." %
1715
1693
                        self.id2path(file_id))
1716
1694
                altered.add(file_id)
1717
 
            id_to_entry_delta.append(StaticTuple(old_key, new_key, new_value))
 
1695
            id_to_entry_delta.append((old_key, new_key, new_value))
1718
1696
            if result.parent_id_basename_to_file_id is not None:
1719
1697
                # parent_id, basename changes
1720
1698
                if old_path is None:
1807
1785
                raise errors.BzrError('Duplicate key in inventory: %r\n%r'
1808
1786
                                      % (key, bytes))
1809
1787
            info[key] = value
1810
 
        revision_id = intern(info['revision_id'])
1811
 
        root_id = intern(info['root_id'])
1812
 
        search_key_name = intern(info.get('search_key_name', 'plain'))
1813
 
        parent_id_basename_to_file_id = intern(info.get(
1814
 
            'parent_id_basename_to_file_id', None))
1815
 
        if not parent_id_basename_to_file_id.startswith('sha1:'):
1816
 
            raise ValueError('parent_id_basename_to_file_id should be a sha1'
1817
 
                             ' key not %r' % (parent_id_basename_to_file_id,))
 
1788
        revision_id = info['revision_id']
 
1789
        root_id = info['root_id']
 
1790
        search_key_name = info.get('search_key_name', 'plain')
 
1791
        parent_id_basename_to_file_id = info.get(
 
1792
            'parent_id_basename_to_file_id', None)
1818
1793
        id_to_entry = info['id_to_entry']
1819
 
        if not id_to_entry.startswith('sha1:'):
1820
 
            raise ValueError('id_to_entry should be a sha1'
1821
 
                             ' key not %r' % (id_to_entry,))
1822
1794
 
1823
1795
        result = CHKInventory(search_key_name)
1824
1796
        result.revision_id = revision_id
1827
1799
                            result._search_key_name)
1828
1800
        if parent_id_basename_to_file_id is not None:
1829
1801
            result.parent_id_basename_to_file_id = chk_map.CHKMap(
1830
 
                chk_store, StaticTuple(parent_id_basename_to_file_id,),
 
1802
                chk_store, (parent_id_basename_to_file_id,),
1831
1803
                search_key_func=search_key_func)
1832
1804
        else:
1833
1805
            result.parent_id_basename_to_file_id = None
1834
1806
 
1835
 
        result.id_to_entry = chk_map.CHKMap(chk_store,
1836
 
                                            StaticTuple(id_to_entry,),
 
1807
        result.id_to_entry = chk_map.CHKMap(chk_store, (id_to_entry,),
1837
1808
                                            search_key_func=search_key_func)
1838
1809
        if (result.revision_id,) != expected_revision_id:
1839
1810
            raise ValueError("Mismatched revision id and expected: %r, %r" %
1861
1832
        id_to_entry_dict = {}
1862
1833
        parent_id_basename_dict = {}
1863
1834
        for path, entry in inventory.iter_entries():
1864
 
            key = StaticTuple(entry.file_id,).intern()
1865
 
            id_to_entry_dict[key] = entry_to_bytes(entry)
 
1835
            id_to_entry_dict[(entry.file_id,)] = entry_to_bytes(entry)
1866
1836
            p_id_key = parent_id_basename_key(entry)
1867
1837
            parent_id_basename_dict[p_id_key] = entry.file_id
1868
1838
 
1891
1861
            parent_id = entry.parent_id
1892
1862
        else:
1893
1863
            parent_id = ''
1894
 
        return StaticTuple(parent_id, entry.name.encode('utf8')).intern()
 
1864
        return parent_id, entry.name.encode('utf8')
1895
1865
 
1896
1866
    def __getitem__(self, file_id):
1897
1867
        """map a single file_id -> InventoryEntry."""
1902
1872
            return result
1903
1873
        try:
1904
1874
            return self._bytes_to_entry(
1905
 
                self.id_to_entry.iteritems([StaticTuple(file_id,)]).next()[1])
 
1875
                self.id_to_entry.iteritems([(file_id,)]).next()[1])
1906
1876
        except StopIteration:
1907
1877
            # really we're passing an inventory, not a tree...
1908
1878
            raise errors.NoSuchId(self, file_id)
1909
1879
 
1910
 
    def _getitems(self, file_ids):
1911
 
        """Similar to __getitem__, but lets you query for multiple.
1912
 
        
1913
 
        The returned order is undefined. And currently if an item doesn't
1914
 
        exist, it isn't included in the output.
1915
 
        """
1916
 
        result = []
1917
 
        remaining = []
1918
 
        for file_id in file_ids:
1919
 
            entry = self._fileid_to_entry_cache.get(file_id, None)
1920
 
            if entry is None:
1921
 
                remaining.append(file_id)
1922
 
            else:
1923
 
                result.append(entry)
1924
 
        file_keys = [StaticTuple(f,).intern() for f in remaining]
1925
 
        for file_key, value in self.id_to_entry.iteritems(file_keys):
1926
 
            entry = self._bytes_to_entry(value)
1927
 
            result.append(entry)
1928
 
            self._fileid_to_entry_cache[entry.file_id] = entry
1929
 
        return result
1930
 
 
1931
1880
    def has_id(self, file_id):
1932
1881
        # Perhaps have an explicit 'contains' method on CHKMap ?
1933
1882
        if self._fileid_to_entry_cache.get(file_id, None) is not None:
1934
1883
            return True
1935
 
        return len(list(
1936
 
            self.id_to_entry.iteritems([StaticTuple(file_id,)]))) == 1
 
1884
        return len(list(self.id_to_entry.iteritems([(file_id,)]))) == 1
1937
1885
 
1938
1886
    def is_root(self, file_id):
1939
1887
        return file_id == self.root_id
2068
2016
            delta.append((old_path, new_path, file_id, entry))
2069
2017
        return delta
2070
2018
 
2071
 
    def path2id(self, relpath):
 
2019
    def path2id(self, name):
2072
2020
        """See CommonInventory.path2id()."""
2073
2021
        # TODO: perhaps support negative hits?
2074
 
        result = self._path_to_fileid_cache.get(relpath, None)
 
2022
        result = self._path_to_fileid_cache.get(name, None)
2075
2023
        if result is not None:
2076
2024
            return result
2077
 
        if isinstance(relpath, basestring):
2078
 
            names = osutils.splitpath(relpath)
 
2025
        if isinstance(name, basestring):
 
2026
            names = osutils.splitpath(name)
2079
2027
        else:
2080
 
            names = relpath
 
2028
            names = name
2081
2029
        current_id = self.root_id
2082
2030
        if current_id is None:
2083
2031
            return None
2084
2032
        parent_id_index = self.parent_id_basename_to_file_id
2085
 
        cur_path = None
2086
2033
        for basename in names:
2087
 
            if cur_path is None:
2088
 
                cur_path = basename
2089
 
            else:
2090
 
                cur_path = cur_path + '/' + basename
 
2034
            # TODO: Cache each path we figure out in this function.
2091
2035
            basename_utf8 = basename.encode('utf8')
2092
 
            file_id = self._path_to_fileid_cache.get(cur_path, None)
 
2036
            key_filter = [(current_id, basename_utf8)]
 
2037
            file_id = None
 
2038
            for (parent_id, name_utf8), file_id in parent_id_index.iteritems(
 
2039
                key_filter=key_filter):
 
2040
                if parent_id != current_id or name_utf8 != basename_utf8:
 
2041
                    raise errors.BzrError("corrupt inventory lookup! "
 
2042
                        "%r %r %r %r" % (parent_id, current_id, name_utf8,
 
2043
                        basename_utf8))
2093
2044
            if file_id is None:
2094
 
                key_filter = [StaticTuple(current_id, basename_utf8)]
2095
 
                items = parent_id_index.iteritems(key_filter)
2096
 
                for (parent_id, name_utf8), file_id in items:
2097
 
                    if parent_id != current_id or name_utf8 != basename_utf8:
2098
 
                        raise errors.BzrError("corrupt inventory lookup! "
2099
 
                            "%r %r %r %r" % (parent_id, current_id, name_utf8,
2100
 
                            basename_utf8))
2101
 
                if file_id is None:
2102
 
                    return None
2103
 
                else:
2104
 
                    self._path_to_fileid_cache[cur_path] = file_id
 
2045
                return None
2105
2046
            current_id = file_id
 
2047
        self._path_to_fileid_cache[name] = current_id
2106
2048
        return current_id
2107
2049
 
2108
2050
    def to_lines(self):
2113
2055
            lines.append('search_key_name: %s\n' % (self._search_key_name,))
2114
2056
            lines.append("root_id: %s\n" % self.root_id)
2115
2057
            lines.append('parent_id_basename_to_file_id: %s\n' %
2116
 
                (self.parent_id_basename_to_file_id.key()[0],))
 
2058
                self.parent_id_basename_to_file_id.key())
2117
2059
            lines.append("revision_id: %s\n" % self.revision_id)
2118
 
            lines.append("id_to_entry: %s\n" % (self.id_to_entry.key()[0],))
 
2060
            lines.append("id_to_entry: %s\n" % self.id_to_entry.key())
2119
2061
        else:
2120
2062
            lines.append("revision_id: %s\n" % self.revision_id)
2121
2063
            lines.append("root_id: %s\n" % self.root_id)
2122
2064
            if self.parent_id_basename_to_file_id is not None:
2123
2065
                lines.append('parent_id_basename_to_file_id: %s\n' %
2124
 
                    (self.parent_id_basename_to_file_id.key()[0],))
2125
 
            lines.append("id_to_entry: %s\n" % (self.id_to_entry.key()[0],))
 
2066
                    self.parent_id_basename_to_file_id.key())
 
2067
            lines.append("id_to_entry: %s\n" % self.id_to_entry.key())
2126
2068
        return lines
2127
2069
 
2128
2070
    @property
2134
2076
class CHKInventoryDirectory(InventoryDirectory):
2135
2077
    """A directory in an inventory."""
2136
2078
 
2137
 
    __slots__ = ['_children', '_chk_inventory']
 
2079
    __slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
 
2080
                 'text_id', 'parent_id', '_children', 'executable',
 
2081
                 'revision', 'symlink_target', 'reference_revision',
 
2082
                 '_chk_inventory']
2138
2083
 
2139
2084
    def __init__(self, file_id, name, parent_id, chk_inventory):
2140
2085
        # Don't call InventoryDirectory.__init__ - it isn't right for this
2141
2086
        # class.
2142
2087
        InventoryEntry.__init__(self, file_id, name, parent_id)
2143
2088
        self._children = None
 
2089
        self.kind = 'directory'
2144
2090
        self._chk_inventory = chk_inventory
2145
2091
 
2146
2092
    @property
2165
2111
        parent_id_index = self._chk_inventory.parent_id_basename_to_file_id
2166
2112
        child_keys = set()
2167
2113
        for (parent_id, name_utf8), file_id in parent_id_index.iteritems(
2168
 
            key_filter=[StaticTuple(self.file_id,)]):
2169
 
            child_keys.add(StaticTuple(file_id,))
 
2114
            key_filter=[(self.file_id,)]):
 
2115
            child_keys.add((file_id,))
2170
2116
        cached = set()
2171
2117
        for file_id_key in child_keys:
2172
2118
            entry = self._chk_inventory._fileid_to_entry_cache.get(
2205
2151
    try:
2206
2152
        factory = entry_factory[kind]
2207
2153
    except KeyError:
2208
 
        raise errors.BadFileKindError(name, kind)
 
2154
        raise BzrError("unknown kind %r" % kind)
2209
2155
    return factory(file_id, name, parent_id)
2210
2156
 
2211
2157