23
23
# But those depend on its position within a particular inventory, and
24
24
# it would be nice not to need to hold the backpointer here.
26
from __future__ import absolute_import
26
28
# This should really be an id randomly assigned when the tree is
27
29
# created, but it's not for now.
30
ROOT_ID = b"TREE_ROOT"
30
from bzrlib.lazy_import import lazy_import
32
from .lazy_import import lazy_import
31
33
lazy_import(globals(), """
48
from bzrlib.errors import (
52
from bzrlib.symbol_versioning import deprecated_in, deprecated_method
53
from bzrlib.trace import mutter
54
from bzrlib.static_tuple import StaticTuple
57
from .static_tuple import StaticTuple
57
60
class InventoryEntry(object):
131
132
RENAMED = 'renamed'
132
133
MODIFIED_AND_RENAMED = 'modified and renamed'
135
__slots__ = ['file_id', 'revision', 'parent_id', 'name']
137
# Attributes that all InventoryEntry instances are expected to have, but
138
# that don't vary for all kinds of entry. (e.g. symlink_target is only
139
# relevant to InventoryLink, so there's no reason to make every
140
# InventoryFile instance allocate space to hold a value for it.)
141
# Attributes that only vary for files: executable, text_sha1, text_size,
147
# Attributes that only vary for symlinks: symlink_target
148
symlink_target = None
149
# Attributes that only vary for tree-references: reference_revision
150
reference_revision = None
136
153
def detect_changes(self, old_entry):
137
154
"""Return a (text_modified, meta_modified) from this to old_entry.
176
193
candidates[ie.revision] = ie
177
194
return candidates
179
@deprecated_method(deprecated_in((1, 6, 0)))
180
def get_tar_item(self, root, dp, now, tree):
181
"""Get a tarfile item and a file stream for its content."""
182
item = tarfile.TarInfo(osutils.pathjoin(root, dp).encode('utf8'))
183
# TODO: would be cool to actually set it to the timestamp of the
184
# revision it was last changed
186
fileobj = self._put_in_tar(item, tree)
189
196
def has_text(self):
190
197
"""Return true if the object this entry represents has textual data.
212
219
Traceback (most recent call last):
213
220
InvalidEntryName: Invalid entry name: src/hello.c
215
if '/' in name or '\\' in name:
222
if u'/' in name or u'\\' in name:
216
223
raise errors.InvalidEntryName(name=name)
217
self.executable = False
224
self.file_id = file_id
218
225
self.revision = None
219
self.text_sha1 = None
220
self.text_size = None
221
self.file_id = file_id
223
self.text_id = text_id
224
227
self.parent_id = parent_id
225
self.symlink_target = None
226
self.reference_revision = None
228
229
def kind_character(self):
229
230
"""Return a short kind indicator useful for appending to names."""
230
raise BzrError('unknown kind %r' % self.kind)
231
raise errors.BzrError('unknown kind %r' % self.kind)
232
233
known_kinds = ('file', 'directory', 'symlink')
234
def _put_in_tar(self, item, tree):
235
"""populate item for stashing in a tar, and return the content stream.
237
If no content is available, return None.
239
raise BzrError("don't know how to export {%s} of kind %r" %
240
(self.file_id, self.kind))
242
@deprecated_method(deprecated_in((1, 6, 0)))
243
def put_on_disk(self, dest, dp, tree):
244
"""Create a representation of self on disk in the prefix dest.
246
This is a template method - implement _put_on_disk in subclasses.
248
fullpath = osutils.pathjoin(dest, dp)
249
self._put_on_disk(fullpath, tree)
250
# mutter(" export {%s} kind %s to %s", self.file_id,
251
# self.kind, fullpath)
253
def _put_on_disk(self, fullpath, tree):
254
"""Put this entry onto disk at fullpath, from tree tree."""
255
raise BzrError("don't know how to export {%s} of kind %r" % (self.file_id, self.kind))
257
def sorted_children(self):
258
return sorted(self.children.items())
261
236
def versionable_kind(kind):
262
237
return (kind in ('file', 'directory', 'symlink', 'tree-reference'))
400
class RootEntry(InventoryEntry):
402
__slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
403
'text_id', 'parent_id', 'children', 'executable',
404
'revision', 'symlink_target', 'reference_revision']
406
def _check(self, checker, rev_id):
407
"""See InventoryEntry._check"""
409
def __init__(self, file_id):
410
self.file_id = file_id
412
self.kind = 'directory'
413
self.parent_id = None
416
symbol_versioning.warn('RootEntry is deprecated as of bzr 0.10.'
417
' Please use InventoryDirectory instead.',
418
DeprecationWarning, stacklevel=2)
420
def __eq__(self, other):
421
if not isinstance(other, RootEntry):
422
return NotImplemented
424
return (self.file_id == other.file_id) \
425
and (self.children == other.children)
428
376
class InventoryDirectory(InventoryEntry):
429
377
"""A directory in an inventory."""
431
__slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
432
'text_id', 'parent_id', 'children', 'executable',
433
'revision', 'symlink_target', 'reference_revision']
379
__slots__ = ['children']
435
383
def _check(self, checker, rev_id):
436
384
"""See InventoryEntry._check"""
437
if (self.text_sha1 is not None or self.text_size is not None or
438
self.text_id is not None):
439
checker._report_items.append('directory {%s} has text in revision {%s}'
440
% (self.file_id, rev_id))
441
385
# In non rich root repositories we do not expect a file graph for the
443
387
if self.name == '' and not checker.rich_roots:
446
390
# to provide a per-fileid log. The hash of every directory content is
447
391
# "da..." below (the sha1sum of '').
448
392
checker.add_pending_item(rev_id,
449
('texts', self.file_id, self.revision), 'text',
450
'da39a3ee5e6b4b0d3255bfef95601890afd80709')
393
(b'texts', self.file_id, self.revision), b'text',
394
b'da39a3ee5e6b4b0d3255bfef95601890afd80709')
453
397
other = InventoryDirectory(self.file_id, self.name, self.parent_id)
459
403
def __init__(self, file_id, name, parent_id):
460
404
super(InventoryDirectory, self).__init__(file_id, name, parent_id)
461
405
self.children = {}
462
self.kind = 'directory'
407
def sorted_children(self):
408
return sorted(viewitems(self.children))
464
410
def kind_character(self):
465
411
"""See InventoryEntry.kind_character."""
468
def _put_in_tar(self, item, tree):
469
"""See InventoryEntry._put_in_tar."""
470
item.type = tarfile.DIRTYPE
477
def _put_on_disk(self, fullpath, tree):
478
"""See InventoryEntry._put_on_disk."""
482
415
class InventoryFile(InventoryEntry):
483
416
"""A file in an inventory."""
485
__slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
486
'text_id', 'parent_id', 'children', 'executable',
487
'revision', 'symlink_target', 'reference_revision']
418
__slots__ = ['text_sha1', 'text_size', 'text_id', 'executable']
422
def __init__(self, file_id, name, parent_id):
423
super(InventoryFile, self).__init__(file_id, name, parent_id)
424
self.text_sha1 = None
425
self.text_size = None
427
self.executable = False
489
429
def _check(self, checker, tree_revision_id):
490
430
"""See InventoryEntry._check"""
491
431
# TODO: check size too.
492
432
checker.add_pending_item(tree_revision_id,
493
('texts', self.file_id, self.revision), 'text',
433
(b'texts', self.file_id, self.revision), b'text',
495
435
if self.text_size is None:
496
436
checker._report_items.append(
515
455
def _diff(self, text_diff, from_label, tree, to_label, to_entry, to_tree,
516
456
output_to, reverse=False):
517
457
"""See InventoryEntry._diff."""
518
from bzrlib.diff import DiffText
458
from breezy.diff import DiffText
519
459
from_file_id = self.file_id
521
461
to_file_id = to_entry.file_id
533
473
"""See InventoryEntry.has_text."""
536
def __init__(self, file_id, name, parent_id):
537
super(InventoryFile, self).__init__(file_id, name, parent_id)
540
476
def kind_character(self):
541
477
"""See InventoryEntry.kind_character."""
544
def _put_in_tar(self, item, tree):
545
"""See InventoryEntry._put_in_tar."""
546
item.type = tarfile.REGTYPE
547
fileobj = tree.get_file(self.file_id)
548
item.size = self.text_size
549
if tree.is_executable(self.file_id):
555
def _put_on_disk(self, fullpath, tree):
556
"""See InventoryEntry._put_on_disk."""
557
osutils.pumpfile(tree.get_file(self.file_id), file(fullpath, 'wb'))
558
if tree.is_executable(self.file_id):
559
os.chmod(fullpath, 0755)
561
480
def _read_tree_state(self, path, work_tree):
562
481
"""See InventoryEntry._read_tree_state."""
563
482
self.text_sha1 = work_tree.get_file_sha1(self.file_id, path=path)
595
514
class InventoryLink(InventoryEntry):
596
515
"""A file in an inventory."""
598
__slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
599
'text_id', 'parent_id', 'children', 'executable',
600
'revision', 'symlink_target', 'reference_revision']
517
__slots__ = ['symlink_target']
521
def __init__(self, file_id, name, parent_id):
522
super(InventoryLink, self).__init__(file_id, name, parent_id)
523
self.symlink_target = None
602
525
def _check(self, checker, tree_revision_id):
603
526
"""See InventoryEntry._check"""
604
if self.text_sha1 is not None or self.text_size is not None or self.text_id is not None:
605
checker._report_items.append(
606
'symlink {%s} has text in revision {%s}'
607
% (self.file_id, tree_revision_id))
608
527
if self.symlink_target is None:
609
528
checker._report_items.append(
610
529
'symlink {%s} has no target in revision {%s}'
611
530
% (self.file_id, tree_revision_id))
612
531
# Symlinks are stored as ''
613
532
checker.add_pending_item(tree_revision_id,
614
('texts', self.file_id, self.revision), 'text',
615
'da39a3ee5e6b4b0d3255bfef95601890afd80709')
533
(b'texts', self.file_id, self.revision), b'text',
534
b'da39a3ee5e6b4b0d3255bfef95601890afd80709')
618
537
other = InventoryLink(self.file_id, self.name, self.parent_id)
625
544
# FIXME: which _modified field should we use ? RBC 20051003
626
545
text_modified = (self.symlink_target != old_entry.symlink_target)
627
546
if text_modified:
628
mutter(" symlink target changed")
547
trace.mutter(" symlink target changed")
629
548
meta_modified = False
630
549
return text_modified, meta_modified
632
551
def _diff(self, text_diff, from_label, tree, to_label, to_entry, to_tree,
633
552
output_to, reverse=False):
634
553
"""See InventoryEntry._diff."""
635
from bzrlib.diff import DiffSymlink
554
from breezy.diff import DiffSymlink
636
555
old_target = self.symlink_target
637
556
if to_entry is not None:
638
557
new_target = to_entry.symlink_target
648
567
differ = DiffSymlink(old_tree, new_tree, output_to)
649
568
return differ.diff_symlink(old_target, new_target)
651
def __init__(self, file_id, name, parent_id):
652
super(InventoryLink, self).__init__(file_id, name, parent_id)
653
self.kind = 'symlink'
655
570
def kind_character(self):
656
571
"""See InventoryEntry.kind_character."""
659
def _put_in_tar(self, item, tree):
660
"""See InventoryEntry._put_in_tar."""
661
item.type = tarfile.SYMTYPE
665
item.linkname = self.symlink_target
668
def _put_on_disk(self, fullpath, tree):
669
"""See InventoryEntry._put_on_disk."""
671
os.symlink(self.symlink_target, fullpath)
673
raise BzrError("Failed to create symlink %r -> %r, error: %s" % (fullpath, self.symlink_target, e))
675
574
def _read_tree_state(self, path, work_tree):
676
575
"""See InventoryEntry._read_tree_state."""
677
576
self.symlink_target = work_tree.get_symlink_target(self.file_id)
733
634
inserted, other than through the Inventory API.
736
def __contains__(self, file_id):
737
"""True if this entry contains a file with given id.
739
>>> inv = Inventory()
740
>>> inv.add(InventoryFile('123', 'foo.c', ROOT_ID))
741
InventoryFile('123', 'foo.c', parent_id='TREE_ROOT', sha1=None, len=None, revision=None)
747
Note that this method along with __iter__ are not encouraged for use as
748
they are less clear than specific query methods - they may be rmeoved
751
return self.has_id(file_id)
753
637
def has_filename(self, filename):
754
638
return bool(self.path2id(filename))
913
808
file_id, self[file_id]))
916
def _get_mutable_inventory(self):
917
"""Returns a mutable copy of the object.
919
Some inventories are immutable, yet working trees, for example, needs
920
to mutate exisiting inventories instead of creating a new one.
922
raise NotImplementedError(self._get_mutable_inventory)
924
811
def make_entry(self, kind, name, parent_id, file_id=None):
925
"""Simple thunk to bzrlib.inventory.make_entry."""
812
"""Simple thunk to breezy.inventory.make_entry."""
926
813
return make_entry(kind, name, parent_id, file_id)
928
815
def entries(self):
934
821
def descend(dir_ie, dir_path):
935
kids = dir_ie.children.items()
822
kids = sorted(viewitems(dir_ie.children))
937
823
for name, ie in kids:
938
824
child_path = osutils.pathjoin(dir_path, name)
939
825
accum.append((child_path, ie))
940
826
if ie.kind == 'directory':
941
827
descend(ie, child_path)
943
descend(self.root, u'')
946
def directories(self):
947
"""Return (path, entry) pairs for all directories, including the root.
950
def descend(parent_ie, parent_path):
951
accum.append((parent_path, parent_ie))
953
kids = [(ie.name, ie) for ie in parent_ie.children.itervalues() if ie.kind == 'directory']
956
for name, child_ie in kids:
957
child_path = osutils.pathjoin(parent_path, name)
958
descend(child_ie, child_path)
959
descend(self.root, u'')
829
if self.root is not None:
830
descend(self.root, u'')
962
833
def path2id(self, relpath):
1272
1138
def _add_child(self, entry):
1273
1139
"""Add an entry to the inventory, without adding it to its parent"""
1274
1140
if entry.file_id in self._byid:
1275
raise BzrError("inventory already contains entry with id {%s}" %
1141
raise errors.BzrError(
1142
"inventory already contains entry with id {%s}" %
1277
1144
self._byid[entry.file_id] = entry
1278
for child in getattr(entry, 'children', {}).itervalues():
1279
self._add_child(child)
1145
children = getattr(entry, 'children', {})
1146
if children is not None:
1147
for child in viewvalues(children):
1148
self._add_child(child)
1282
1151
def add(self, entry):
1283
1152
"""Add entry to inventory.
1285
To add a file to a branch ready to be committed, use Branch.add,
1290
1156
if entry.file_id in self._byid:
1447
1313
new_name = ensure_normalized_name(new_name)
1448
1314
if not is_valid_name(new_name):
1449
raise BzrError("not an acceptable filename: %r" % new_name)
1315
raise errors.BzrError("not an acceptable filename: %r" % new_name)
1451
1317
new_parent = self._byid[new_parent_id]
1452
1318
if new_name in new_parent.children:
1453
raise BzrError("%r already exists in %r" % (new_name, self.id2path(new_parent_id)))
1319
raise errors.BzrError("%r already exists in %r" %
1320
(new_name, self.id2path(new_parent_id)))
1455
1322
new_parent_idpath = self.get_idpath(new_parent_id)
1456
1323
if file_id in new_parent_idpath:
1457
raise BzrError("cannot move directory %r into a subdirectory of itself, %r"
1324
raise errors.BzrError(
1325
"cannot move directory %r into a subdirectory of itself, %r"
1458
1326
% (self.id2path(file_id), self.id2path(new_parent_id)))
1460
1328
file_ie = self._byid[file_id]
1531
1400
if entry.parent_id is not None:
1532
1401
parent_str = entry.parent_id
1535
1404
name_str = entry.name.encode("utf8")
1536
1405
if entry.kind == 'file':
1537
1406
if entry.executable:
1541
return "file: %s\n%s\n%s\n%s\n%s\n%d\n%s" % (
1410
return b"file: %s\n%s\n%s\n%s\n%s\n%d\n%s" % (
1542
1411
entry.file_id, parent_str, name_str, entry.revision,
1543
1412
entry.text_sha1, entry.text_size, exec_str)
1544
1413
elif entry.kind == 'directory':
1545
return "dir: %s\n%s\n%s\n%s" % (
1414
return b"dir: %s\n%s\n%s\n%s" % (
1546
1415
entry.file_id, parent_str, name_str, entry.revision)
1547
1416
elif entry.kind == 'symlink':
1548
return "symlink: %s\n%s\n%s\n%s\n%s" % (
1417
return b"symlink: %s\n%s\n%s\n%s\n%s" % (
1549
1418
entry.file_id, parent_str, name_str, entry.revision,
1550
1419
entry.symlink_target.encode("utf8"))
1551
1420
elif entry.kind == 'tree-reference':
1552
return "tree: %s\n%s\n%s\n%s\n%s" % (
1421
return b"tree: %s\n%s\n%s\n%s\n%s" % (
1553
1422
entry.file_id, parent_str, name_str, entry.revision,
1554
1423
entry.reference_revision)
1617
1486
keys = [StaticTuple(f,).intern() for f in directories_to_expand]
1618
1487
directories_to_expand = set()
1619
1488
items = self.parent_id_basename_to_file_id.iteritems(keys)
1620
next_file_ids = set([item[1] for item in items])
1489
next_file_ids = {item[1] for item in items}
1621
1490
next_file_ids = next_file_ids.difference(interesting)
1622
1491
interesting.update(next_file_ids)
1623
1492
for entry in self._getitems(next_file_ids):
1624
1493
if entry.kind == 'directory':
1625
1494
directories_to_expand.add(entry.file_id)
1626
children_of_parent_id.setdefault(entry.parent_id, []
1627
).append(entry.file_id)
1495
children_of_parent_id.setdefault(entry.parent_id, set()
1496
).add(entry.file_id)
1628
1497
return interesting, children_of_parent_id
1630
1499
def filter(self, specific_fileids):
1674
def _bytes_to_utf8name_key(bytes):
1675
"""Get the file_id, revision_id key out of bytes."""
1539
def _bytes_to_utf8name_key(data):
1540
"""Get the file_id, revision_id key out of data."""
1676
1541
# We don't normally care about name, except for times when we want
1677
1542
# to filter out empty names because of non rich-root...
1678
sections = bytes.split('\n')
1679
kind, file_id = sections[0].split(': ')
1680
return (sections[2], intern(file_id), intern(sections[3]))
1543
sections = data.split(b'\n')
1544
kind, file_id = sections[0].split(b': ')
1545
return (sections[2], bytesintern(file_id), bytesintern(sections[3]))
1682
1547
def _bytes_to_entry(self, bytes):
1683
1548
"""Deserialise a serialised entry."""
1684
sections = bytes.split('\n')
1685
if sections[0].startswith("file: "):
1549
sections = bytes.split(b'\n')
1550
if sections[0].startswith(b"file: "):
1686
1551
result = InventoryFile(sections[0][6:],
1687
1552
sections[2].decode('utf8'),
1689
1554
result.text_sha1 = sections[4]
1690
1555
result.text_size = int(sections[5])
1691
result.executable = sections[6] == "Y"
1692
elif sections[0].startswith("dir: "):
1556
result.executable = sections[6] == b"Y"
1557
elif sections[0].startswith(b"dir: "):
1693
1558
result = CHKInventoryDirectory(sections[0][5:],
1694
1559
sections[2].decode('utf8'),
1695
1560
sections[1], self)
1696
elif sections[0].startswith("symlink: "):
1561
elif sections[0].startswith(b"symlink: "):
1697
1562
result = InventoryLink(sections[0][9:],
1698
1563
sections[2].decode('utf8'),
1700
1565
result.symlink_target = sections[4].decode('utf8')
1701
elif sections[0].startswith("tree: "):
1566
elif sections[0].startswith(b"tree: "):
1702
1567
result = TreeReference(sections[0][6:],
1703
1568
sections[2].decode('utf8'),
1705
1570
result.reference_revision = sections[4]
1707
1572
raise ValueError("Not a serialised entry %r" % bytes)
1708
result.file_id = intern(result.file_id)
1709
result.revision = intern(sections[3])
1710
if result.parent_id == '':
1573
result.file_id = bytesintern(result.file_id)
1574
result.revision = bytesintern(sections[3])
1575
if result.parent_id == b'':
1711
1576
result.parent_id = None
1712
1577
self._fileid_to_entry_cache[result.file_id] = result
1715
def _get_mutable_inventory(self):
1716
"""See CommonInventory._get_mutable_inventory."""
1717
entries = self.iter_entries()
1718
inv = Inventory(None, self.revision_id)
1719
for path, inv_entry in entries:
1720
inv.add(inv_entry.copy())
1723
1580
def create_by_apply_delta(self, inventory_delta, new_revision_id,
1724
1581
propagate_caches=False):
1725
1582
"""Create a new CHKInventory by applying inventory_delta to this one.
1900
1757
:return: A CHKInventory
1902
lines = bytes.split('\n')
1759
lines = bytes.split(b'\n')
1760
if lines[-1] != b'':
1904
1761
raise AssertionError('bytes to deserialize must end with an eol')
1906
if lines[0] != 'chkinventory:':
1763
if lines[0] != b'chkinventory:':
1907
1764
raise ValueError("not a serialised CHKInventory: %r" % bytes)
1909
allowed_keys = frozenset(['root_id', 'revision_id', 'search_key_name',
1910
'parent_id_basename_to_file_id',
1766
allowed_keys = frozenset((b'root_id', b'revision_id',
1767
b'parent_id_basename_to_file_id',
1768
b'search_key_name', b'id_to_entry'))
1912
1769
for line in lines[1:]:
1913
key, value = line.split(': ', 1)
1770
key, value = line.split(b': ', 1)
1914
1771
if key not in allowed_keys:
1915
1772
raise errors.BzrError('Unknown key in inventory: %r\n%r'
1916
1773
% (key, bytes))
1918
1775
raise errors.BzrError('Duplicate key in inventory: %r\n%r'
1919
1776
% (key, bytes))
1920
1777
info[key] = value
1921
revision_id = intern(info['revision_id'])
1922
root_id = intern(info['root_id'])
1923
search_key_name = intern(info.get('search_key_name', 'plain'))
1924
parent_id_basename_to_file_id = intern(info.get(
1925
'parent_id_basename_to_file_id', None))
1926
if not parent_id_basename_to_file_id.startswith('sha1:'):
1778
revision_id = bytesintern(info[b'revision_id'])
1779
root_id = bytesintern(info[b'root_id'])
1780
search_key_name = bytesintern(info.get(b'search_key_name', b'plain'))
1781
parent_id_basename_to_file_id = bytesintern(info.get(
1782
b'parent_id_basename_to_file_id', None))
1783
if not parent_id_basename_to_file_id.startswith(b'sha1:'):
1927
1784
raise ValueError('parent_id_basename_to_file_id should be a sha1'
1928
1785
' key not %r' % (parent_id_basename_to_file_id,))
1929
id_to_entry = info['id_to_entry']
1930
if not id_to_entry.startswith('sha1:'):
1786
id_to_entry = info[b'id_to_entry']
1787
if not id_to_entry.startswith(b'sha1:'):
1931
1788
raise ValueError('id_to_entry should be a sha1'
1932
1789
' key not %r' % (id_to_entry,))
2080
1937
self._fileid_to_entry_cache[file_id] = ie
1940
def _preload_cache(self):
1941
"""Make sure all file-ids are in _fileid_to_entry_cache"""
1942
if self._fully_cached:
1943
return # No need to do it again
1944
# The optimal sort order is to use iteritems() directly
1945
cache = self._fileid_to_entry_cache
1946
for key, entry in self.id_to_entry.iteritems():
1948
if file_id not in cache:
1949
ie = self._bytes_to_entry(entry)
1953
last_parent_id = last_parent_ie = None
1954
pid_items = self.parent_id_basename_to_file_id.iteritems()
1955
for key, child_file_id in pid_items:
1956
if key == (b'', b''): # This is the root
1957
if child_file_id != self.root_id:
1958
raise ValueError('Data inconsistency detected.'
1959
' We expected data with key ("","") to match'
1960
' the root id, but %s != %s'
1961
% (child_file_id, self.root_id))
1963
parent_id, basename = key
1964
ie = cache[child_file_id]
1965
if parent_id == last_parent_id:
1966
parent_ie = last_parent_ie
1968
parent_ie = cache[parent_id]
1969
if parent_ie.kind != 'directory':
1970
raise ValueError('Data inconsistency detected.'
1971
' An entry in the parent_id_basename_to_file_id map'
1972
' has parent_id {%s} but the kind of that object'
1973
' is %r not "directory"' % (parent_id, parent_ie.kind))
1974
if parent_ie._children is None:
1975
parent_ie._children = {}
1976
basename = basename.decode('utf-8')
1977
if basename in parent_ie._children:
1978
existing_ie = parent_ie._children[basename]
1979
if existing_ie != ie:
1980
raise ValueError('Data inconsistency detected.'
1981
' Two entries with basename %r were found'
1982
' in the parent entry {%s}'
1983
% (basename, parent_id))
1984
if basename != ie.name:
1985
raise ValueError('Data inconsistency detected.'
1986
' In the parent_id_basename_to_file_id map, file_id'
1987
' {%s} is listed as having basename %r, but in the'
1988
' id_to_entry map it is %r'
1989
% (child_file_id, basename, ie.name))
1990
parent_ie._children[basename] = ie
1991
self._fully_cached = True
2083
1993
def iter_changes(self, basis):
2084
1994
"""Generate a Tree.iter_changes change list between this and basis.
2182
2092
def path2id(self, relpath):
2183
2093
"""See CommonInventory.path2id()."""
2184
2094
# TODO: perhaps support negative hits?
2095
if isinstance(relpath, basestring):
2096
names = osutils.splitpath(relpath)
2101
relpath = osutils.pathjoin(*relpath)
2185
2102
result = self._path_to_fileid_cache.get(relpath, None)
2186
2103
if result is not None:
2188
if isinstance(relpath, basestring):
2189
names = osutils.splitpath(relpath)
2192
2105
current_id = self.root_id
2193
2106
if current_id is None:
2219
2132
def to_lines(self):
2220
2133
"""Serialise the inventory to lines."""
2221
lines = ["chkinventory:\n"]
2134
lines = [b"chkinventory:\n"]
2222
2135
if self._search_key_name != 'plain':
2223
2136
# custom ordering grouping things that don't change together
2224
lines.append('search_key_name: %s\n' % (self._search_key_name,))
2225
lines.append("root_id: %s\n" % self.root_id)
2226
lines.append('parent_id_basename_to_file_id: %s\n' %
2137
lines.append(b'search_key_name: %s\n' % (
2138
self._search_key_name.encode('ascii')))
2139
lines.append(b"root_id: %s\n" % self.root_id)
2140
lines.append(b'parent_id_basename_to_file_id: %s\n' %
2227
2141
(self.parent_id_basename_to_file_id.key()[0],))
2228
lines.append("revision_id: %s\n" % self.revision_id)
2229
lines.append("id_to_entry: %s\n" % (self.id_to_entry.key()[0],))
2142
lines.append(b"revision_id: %s\n" % self.revision_id)
2143
lines.append(b"id_to_entry: %s\n" % (self.id_to_entry.key()[0],))
2231
lines.append("revision_id: %s\n" % self.revision_id)
2232
lines.append("root_id: %s\n" % self.root_id)
2145
lines.append(b"revision_id: %s\n" % self.revision_id)
2146
lines.append(b"root_id: %s\n" % self.root_id)
2233
2147
if self.parent_id_basename_to_file_id is not None:
2234
lines.append('parent_id_basename_to_file_id: %s\n' %
2148
lines.append(b'parent_id_basename_to_file_id: %s\n' %
2235
2149
(self.parent_id_basename_to_file_id.key()[0],))
2236
lines.append("id_to_entry: %s\n" % (self.id_to_entry.key()[0],))
2150
lines.append(b"id_to_entry: %s\n" % (self.id_to_entry.key()[0],))
2245
2159
class CHKInventoryDirectory(InventoryDirectory):
2246
2160
"""A directory in an inventory."""
2248
__slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
2249
'text_id', 'parent_id', '_children', 'executable',
2250
'revision', 'symlink_target', 'reference_revision',
2162
__slots__ = ['_children', '_chk_inventory']
2253
2164
def __init__(self, file_id, name, parent_id, chk_inventory):
2254
2165
# Don't call InventoryDirectory.__init__ - it isn't right for this
2256
2167
InventoryEntry.__init__(self, file_id, name, parent_id)
2257
2168
self._children = None
2258
self.kind = 'directory'
2259
2169
self._chk_inventory = chk_inventory
2448
2354
raise errors.InconsistentDelta(new_path, item[1],
2449
2355
"new_path with no entry")
2359
def mutable_inventory_from_tree(tree):
2360
"""Create a new inventory that has the same contents as a specified tree.
2362
:param tree: Revision tree to create inventory from
2364
entries = tree.iter_entries_by_dir()
2365
inv = Inventory(None, tree.get_revision_id())
2366
for path, inv_entry in entries:
2367
inv.add(inv_entry.copy())