78
90
>>> i.add(InventoryDirectory('123', 'src', ROOT_ID))
79
InventoryDirectory('123', 'src', parent_id='TREE_ROOT')
91
InventoryDirectory('123', 'src', parent_id='TREE_ROOT', revision=None)
80
92
>>> 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')}
93
InventoryFile('2323', 'hello.c', parent_id='123', sha1=None, len=None)
94
>>> shouldbe = {0: '', 1: 'src', 2: 'src/hello.c'}
83
95
>>> for ix, j in enumerate(i.iter_entries()):
84
96
... 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'))
88
>>> i.add(InventoryFile('2323', 'bye.c', '123'))
89
Traceback (most recent call last):
91
BzrError: inventory already contains entry with id {2323}
98
(True, InventoryDirectory('TREE_ROOT', u'', parent_id=None, revision=None))
99
(True, InventoryDirectory('123', 'src', parent_id='TREE_ROOT', revision=None))
100
(True, InventoryFile('2323', 'hello.c', parent_id='123', sha1=None, len=None))
92
101
>>> i.add(InventoryFile('2324', 'bye.c', '123'))
93
InventoryFile('2324', 'bye.c', parent_id='123')
102
InventoryFile('2324', 'bye.c', parent_id='123', sha1=None, len=None)
94
103
>>> i.add(InventoryDirectory('2325', 'wibble', '123'))
95
InventoryDirectory('2325', 'wibble', parent_id='123')
104
InventoryDirectory('2325', 'wibble', parent_id='123', revision=None)
96
105
>>> i.path2id('src/wibble')
100
109
>>> i.add(InventoryFile('2326', 'wibble.c', '2325'))
101
InventoryFile('2326', 'wibble.c', parent_id='2325')
110
InventoryFile('2326', 'wibble.c', parent_id='2325', sha1=None, len=None)
103
InventoryFile('2326', 'wibble.c', parent_id='2325')
112
InventoryFile('2326', 'wibble.c', parent_id='2325', sha1=None, len=None)
104
113
>>> for path, entry in i.iter_entries():
106
115
... assert i.path2id(path)
160
162
def _diff(self, text_diff, from_label, tree, to_label, to_entry, to_tree,
161
163
output_to, reverse=False):
162
164
"""Perform a diff between two entries of the same kind."""
164
def find_previous_heads(self, previous_inventories,
165
versioned_file_store,
168
"""Return the revisions and entries that directly preceed this.
170
Returned as a map from revision to inventory entry.
172
This is a map containing the file revisions in all parents
173
for which the file exists, and its revision is not a parent of
174
any other. If the file is new, the set will be empty.
176
:param versioned_file_store: A store where ancestry data on this
177
file id can be queried.
178
:param transaction: The transaction that queries to the versioned
179
file store should be completed under.
180
:param entry_vf: The entry versioned file, if its already available.
166
def parent_candidates(self, previous_inventories):
167
"""Find possible per-file graph parents.
169
This is currently defined by:
170
- Select the last changed revision in the parent inventory.
171
- Do deal with a short lived bug in bzr 0.8's development two entries
172
that have the same last changed but different 'x' bit settings are
182
def get_ancestors(weave, entry):
183
return set(weave.get_ancestry(entry.revision))
184
175
# revision:ie mapping for each ie found in previous_inventories.
186
# revision:ie mapping with one revision for each head.
188
# revision: ancestor list for each head
190
177
# identify candidate head revision ids.
191
178
for inv in previous_inventories:
192
179
if self.file_id in inv:
209
196
# add this revision as a candidate.
210
197
candidates[ie.revision] = ie
200
@deprecated_method(zero_ninetyone)
201
def find_previous_heads(self, previous_inventories,
202
versioned_file_store,
205
"""Return the revisions and entries that directly precede this.
207
Returned as a map from revision to inventory entry.
209
This is a map containing the file revisions in all parents
210
for which the file exists, and its revision is not a parent of
211
any other. If the file is new, the set will be empty.
213
:param versioned_file_store: A store where ancestry data on this
214
file id can be queried.
215
:param transaction: The transaction that queries to the versioned
216
file store should be completed under.
217
:param entry_vf: The entry versioned file, if its already available.
219
candidates = self.parent_candidates(previous_inventories)
221
# revision:ie mapping with one revision for each head.
212
223
# common case optimisation
213
224
if len(candidates) == 1:
214
225
# if there is only one candidate revision found
215
# then we can opening the versioned file to access ancestry:
226
# then we can avoid opening the versioned file to access ancestry:
216
227
# there cannot be any ancestors to eliminate when there is
217
228
# only one revision available.
218
heads[ie.revision] = ie
231
# --- what follows is now encapsulated in repository.get_graph.heads(),
232
# but that is not accessible from here as we have no repository
233
# pointer. Note that the repository.get_graph.heads() call can return
234
# different results *at the moment* because of the kind-changing check
235
# we have in parent_candidates().
221
237
# eliminate ancestors amongst the available candidates:
222
238
# heads are those that are not an ancestor of any other candidate
223
239
# - this provides convergence at a per-file level.
240
def get_ancestors(weave, entry):
241
return set(weave.get_ancestry(entry.revision, topo_sorted=False))
242
# revision: ancestor list for each head
224
244
for ie in candidates.values():
225
245
# may be an ancestor of a known head:
226
246
already_present = 0 != len(
285
305
assert isinstance(name, basestring), name
286
306
if '/' in name or '\\' in name:
287
raise InvalidEntryName(name=name)
307
raise errors.InvalidEntryName(name=name)
288
308
self.executable = False
289
309
self.revision = None
290
310
self.text_sha1 = None
291
311
self.text_size = None
292
312
self.file_id = file_id
313
assert isinstance(file_id, (str, None.__class__)), \
314
'bad type %r for %r' % (type(file_id), file_id)
294
316
self.text_id = text_id
295
317
self.parent_id = parent_id
296
318
self.symlink_target = None
319
self.reference_revision = None
298
321
def kind_character(self):
299
322
"""Return a short kind indicator useful for appending to names."""
300
323
raise BzrError('unknown kind %r' % self.kind)
302
known_kinds = ('file', 'directory', 'symlink', 'root_directory')
325
known_kinds = ('file', 'directory', 'symlink')
304
327
def _put_in_tar(self, item, tree):
305
328
"""populate item for stashing in a tar, and return the content stream.
315
338
This is a template method - implement _put_on_disk in subclasses.
317
fullpath = pathjoin(dest, dp)
340
fullpath = osutils.pathjoin(dest, dp)
318
341
self._put_on_disk(fullpath, tree)
319
mutter(" export {%s} kind %s to %s", self.file_id,
342
# mutter(" export {%s} kind %s to %s", self.file_id,
343
# self.kind, fullpath)
322
345
def _put_on_disk(self, fullpath, tree):
323
346
"""Put this entry onto disk at fullpath, from tree tree."""
324
347
raise BzrError("don't know how to export {%s} of kind %r" % (self.file_id, self.kind))
326
349
def sorted_children(self):
327
l = self.children.items()
350
return sorted(self.children.items())
332
353
def versionable_kind(kind):
333
return kind in ('file', 'directory', 'symlink')
354
return (kind in ('file', 'directory', 'symlink', 'tree-reference'))
335
356
def check(self, checker, rev_id, inv, tree):
336
357
"""Check this inventory entry is intact.
402
425
return 'unchanged'
404
427
def __repr__(self):
405
return ("%s(%r, %r, parent_id=%r)"
428
return ("%s(%r, %r, parent_id=%r, revision=%r)"
406
429
% (self.__class__.__name__,
411
435
def snapshot(self, revision, path, previous_entries,
412
work_tree, weave_store, transaction):
436
work_tree, commit_builder):
413
437
"""Make a snapshot of this entry which may or may not have changed.
415
439
This means that all its fields are populated, that it has its
416
440
text stored in the text store or weave.
442
:return: True if anything was recorded
418
mutter('new parents of %s are %r', path, previous_entries)
444
# cannot be unchanged unless there is only one parent file rev.
419
445
self._read_tree_state(path, work_tree)
420
446
if len(previous_entries) == 1:
421
# cannot be unchanged unless there is only one parent file rev.
422
447
parent_ie = previous_entries.values()[0]
423
448
if self._unchanged(parent_ie):
424
mutter("found unchanged entry")
425
449
self.revision = parent_ie.revision
427
return self._snapshot_into_revision(revision, previous_entries,
428
work_tree, weave_store, transaction)
430
def _snapshot_into_revision(self, revision, previous_entries, work_tree,
431
weave_store, transaction):
432
"""Record this revision unconditionally into a store.
434
The entry's last-changed revision property (`revision`) is updated to
435
that of the new revision.
437
:param revision: id of the new revision that is being recorded.
439
:returns: String description of the commit (e.g. "merged", "modified"), etc.
441
mutter('new revision {%s} for {%s}', revision, self.file_id)
442
451
self.revision = revision
443
self._snapshot_text(previous_entries, work_tree, weave_store,
452
return self._snapshot_text(previous_entries, work_tree, commit_builder)
446
def _snapshot_text(self, file_parents, work_tree, weave_store, transaction):
454
def _snapshot_text(self, file_parents, work_tree, commit_builder):
447
455
"""Record the 'text' of this entry, whatever form that takes.
449
This default implementation simply adds an empty text.
457
:return: True if anything was recorded
451
mutter('storing file {%s} in revision {%s}',
452
self.file_id, self.revision)
453
self._add_text_to_weave([], file_parents.keys(), weave_store, transaction)
459
raise NotImplementedError(self._snapshot_text)
455
461
def __eq__(self, other):
456
462
if not isinstance(other, InventoryEntry):
506
515
class RootEntry(InventoryEntry):
517
__slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
518
'text_id', 'parent_id', 'children', 'executable',
519
'revision', 'symlink_target', 'reference_revision']
508
521
def _check(self, checker, rev_id, tree):
509
522
"""See InventoryEntry._check"""
511
524
def __init__(self, file_id):
512
525
self.file_id = file_id
513
526
self.children = {}
514
self.kind = 'root_directory'
527
self.kind = 'directory'
515
528
self.parent_id = None
531
symbol_versioning.warn('RootEntry is deprecated as of bzr 0.10.'
532
' Please use InventoryDirectory instead.',
533
DeprecationWarning, stacklevel=2)
518
535
def __eq__(self, other):
519
536
if not isinstance(other, RootEntry):
526
543
class InventoryDirectory(InventoryEntry):
527
544
"""A directory in an inventory."""
546
__slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
547
'text_id', 'parent_id', 'children', 'executable',
548
'revision', 'symlink_target', 'reference_revision']
529
550
def _check(self, checker, rev_id, tree):
530
551
"""See InventoryEntry._check"""
531
if self.text_sha1 != None or self.text_size != None or self.text_id != None:
552
if self.text_sha1 is not None or self.text_size is not None or self.text_id is not None:
532
553
raise BzrCheckError('directory {%s} has text in revision {%s}'
533
554
% (self.file_id, rev_id))
561
582
"""See InventoryEntry._put_on_disk."""
562
583
os.mkdir(fullpath)
585
def _snapshot_text(self, file_parents, work_tree, commit_builder):
586
"""See InventoryEntry._snapshot_text."""
587
commit_builder.modified_directory(self.file_id, file_parents)
565
591
class InventoryFile(InventoryEntry):
566
592
"""A file in an inventory."""
594
__slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
595
'text_id', 'parent_id', 'children', 'executable',
596
'revision', 'symlink_target', 'reference_revision']
568
598
def _check(self, checker, tree_revision_id, tree):
569
599
"""See InventoryEntry._check"""
570
600
t = (self.file_id, self.revision)
663
694
def _put_on_disk(self, fullpath, tree):
664
695
"""See InventoryEntry._put_on_disk."""
665
pumpfile(tree.get_file(self.file_id), file(fullpath, 'wb'))
696
osutils.pumpfile(tree.get_file(self.file_id), file(fullpath, 'wb'))
666
697
if tree.is_executable(self.file_id):
667
698
os.chmod(fullpath, 0755)
669
700
def _read_tree_state(self, path, work_tree):
670
701
"""See InventoryEntry._read_tree_state."""
671
self.text_sha1 = work_tree.get_file_sha1(self.file_id)
672
self.executable = work_tree.is_executable(self.file_id)
702
self.text_sha1 = work_tree.get_file_sha1(self.file_id, path=path)
703
# FIXME: 20050930 probe for the text size when getting sha1
704
# in _read_tree_state
705
self.executable = work_tree.is_executable(self.file_id, path=path)
708
return ("%s(%r, %r, parent_id=%r, sha1=%r, len=%s)"
709
% (self.__class__.__name__,
674
716
def _forget_tree_state(self):
675
717
self.text_sha1 = None
676
self.executable = None
678
def _snapshot_text(self, file_parents, work_tree, versionedfile_store, transaction):
679
"""See InventoryEntry._snapshot_text."""
680
mutter('storing text of file {%s} in revision {%s} into %r',
681
self.file_id, self.revision, versionedfile_store)
682
# special case to avoid diffing on renames or
684
if (len(file_parents) == 1
685
and self.text_sha1 == file_parents.values()[0].text_sha1
686
and self.text_size == file_parents.values()[0].text_size):
687
previous_ie = file_parents.values()[0]
688
versionedfile = versionedfile_store.get_weave(self.file_id, transaction)
689
versionedfile.clone_text(self.revision, previous_ie.revision, file_parents.keys())
719
def snapshot(self, revision, path, previous_entries,
720
work_tree, commit_builder):
721
"""See InventoryEntry.snapshot."""
722
# Note: We use a custom implementation of this method for files
723
# because it's a performance critical part of commit.
725
# If this is the initial commit for this file, we know the sha is
726
# coming later so skip calculating it now (in _read_tree_state())
727
if len(previous_entries) == 0:
728
self.executable = work_tree.is_executable(self.file_id, path=path)
691
new_lines = work_tree.get_file(self.file_id).readlines()
692
self._add_text_to_weave(new_lines, file_parents.keys(), versionedfile_store,
694
self.text_sha1 = sha_strings(new_lines)
695
self.text_size = sum(map(len, new_lines))
730
self._read_tree_state(path, work_tree)
732
# If nothing is changed from the sole parent, there's nothing to do
733
if len(previous_entries) == 1:
734
parent_ie = previous_entries.values()[0]
735
if self._unchanged(parent_ie):
736
self.revision = parent_ie.revision
739
# Add the file to the repository
740
self.revision = revision
741
def get_content_byte_lines():
742
return work_tree.get_file(self.file_id, path).readlines()
743
self.text_sha1, self.text_size = commit_builder.modified_file_text(
744
self.file_id, previous_entries, get_content_byte_lines,
745
self.text_sha1, self.text_size)
698
748
def _unchanged(self, previous_ie):
699
749
"""See InventoryEntry._unchanged."""
712
762
class InventoryLink(InventoryEntry):
713
763
"""A file in an inventory."""
715
__slots__ = ['symlink_target']
765
__slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
766
'text_id', 'parent_id', 'children', 'executable',
767
'revision', 'symlink_target', 'reference_revision']
717
769
def _check(self, checker, rev_id, tree):
718
770
"""See InventoryEntry._check"""
719
if self.text_sha1 != None or self.text_size != None or self.text_id != None:
771
if self.text_sha1 is not None or self.text_size is not None or self.text_id is not None:
720
772
raise BzrCheckError('symlink {%s} has text in revision {%s}'
721
773
% (self.file_id, rev_id))
722
if self.symlink_target == None:
774
if self.symlink_target is None:
723
775
raise BzrCheckError('symlink {%s} has no target in revision {%s}'
724
776
% (self.file_id, rev_id))
793
845
compatible = False
794
846
return compatible
848
def _snapshot_text(self, file_parents, work_tree, commit_builder):
849
"""See InventoryEntry._snapshot_text."""
850
commit_builder.modified_link(
851
self.file_id, file_parents, self.symlink_target)
855
class TreeReference(InventoryEntry):
857
kind = 'tree-reference'
859
def __init__(self, file_id, name, parent_id, revision=None,
860
reference_revision=None):
861
InventoryEntry.__init__(self, file_id, name, parent_id)
862
self.revision = revision
863
self.reference_revision = reference_revision
866
return TreeReference(self.file_id, self.name, self.parent_id,
867
self.revision, self.reference_revision)
869
def _snapshot_text(self, file_parents, work_tree, commit_builder):
870
commit_builder.modified_reference(self.file_id, file_parents)
873
def _read_tree_state(self, path, work_tree):
874
"""Populate fields in the inventory entry from the given tree.
876
self.reference_revision = work_tree.get_reference_revision(
879
def _forget_tree_state(self):
880
self.reference_revision = None
797
883
class Inventory(object):
798
884
"""Inventory of versioned files in a tree.
842
931
The inventory is created with a default root directory, with
845
# We are letting Branch.create() create a unique inventory
846
# root id. Rather than generating a random one here.
848
# root_id = bzrlib.branch.gen_file_id('TREE_ROOT')
849
self.root = RootEntry(root_id)
934
if root_id is not None:
935
assert root_id.__class__ == str
936
self._set_root(InventoryDirectory(root_id, u'', None))
850
940
self.revision_id = revision_id
942
def _set_root(self, ie):
851
944
self._byid = {self.root.file_id: self.root}
855
947
# TODO: jam 20051218 Should copy also copy the revision_id?
856
other = Inventory(self.root.file_id)
948
entries = self.iter_entries()
949
other = Inventory(entries.next()[1].file_id)
857
950
# copy recursively so we know directories will be added before
858
951
# their children. There are more efficient ways than this...
859
for path, entry in self.iter_entries():
860
if entry == self.root:
952
for path, entry in entries():
862
953
other.add(entry.copy())
866
956
def __iter__(self):
867
957
return iter(self._byid)
870
959
def __len__(self):
871
960
"""Returns number of entries."""
872
961
return len(self._byid)
875
963
def iter_entries(self, from_dir=None):
876
964
"""Return (path, entry) pairs, in order by name."""
880
elif isinstance(from_dir, basestring):
881
from_dir = self._byid[from_dir]
883
kids = from_dir.children.items()
885
for name, ie in kids:
887
if ie.kind == 'directory':
888
for cn, cie in self.iter_entries(from_dir=ie.file_id):
889
yield pathjoin(name, cn), cie
966
if self.root is None:
970
elif isinstance(from_dir, basestring):
971
from_dir = self._byid[from_dir]
973
# unrolling the recursive called changed the time from
974
# 440ms/663ms (inline/total) to 116ms/116ms
975
children = from_dir.children.items()
977
children = collections.deque(children)
978
stack = [(u'', children)]
980
from_dir_relpath, children = stack[-1]
983
name, ie = children.popleft()
985
# we know that from_dir_relpath never ends in a slash
986
# and 'f' doesn't begin with one, we can do a string op, rather
987
# than the checks of pathjoin(), though this means that all paths
989
path = from_dir_relpath + '/' + name
993
if ie.kind != 'directory':
996
# But do this child first
997
new_children = ie.children.items()
999
new_children = collections.deque(new_children)
1000
stack.append((path, new_children))
1001
# Break out of inner loop, so that we start outer loop with child
1004
# if we finished all children, pop it off the stack
1007
def iter_entries_by_dir(self, from_dir=None, specific_file_ids=None):
1008
"""Iterate over the entries in a directory first order.
1010
This returns all entries for a directory before returning
1011
the entries for children of a directory. This is not
1012
lexicographically sorted order, and is a hybrid between
1013
depth-first and breadth-first.
1015
:return: This yields (path, entry) pairs
1017
if specific_file_ids:
1018
safe = osutils.safe_file_id
1019
specific_file_ids = set(safe(fid) for fid in specific_file_ids)
1020
# TODO? Perhaps this should return the from_dir so that the root is
1021
# yielded? or maybe an option?
1022
if from_dir is None:
1023
if self.root is None:
1025
# Optimize a common case
1026
if specific_file_ids is not None and len(specific_file_ids) == 1:
1027
file_id = list(specific_file_ids)[0]
1029
yield self.id2path(file_id), self[file_id]
1031
from_dir = self.root
1032
if (specific_file_ids is None or
1033
self.root.file_id in specific_file_ids):
1034
yield u'', self.root
1035
elif isinstance(from_dir, basestring):
1036
from_dir = self._byid[from_dir]
1038
if specific_file_ids is not None:
1039
# TODO: jam 20070302 This could really be done as a loop rather
1040
# than a bunch of recursive calls.
1043
def add_ancestors(file_id):
1044
if file_id not in byid:
1046
parent_id = byid[file_id].parent_id
1047
if parent_id is None:
1049
if parent_id not in parents:
1050
parents.add(parent_id)
1051
add_ancestors(parent_id)
1052
for file_id in specific_file_ids:
1053
add_ancestors(file_id)
1057
stack = [(u'', from_dir)]
1059
cur_relpath, cur_dir = stack.pop()
1062
for child_name, child_ie in sorted(cur_dir.children.iteritems()):
1064
child_relpath = cur_relpath + child_name
1066
if (specific_file_ids is None or
1067
child_ie.file_id in specific_file_ids):
1068
yield child_relpath, child_ie
1070
if child_ie.kind == 'directory':
1071
if parents is None or child_ie.file_id in parents:
1072
child_dirs.append((child_relpath+'/', child_ie))
1073
stack.extend(reversed(child_dirs))
1075
def make_entry(self, kind, name, parent_id, file_id=None):
1076
"""Simple thunk to bzrlib.inventory.make_entry."""
1077
return make_entry(kind, name, parent_id, file_id)
892
1079
def entries(self):
893
1080
"""Return list of (path, ie) for all entries except the root.
921
1107
for name, child_ie in kids:
922
child_path = pathjoin(parent_path, name)
1108
child_path = osutils.pathjoin(parent_path, name)
923
1109
descend(child_ie, child_path)
924
1110
descend(self.root, u'')
929
1113
def __contains__(self, file_id):
930
1114
"""True if this entry contains a file with given id.
932
1116
>>> inv = Inventory()
933
1117
>>> inv.add(InventoryFile('123', 'foo.c', ROOT_ID))
934
InventoryFile('123', 'foo.c', parent_id='TREE_ROOT')
1118
InventoryFile('123', 'foo.c', parent_id='TREE_ROOT', sha1=None, len=None)
935
1119
>>> '123' in inv
937
1121
>>> '456' in inv
940
return file_id in self._byid
1124
file_id = osutils.safe_file_id(file_id)
1125
return (file_id in self._byid)
943
1127
def __getitem__(self, file_id):
944
1128
"""Return the entry for given file_id.
946
1130
>>> inv = Inventory()
947
1131
>>> inv.add(InventoryFile('123123', 'hello.c', ROOT_ID))
948
InventoryFile('123123', 'hello.c', parent_id='TREE_ROOT')
1132
InventoryFile('123123', 'hello.c', parent_id='TREE_ROOT', sha1=None, len=None)
949
1133
>>> inv['123123'].name
1136
file_id = osutils.safe_file_id(file_id)
953
1138
return self._byid[file_id]
954
1139
except KeyError:
956
raise BzrError("can't look up file_id None")
958
raise BzrError("file_id {%s} not in inventory" % file_id)
1140
# really we're passing an inventory, not a tree...
1141
raise errors.NoSuchId(self, file_id)
961
1143
def get_file_kind(self, file_id):
1144
file_id = osutils.safe_file_id(file_id)
962
1145
return self._byid[file_id].kind
964
1147
def get_child(self, parent_id, filename):
1148
parent_id = osutils.safe_file_id(parent_id)
965
1149
return self[parent_id].children.get(filename)
1151
def _add_child(self, entry):
1152
"""Add an entry to the inventory, without adding it to its parent"""
1153
if entry.file_id in self._byid:
1154
raise BzrError("inventory already contains entry with id {%s}" %
1156
self._byid[entry.file_id] = entry
1157
for child in getattr(entry, 'children', {}).itervalues():
1158
self._add_child(child)
968
1161
def add(self, entry):
969
1162
"""Add entry to inventory.
974
1167
Returns the new entry object.
976
1169
if entry.file_id in self._byid:
977
raise BzrError("inventory already contains entry with id {%s}" % entry.file_id)
979
if entry.parent_id == ROOT_ID or entry.parent_id is None:
980
entry.parent_id = self.root.file_id
983
parent = self._byid[entry.parent_id]
985
raise BzrError("parent_id {%s} not in inventory" % entry.parent_id)
987
if parent.children.has_key(entry.name):
988
raise BzrError("%s is already versioned" %
989
pathjoin(self.id2path(parent.file_id), entry.name))
991
self._byid[entry.file_id] = entry
992
parent.children[entry.name] = entry
1170
raise errors.DuplicateFileId(entry.file_id,
1171
self._byid[entry.file_id])
1173
if entry.parent_id is None:
1174
assert self.root is None and len(self._byid) == 0
1178
parent = self._byid[entry.parent_id]
1180
raise BzrError("parent_id {%s} not in inventory" %
1183
if entry.name in parent.children:
1184
raise BzrError("%s is already versioned" %
1185
osutils.pathjoin(self.id2path(parent.file_id),
1186
entry.name).encode('utf-8'))
1187
parent.children[entry.name] = entry
1188
return self._add_child(entry)
996
1190
def add_path(self, relpath, kind, file_id=None, parent_id=None):
997
1191
"""Add entry from a path.
1048
1244
>>> i1.add(InventoryFile('123', 'foo', ROOT_ID))
1049
InventoryFile('123', 'foo', parent_id='TREE_ROOT')
1245
InventoryFile('123', 'foo', parent_id='TREE_ROOT', sha1=None, len=None)
1052
1248
>>> i2.add(InventoryFile('123', 'foo', ROOT_ID))
1053
InventoryFile('123', 'foo', parent_id='TREE_ROOT')
1249
InventoryFile('123', 'foo', parent_id='TREE_ROOT', sha1=None, len=None)
1057
1253
if not isinstance(other, Inventory):
1058
1254
return NotImplemented
1060
if len(self._byid) != len(other._byid):
1061
# shortcut: obviously not the same
1064
1256
return self._byid == other._byid
1067
1258
def __ne__(self, other):
1068
1259
return not self.__eq__(other)
1071
1261
def __hash__(self):
1072
1262
raise ValueError('not hashable')
1074
1264
def _iter_file_id_parents(self, file_id):
1075
1265
"""Yield the parents of file_id up to the root."""
1076
while file_id != None:
1266
file_id = osutils.safe_file_id(file_id)
1267
while file_id is not None:
1078
1269
ie = self._byid[file_id]
1079
1270
except KeyError:
1080
raise BzrError("file_id {%s} not found in inventory" % file_id)
1271
raise errors.NoSuchId(tree=None, file_id=file_id)
1082
1273
file_id = ie.parent_id
1138
1336
return parent.file_id
1141
1338
def has_filename(self, names):
1142
1339
return bool(self.path2id(names))
1145
1341
def has_id(self, file_id):
1146
return self._byid.has_key(file_id)
1342
file_id = osutils.safe_file_id(file_id)
1343
return (file_id in self._byid)
1345
def remove_recursive_id(self, file_id):
1346
"""Remove file_id, and children, from the inventory.
1348
:param file_id: A file_id to remove.
1350
file_id = osutils.safe_file_id(file_id)
1351
to_find_delete = [self._byid[file_id]]
1353
while to_find_delete:
1354
ie = to_find_delete.pop()
1355
to_delete.append(ie.file_id)
1356
if ie.kind == 'directory':
1357
to_find_delete.extend(ie.children.values())
1358
for file_id in reversed(to_delete):
1360
del self._byid[file_id]
1361
if ie.parent_id is not None:
1362
del self[ie.parent_id].children[ie.name]
1149
1366
def rename(self, file_id, new_parent_id, new_name):
1150
1367
"""Move a file within the inventory.
1152
1369
This can change either the name, or the parent, or both.
1154
This does not move the working file."""
1371
This does not move the working file.
1373
file_id = osutils.safe_file_id(file_id)
1155
1374
if not is_valid_name(new_name):
1156
1375
raise BzrError("not an acceptable filename: %r" % new_name)
1185
1415
:param file_id: the file_id to use. if None, one will be created.
1187
1417
if file_id is None:
1188
file_id = bzrlib.workingtree.gen_file_id(name)
1189
if kind == 'directory':
1190
return InventoryDirectory(file_id, name, parent_id)
1191
elif kind == 'file':
1192
return InventoryFile(file_id, name, parent_id)
1193
elif kind == 'symlink':
1194
return InventoryLink(file_id, name, parent_id)
1418
file_id = generate_ids.gen_file_id(name)
1420
file_id = osutils.safe_file_id(file_id)
1422
#------- This has been copied to bzrlib.dirstate.DirState.add, please
1423
# keep them synchronised.
1424
# we dont import normalized_filename directly because we want to be
1425
# able to change the implementation at runtime for tests.
1426
norm_name, can_access = osutils.normalized_filename(name)
1427
if norm_name != name:
1431
# TODO: jam 20060701 This would probably be more useful
1432
# if the error was raised with the full path
1433
raise errors.InvalidNormalization(name)
1436
factory = entry_factory[kind]
1196
1438
raise BzrError("unknown kind %r" % kind)
1439
return factory(file_id, name, parent_id)
1200
1442
_NAME_RE = None
1202
1444
def is_valid_name(name):
1203
1445
global _NAME_RE
1204
if _NAME_RE == None:
1446
if _NAME_RE is None:
1205
1447
_NAME_RE = re.compile(r'^[^/\\]+$')
1207
1449
return bool(_NAME_RE.match(name))