78
81
>>> i.add(InventoryDirectory('123', 'src', ROOT_ID))
79
InventoryDirectory('123', 'src', parent_id='TREE_ROOT')
82
InventoryDirectory('123', 'src', parent_id='TREE_ROOT', revision=None)
80
83
>>> i.add(InventoryFile('2323', 'hello.c', parent_id='123'))
81
InventoryFile('2323', 'hello.c', parent_id='123')
82
>>> shouldbe = {0: 'src', 1: pathjoin('src','hello.c')}
84
InventoryFile('2323', 'hello.c', parent_id='123', sha1=None, len=None)
85
>>> shouldbe = {0: '', 1: 'src', 2: pathjoin('src','hello.c')}
83
86
>>> for ix, j in enumerate(i.iter_entries()):
84
87
... print (j[0] == shouldbe[ix], j[1])
86
(True, InventoryDirectory('123', 'src', parent_id='TREE_ROOT'))
87
(True, InventoryFile('2323', 'hello.c', parent_id='123'))
89
(True, InventoryDirectory('TREE_ROOT', '', parent_id=None, revision=None))
90
(True, InventoryDirectory('123', 'src', parent_id='TREE_ROOT', revision=None))
91
(True, InventoryFile('2323', 'hello.c', parent_id='123', sha1=None, len=None))
88
92
>>> i.add(InventoryFile('2323', 'bye.c', '123'))
89
93
Traceback (most recent call last):
91
95
BzrError: inventory already contains entry with id {2323}
92
96
>>> i.add(InventoryFile('2324', 'bye.c', '123'))
93
InventoryFile('2324', 'bye.c', parent_id='123')
97
InventoryFile('2324', 'bye.c', parent_id='123', sha1=None, len=None)
94
98
>>> i.add(InventoryDirectory('2325', 'wibble', '123'))
95
InventoryDirectory('2325', 'wibble', parent_id='123')
99
InventoryDirectory('2325', 'wibble', parent_id='123', revision=None)
96
100
>>> i.path2id('src/wibble')
100
104
>>> i.add(InventoryFile('2326', 'wibble.c', '2325'))
101
InventoryFile('2326', 'wibble.c', parent_id='2325')
105
InventoryFile('2326', 'wibble.c', parent_id='2325', sha1=None, len=None)
103
InventoryFile('2326', 'wibble.c', parent_id='2325')
107
InventoryFile('2326', 'wibble.c', parent_id='2325', sha1=None, len=None)
104
108
>>> for path, entry in i.iter_entries():
106
110
... assert i.path2id(path)
113
118
>>> i.id2path('2326')
114
119
'src/wibble/wibble.c'
122
# Constants returned by describe_change()
124
# TODO: These should probably move to some kind of FileChangeDescription
125
# class; that's like what's inside a TreeDelta but we want to be able to
126
# generate them just for one file at a time.
128
MODIFIED_AND_RENAMED = 'modified and renamed'
117
__slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
118
'text_id', 'parent_id', 'children', 'executable',
121
def _add_text_to_weave(self, new_lines, parents, weave_store, transaction):
122
versionedfile = weave_store.get_weave_or_empty(self.file_id,
124
versionedfile.add_lines(self.revision, parents, new_lines)
126
132
def detect_changes(self, old_entry):
127
133
"""Return a (text_modified, meta_modified) from this to old_entry.
308
314
fullpath = pathjoin(dest, dp)
309
315
self._put_on_disk(fullpath, tree)
310
mutter(" export {%s} kind %s to %s", self.file_id,
316
# mutter(" export {%s} kind %s to %s", self.file_id,
317
# self.kind, fullpath)
313
319
def _put_on_disk(self, fullpath, tree):
314
320
"""Put this entry onto disk at fullpath, from tree tree."""
315
321
raise BzrError("don't know how to export {%s} of kind %r" % (self.file_id, self.kind))
317
323
def sorted_children(self):
318
l = self.children.items()
324
return sorted(self.children.items())
323
327
def versionable_kind(kind):
324
return kind in ('file', 'directory', 'symlink')
328
return (kind in ('file', 'directory', 'symlink'))
326
330
def check(self, checker, rev_id, inv, tree):
327
331
"""Check this inventory entry is intact.
348
352
raise BzrCheckError('unknown entry kind %r in revision {%s}' %
349
353
(self.kind, rev_id))
353
356
"""Clone this inventory entry."""
354
357
raise NotImplementedError
356
def _get_snapshot_change(self, previous_entries):
357
if len(previous_entries) > 1:
359
elif len(previous_entries) == 0:
360
def describe_change(old_entry, new_entry):
361
"""Describe the change between old_entry and this.
363
This smells of being an InterInventoryEntry situation, but as its
364
the first one, we're making it a static method for now.
366
An entry with a different parent, or different name is considered
367
to be renamed. Reparenting is an internal detail.
368
Note that renaming the parent does not trigger a rename for the
371
# TODO: Perhaps return an object rather than just a string
372
if old_entry is new_entry:
373
# also the case of both being None
375
elif old_entry is None:
362
return 'modified/renamed/reparented'
377
elif new_entry is None:
379
text_modified, meta_modified = new_entry.detect_changes(old_entry)
380
if text_modified or meta_modified:
384
# TODO 20060511 (mbp, rbc) factor out 'detect_rename' here.
385
if old_entry.parent_id != new_entry.parent_id:
387
elif old_entry.name != new_entry.name:
391
if renamed and not modified:
392
return InventoryEntry.RENAMED
393
if modified and not renamed:
395
if modified and renamed:
396
return InventoryEntry.MODIFIED_AND_RENAMED
364
399
def __repr__(self):
365
return ("%s(%r, %r, parent_id=%r)"
400
return ("%s(%r, %r, parent_id=%r, revision=%r)"
366
401
% (self.__class__.__name__,
371
407
def snapshot(self, revision, path, previous_entries,
372
work_tree, weave_store, transaction):
408
work_tree, commit_builder):
373
409
"""Make a snapshot of this entry which may or may not have changed.
375
411
This means that all its fields are populated, that it has its
376
412
text stored in the text store or weave.
378
mutter('new parents of %s are %r', path, previous_entries)
414
# mutter('new parents of %s are %r', path, previous_entries)
379
415
self._read_tree_state(path, work_tree)
416
# TODO: Where should we determine whether to reuse a
417
# previous revision id or create a new revision? 20060606
380
418
if len(previous_entries) == 1:
381
419
# cannot be unchanged unless there is only one parent file rev.
382
420
parent_ie = previous_entries.values()[0]
383
421
if self._unchanged(parent_ie):
384
mutter("found unchanged entry")
422
# mutter("found unchanged entry")
385
423
self.revision = parent_ie.revision
386
424
return "unchanged"
387
return self.snapshot_revision(revision, previous_entries,
388
work_tree, weave_store, transaction)
390
def snapshot_revision(self, revision, previous_entries, work_tree,
391
weave_store, transaction):
392
"""Record this revision unconditionally."""
393
mutter('new revision for {%s}', self.file_id)
425
return self._snapshot_into_revision(revision, previous_entries,
426
work_tree, commit_builder)
428
def _snapshot_into_revision(self, revision, previous_entries, work_tree,
430
"""Record this revision unconditionally into a store.
432
The entry's last-changed revision property (`revision`) is updated to
433
that of the new revision.
435
:param revision: id of the new revision that is being recorded.
437
:returns: String description of the commit (e.g. "merged", "modified"), etc.
439
# mutter('new revision {%s} for {%s}', revision, self.file_id)
394
440
self.revision = revision
395
change = self._get_snapshot_change(previous_entries)
396
self._snapshot_text(previous_entries, work_tree, weave_store,
441
self._snapshot_text(previous_entries, work_tree, commit_builder)
400
def _snapshot_text(self, file_parents, work_tree, weave_store, transaction):
443
def _snapshot_text(self, file_parents, work_tree, commit_builder):
401
444
"""Record the 'text' of this entry, whatever form that takes.
403
446
This default implementation simply adds an empty text.
405
mutter('storing file {%s} in revision {%s}',
406
self.file_id, self.revision)
407
self._add_text_to_weave([], file_parents.keys(), weave_store, transaction)
448
raise NotImplementedError(self._snapshot_text)
409
450
def __eq__(self, other):
410
451
if not isinstance(other, InventoryEntry):
460
501
class RootEntry(InventoryEntry):
503
__slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
504
'text_id', 'parent_id', 'children', 'executable',
505
'revision', 'symlink_target']
462
507
def _check(self, checker, rev_id, tree):
463
508
"""See InventoryEntry._check"""
465
510
def __init__(self, file_id):
466
511
self.file_id = file_id
467
512
self.children = {}
468
self.kind = 'root_directory'
513
self.kind = 'directory'
469
514
self.parent_id = None
517
warn('RootEntry is deprecated as of bzr 0.10. Please use '
518
'InventoryDirectory instead.',
519
DeprecationWarning, stacklevel=2)
472
521
def __eq__(self, other):
473
522
if not isinstance(other, RootEntry):
515
568
"""See InventoryEntry._put_on_disk."""
516
569
os.mkdir(fullpath)
571
def _snapshot_text(self, file_parents, work_tree, commit_builder):
572
"""See InventoryEntry._snapshot_text."""
573
commit_builder.modified_directory(self.file_id, file_parents)
519
576
class InventoryFile(InventoryEntry):
520
577
"""A file in an inventory."""
579
__slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
580
'text_id', 'parent_id', 'children', 'executable',
581
'revision', 'symlink_target']
522
583
def _check(self, checker, tree_revision_id, tree):
523
584
"""See InventoryEntry._check"""
524
585
t = (self.file_id, self.revision)
572
633
def _diff(self, text_diff, from_label, tree, to_label, to_entry, to_tree,
573
634
output_to, reverse=False):
574
635
"""See InventoryEntry._diff."""
575
from_text = tree.get_file(self.file_id).readlines()
577
to_text = to_tree.get_file(to_entry.file_id).readlines()
581
text_diff(from_label, from_text,
582
to_label, to_text, output_to)
584
text_diff(to_label, to_text,
585
from_label, from_text, output_to)
637
from_text = tree.get_file(self.file_id).readlines()
639
to_text = to_tree.get_file(to_entry.file_id).readlines()
643
text_diff(from_label, from_text,
644
to_label, to_text, output_to)
646
text_diff(to_label, to_text,
647
from_label, from_text, output_to)
650
label_pair = (to_label, from_label)
652
label_pair = (from_label, to_label)
653
print >> output_to, "Binary files %s and %s differ" % label_pair
587
655
def has_text(self):
588
656
"""See InventoryEntry.has_text."""
616
684
def _read_tree_state(self, path, work_tree):
617
685
"""See InventoryEntry._read_tree_state."""
618
self.text_sha1 = work_tree.get_file_sha1(self.file_id)
619
self.executable = work_tree.is_executable(self.file_id)
686
self.text_sha1 = work_tree.get_file_sha1(self.file_id, path=path)
687
# FIXME: 20050930 probe for the text size when getting sha1
688
# in _read_tree_state
689
self.executable = work_tree.is_executable(self.file_id, path=path)
692
return ("%s(%r, %r, parent_id=%r, sha1=%r, len=%s)"
693
% (self.__class__.__name__,
621
700
def _forget_tree_state(self):
622
701
self.text_sha1 = None
623
self.executable = None
625
def _snapshot_text(self, file_parents, work_tree, weave_store, transaction):
703
def _snapshot_text(self, file_parents, work_tree, commit_builder):
626
704
"""See InventoryEntry._snapshot_text."""
627
mutter('storing file {%s} in revision {%s}',
628
self.file_id, self.revision)
629
# special case to avoid diffing on renames or
631
if (len(file_parents) == 1
632
and self.text_sha1 == file_parents.values()[0].text_sha1
633
and self.text_size == file_parents.values()[0].text_size):
634
previous_ie = file_parents.values()[0]
635
versionedfile = weave_store.get_weave(self.file_id, transaction)
636
versionedfile.clone_text(self.revision, previous_ie.revision, file_parents.keys())
638
new_lines = work_tree.get_file(self.file_id).readlines()
639
self._add_text_to_weave(new_lines, file_parents.keys(), weave_store,
641
self.text_sha1 = sha_strings(new_lines)
642
self.text_size = sum(map(len, new_lines))
705
def get_content_byte_lines():
706
return work_tree.get_file(self.file_id).readlines()
707
self.text_sha1, self.text_size = commit_builder.modified_file_text(
708
self.file_id, file_parents, get_content_byte_lines, self.text_sha1, self.text_size)
645
710
def _unchanged(self, previous_ie):
646
711
"""See InventoryEntry._unchanged."""
659
724
class InventoryLink(InventoryEntry):
660
725
"""A file in an inventory."""
662
__slots__ = ['symlink_target']
727
__slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
728
'text_id', 'parent_id', 'children', 'executable',
729
'revision', 'symlink_target']
664
731
def _check(self, checker, rev_id, tree):
665
732
"""See InventoryEntry._check"""
666
if self.text_sha1 != None or self.text_size != None or self.text_id != None:
733
if self.text_sha1 is not None or self.text_size is not None or self.text_id is not None:
667
734
raise BzrCheckError('symlink {%s} has text in revision {%s}'
668
735
% (self.file_id, rev_id))
669
if self.symlink_target == None:
736
if self.symlink_target is None:
670
737
raise BzrCheckError('symlink {%s} has no target in revision {%s}'
671
738
% (self.file_id, rev_id))
793
865
# root id. Rather than generating a random one here.
794
866
#if root_id is None:
795
867
# root_id = bzrlib.branch.gen_file_id('TREE_ROOT')
796
self.root = RootEntry(root_id)
868
if root_id is not None:
869
self._set_root(InventoryDirectory(root_id, '', None))
873
# FIXME: this isn't ever used, changing it to self.revision may break
874
# things. TODO make everything use self.revision_id
797
875
self.revision_id = revision_id
877
def _set_root(self, ie):
798
879
self._byid = {self.root.file_id: self.root}
802
882
# TODO: jam 20051218 Should copy also copy the revision_id?
803
other = Inventory(self.root.file_id)
883
entries = self.iter_entries()
884
other = Inventory(entries.next()[1].file_id)
804
885
# copy recursively so we know directories will be added before
805
886
# their children. There are more efficient ways than this...
806
for path, entry in self.iter_entries():
807
if entry == self.root:
887
for path, entry in entries():
809
888
other.add(entry.copy())
813
891
def __iter__(self):
814
892
return iter(self._byid)
817
894
def __len__(self):
818
895
"""Returns number of entries."""
819
896
return len(self._byid)
822
898
def iter_entries(self, from_dir=None):
823
899
"""Return (path, entry) pairs, in order by name."""
827
elif isinstance(from_dir, basestring):
828
from_dir = self._byid[from_dir]
830
kids = from_dir.children.items()
832
for name, ie in kids:
834
if ie.kind == 'directory':
835
for cn, cie in self.iter_entries(from_dir=ie.file_id):
836
yield pathjoin(name, cn), cie
904
elif isinstance(from_dir, basestring):
905
from_dir = self._byid[from_dir]
907
# unrolling the recursive called changed the time from
908
# 440ms/663ms (inline/total) to 116ms/116ms
909
children = from_dir.children.items()
911
children = collections.deque(children)
912
stack = [(u'', children)]
914
from_dir_relpath, children = stack[-1]
917
name, ie = children.popleft()
919
# we know that from_dir_relpath never ends in a slash
920
# and 'f' doesn't begin with one, we can do a string op, rather
921
# than the checks of pathjoin(), though this means that all paths
923
path = from_dir_relpath + '/' + name
927
if ie.kind != 'directory':
930
# But do this child first
931
new_children = ie.children.items()
933
new_children = collections.deque(new_children)
934
stack.append((path, new_children))
935
# Break out of inner loop, so that we start outer loop with child
938
# if we finished all children, pop it off the stack
941
def iter_entries_by_dir(self, from_dir=None):
942
"""Iterate over the entries in a directory first order.
944
This returns all entries for a directory before returning
945
the entries for children of a directory. This is not
946
lexicographically sorted order, and is a hybrid between
947
depth-first and breadth-first.
949
:return: This yields (path, entry) pairs
951
# TODO? Perhaps this should return the from_dir so that the root is
952
# yielded? or maybe an option?
957
elif isinstance(from_dir, basestring):
958
from_dir = self._byid[from_dir]
960
stack = [(u'', from_dir)]
962
cur_relpath, cur_dir = stack.pop()
965
for child_name, child_ie in sorted(cur_dir.children.iteritems()):
967
child_relpath = cur_relpath + child_name
969
yield child_relpath, child_ie
971
if child_ie.kind == 'directory':
972
child_dirs.append((child_relpath+'/', child_ie))
973
stack.extend(reversed(child_dirs))
839
975
def entries(self):
840
976
"""Return list of (path, ie) for all entries except the root.
871
1006
descend(self.root, u'')
876
1009
def __contains__(self, file_id):
877
1010
"""True if this entry contains a file with given id.
879
1012
>>> inv = Inventory()
880
1013
>>> inv.add(InventoryFile('123', 'foo.c', ROOT_ID))
881
InventoryFile('123', 'foo.c', parent_id='TREE_ROOT')
1014
InventoryFile('123', 'foo.c', parent_id='TREE_ROOT', sha1=None, len=None)
882
1015
>>> '123' in inv
884
1017
>>> '456' in inv
887
return file_id in self._byid
1020
return (file_id in self._byid)
890
1022
def __getitem__(self, file_id):
891
1023
"""Return the entry for given file_id.
893
1025
>>> inv = Inventory()
894
1026
>>> inv.add(InventoryFile('123123', 'hello.c', ROOT_ID))
895
InventoryFile('123123', 'hello.c', parent_id='TREE_ROOT')
1027
InventoryFile('123123', 'hello.c', parent_id='TREE_ROOT', sha1=None, len=None)
896
1028
>>> inv['123123'].name
900
1032
return self._byid[file_id]
901
1033
except KeyError:
903
1035
raise BzrError("can't look up file_id None")
905
1037
raise BzrError("file_id {%s} not in inventory" % file_id)
908
1039
def get_file_kind(self, file_id):
909
1040
return self._byid[file_id].kind
911
1042
def get_child(self, parent_id, filename):
912
1043
return self[parent_id].children.get(filename)
915
1045
def add(self, entry):
916
1046
"""Add entry to inventory.
939
1074
parent.children[entry.name] = entry
943
def add_path(self, relpath, kind, file_id=None):
1077
def add_path(self, relpath, kind, file_id=None, parent_id=None):
944
1078
"""Add entry from a path.
946
1080
The immediate parent must already be versioned.
948
1082
Returns the new entry object."""
949
from bzrlib.workingtree import gen_file_id
951
parts = bzrlib.osutils.splitpath(relpath)
954
file_id = gen_file_id(relpath)
1084
parts = osutils.splitpath(relpath)
956
1086
if len(parts) == 0:
957
self.root = RootEntry(file_id)
1088
file_id = bzrlib.workingtree.gen_root_id()
1089
self.root = InventoryDirectory(file_id, '', None)
958
1090
self._byid = {self.root.file_id: self.root}
961
1093
parent_path = parts[:-1]
962
1094
parent_id = self.path2id(parent_path)
963
if parent_id == None:
1095
if parent_id is None:
964
1096
raise NotVersionedError(path=parent_path)
965
if kind == 'directory':
966
ie = InventoryDirectory(file_id, parts[-1], parent_id)
968
ie = InventoryFile(file_id, parts[-1], parent_id)
969
elif kind == 'symlink':
970
ie = InventoryLink(file_id, parts[-1], parent_id)
972
raise BzrError("unknown kind %r" % kind)
1097
ie = make_entry(kind, parts[-1], parent_id, file_id)
973
1098
return self.add(ie)
976
1100
def __delitem__(self, file_id):
977
1101
"""Remove entry by id.
979
1103
>>> inv = Inventory()
980
1104
>>> inv.add(InventoryFile('123', 'foo.c', ROOT_ID))
981
InventoryFile('123', 'foo.c', parent_id='TREE_ROOT')
1105
InventoryFile('123', 'foo.c', parent_id='TREE_ROOT', sha1=None, len=None)
982
1106
>>> '123' in inv
984
1108
>>> del inv['123']
1005
1128
>>> i1.add(InventoryFile('123', 'foo', ROOT_ID))
1006
InventoryFile('123', 'foo', parent_id='TREE_ROOT')
1129
InventoryFile('123', 'foo', parent_id='TREE_ROOT', sha1=None, len=None)
1009
1132
>>> i2.add(InventoryFile('123', 'foo', ROOT_ID))
1010
InventoryFile('123', 'foo', parent_id='TREE_ROOT')
1133
InventoryFile('123', 'foo', parent_id='TREE_ROOT', sha1=None, len=None)
1014
1137
if not isinstance(other, Inventory):
1015
1138
return NotImplemented
1017
if len(self._byid) != len(other._byid):
1018
# shortcut: obviously not the same
1021
1140
return self._byid == other._byid
1024
1142
def __ne__(self, other):
1025
1143
return not self.__eq__(other)
1028
1145
def __hash__(self):
1029
1146
raise ValueError('not hashable')
1031
1148
def _iter_file_id_parents(self, file_id):
1032
1149
"""Yield the parents of file_id up to the root."""
1033
while file_id != None:
1150
while file_id is not None:
1035
1152
ie = self._byid[file_id]
1036
1153
except KeyError:
1095
1212
return parent.file_id
1098
1214
def has_filename(self, names):
1099
1215
return bool(self.path2id(names))
1102
1217
def has_id(self, file_id):
1103
return self._byid.has_key(file_id)
1218
return (file_id in self._byid)
1220
def remove_recursive_id(self, file_id):
1221
"""Remove file_id, and children, from the inventory.
1223
:param file_id: A file_id to remove.
1225
to_find_delete = [self._byid[file_id]]
1227
while to_find_delete:
1228
ie = to_find_delete.pop()
1229
to_delete.append(ie.file_id)
1230
if ie.kind == 'directory':
1231
to_find_delete.extend(ie.children.values())
1232
for file_id in reversed(to_delete):
1234
del self._byid[file_id]
1235
if ie.parent_id is not None:
1236
del self[ie.parent_id].children[ie.name]
1106
1238
def rename(self, file_id, new_parent_id, new_name):
1107
1239
"""Move a file within the inventory.
1133
1265
file_ie.parent_id = new_parent_id
1268
def make_entry(kind, name, parent_id, file_id=None):
1269
"""Create an inventory entry.
1271
:param kind: the type of inventory entry to create.
1272
:param name: the basename of the entry.
1273
:param parent_id: the parent_id of the entry.
1274
:param file_id: the file_id to use. if None, one will be created.
1277
file_id = bzrlib.workingtree.gen_file_id(name)
1279
norm_name, can_access = osutils.normalized_filename(name)
1280
if norm_name != name:
1284
# TODO: jam 20060701 This would probably be more useful
1285
# if the error was raised with the full path
1286
raise errors.InvalidNormalization(name)
1288
if kind == 'directory':
1289
return InventoryDirectory(file_id, name, parent_id)
1290
elif kind == 'file':
1291
return InventoryFile(file_id, name, parent_id)
1292
elif kind == 'symlink':
1293
return InventoryLink(file_id, name, parent_id)
1295
raise BzrError("unknown kind %r" % kind)
1138
1298
_NAME_RE = None
1140
1300
def is_valid_name(name):
1141
1301
global _NAME_RE
1142
if _NAME_RE == None:
1302
if _NAME_RE is None:
1143
1303
_NAME_RE = re.compile(r'^[^/\\]+$')
1145
1305
return bool(_NAME_RE.match(name))