15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
# TODO: Maybe also keep the full path of the entry, and the children?
19
# But those depend on its position within a particular inventory, and
20
# it would be nice not to need to hold the backpointer here.
22
# TODO: Perhaps split InventoryEntry into subclasses for files,
23
# directories, etc etc.
18
26
# This should really be an id randomly assigned when the tree is
19
27
# created, but it's not for now.
20
28
ROOT_ID = "TREE_ROOT"
23
import sys, os.path, types, re
26
38
from bzrlib.errors import BzrError, BzrCheckError
28
from bzrlib.osutils import uuid, quotefn, splitpath, joinpath, appendpath
40
from bzrlib.osutils import (pumpfile, quotefn, splitpath, joinpath,
41
appendpath, sha_strings)
29
42
from bzrlib.trace import mutter
30
43
from bzrlib.errors import NotVersionedError
33
46
class InventoryEntry(object):
34
47
"""Description of a versioned file.
36
49
An InventoryEntry has the following fields, which are also
37
50
present in the XML inventory-entry element:
40
* *name*: (only the basename within the directory, must not
42
* *kind*: "directory" or "file"
43
* *directory_id*: (if absent/null means the branch root directory)
44
* *text_sha1*: only for files
45
* *text_size*: in bytes, only for files
46
* *text_id*: identifier for the text version, only for files
48
InventoryEntries can also exist inside a WorkingTree
49
inventory, in which case they are not yet bound to a
50
particular revision of the file. In that case the text_sha1,
51
text_size and text_id are absent.
55
(within the parent directory)
58
'directory' or 'file' or 'symlink'
61
file_id of the parent directory, or ROOT_ID
64
the revision_id in which this variation of this file was
68
Indicates that this file should be executable on systems
72
sha-1 of the text of the file
75
size in bytes of the text of the file
77
(reading a version 4 tree created a text_id field.)
54
79
>>> i = Inventory()
57
82
>>> i.add(InventoryEntry('123', 'src', 'directory', ROOT_ID))
83
InventoryEntry('123', 'src', kind='directory', parent_id='TREE_ROOT')
58
84
>>> i.add(InventoryEntry('2323', 'hello.c', 'file', parent_id='123'))
85
InventoryEntry('2323', 'hello.c', kind='file', parent_id='123')
59
86
>>> for j in i.iter_entries():
67
94
BzrError: inventory already contains entry with id {2323}
68
95
>>> i.add(InventoryEntry('2324', 'bye.c', 'file', '123'))
96
InventoryEntry('2324', 'bye.c', kind='file', parent_id='123')
69
97
>>> i.add(InventoryEntry('2325', 'wibble', 'directory', '123'))
98
InventoryEntry('2325', 'wibble', kind='directory', parent_id='123')
70
99
>>> i.path2id('src/wibble')
74
103
>>> i.add(InventoryEntry('2326', 'wibble.c', 'file', '2325'))
104
InventoryEntry('2326', 'wibble.c', kind='file', parent_id='2325')
76
106
InventoryEntry('2326', 'wibble.c', kind='file', parent_id='2325')
77
>>> for j in i.iter_entries():
79
... assert i.path2id(j[0])
107
>>> for path, entry in i.iter_entries():
108
... print path.replace('\\\\', '/') # for win32 os.sep
109
... assert i.path2id(path)
85
115
src/wibble/wibble.c
116
>>> i.id2path('2326').replace('\\\\', '/')
87
117
'src/wibble/wibble.c'
89
TODO: Maybe also keep the full path of the entry, and the children?
90
But those depend on its position within a particular inventory, and
91
it would be nice not to need to hold the backpointer here.
94
# TODO: split InventoryEntry into subclasses for files,
95
# directories, etc etc.
97
120
__slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
98
'text_id', 'parent_id', 'children', ]
121
'text_id', 'parent_id', 'children', 'executable',
122
'revision', 'symlink_target']
124
def _add_text_to_weave(self, new_lines, parents, weave_store):
125
weave_store.add_text(self.file_id, self.revision, new_lines, parents)
127
def detect_changes(self, old_entry):
128
"""Return a (text_modified, meta_modified) from this to old_entry.
130
_read_tree_state must have been called on self and old_entry prior to
131
calling detect_changes.
133
if self.kind == 'file':
134
assert self.text_sha1 != None
135
assert old_entry.text_sha1 != None
136
text_modified = (self.text_sha1 != old_entry.text_sha1)
137
meta_modified = (self.executable != old_entry.executable)
138
elif self.kind == 'symlink':
139
# FIXME: which _modified field should we use ? RBC 20051003
140
text_modified = (self.symlink_target != old_entry.symlink_target)
142
mutter(" symlink target changed")
143
meta_modified = False
145
text_modified = False
146
meta_modified = False
147
return text_modified, meta_modified
149
def diff(self, text_diff, from_label, tree, to_label, to_entry, to_tree,
150
output_to, reverse=False):
151
"""Perform a diff from this to to_entry.
153
text_diff will be used for textual difference calculation.
155
self._read_tree_state(tree.id2path(self.file_id), tree)
157
# cannot diff from one kind to another - you must do a removal
158
# and an addif they do not match.
159
assert self.kind == to_entry.kind
160
to_entry._read_tree_state(to_tree.id2path(to_entry.file_id),
162
if self.kind == 'file':
163
from_text = tree.get_file(self.file_id).readlines()
165
to_text = to_tree.get_file(to_entry.file_id).readlines()
169
text_diff(from_label, from_text,
170
to_label, to_text, output_to)
172
text_diff(to_label, to_text,
173
from_label, from_text, output_to)
174
elif self.kind == 'symlink':
175
from_text = self.symlink_target
176
if to_entry is not None:
177
to_text = to_entry.symlink_target
182
print >>output_to, '=== target changed %r => %r' % (from_text, to_text)
185
print >>output_to, '=== target was %r' % self.symlink_target
187
print >>output_to, '=== target is %r' % self.symlink_target
189
def get_tar_item(self, root, dp, now, tree):
190
item = tarfile.TarInfo(os.path.join(root, dp))
191
# TODO: would be cool to actually set it to the timestamp of the
192
# revision it was last changed
194
if self.kind == 'directory':
195
item.type = tarfile.DIRTYPE
200
elif self.kind == 'file':
201
item.type = tarfile.REGTYPE
202
fileobj = tree.get_file(self.file_id)
203
item.size = self.text_size
204
if tree.is_executable(self.file_id):
209
raise BzrError("don't know how to export {%s} of kind %r" %
210
(self.file_id, self.kind))
214
"""Return true if the object this entry represents has textual data.
216
Note that textual data includes binary content.
218
if self.kind =='file':
100
223
def __init__(self, file_id, name, kind, parent_id, text_id=None):
101
224
"""Create an InventoryEntry
112
235
Traceback (most recent call last):
113
236
BzrCheckError: InventoryEntry name 'src/hello.c' is invalid
238
assert isinstance(name, basestring), name
115
239
if '/' in name or '\\' in name:
116
240
raise BzrCheckError('InventoryEntry name %r is invalid' % name)
242
self.executable = False
118
244
self.text_sha1 = None
119
245
self.text_size = None
121
246
self.file_id = file_id
124
249
self.text_id = text_id
125
250
self.parent_id = parent_id
251
self.symlink_target = None
126
252
if kind == 'directory':
127
253
self.children = {}
128
254
elif kind == 'file':
256
elif kind == 'symlink':
131
259
raise BzrError("unhandled entry kind %r" % kind)
261
def kind_character(self):
262
"""Return a short kind indicator useful for appending to names."""
263
if self.kind == 'directory':
265
if self.kind == 'file':
267
if self.kind == 'symlink':
269
raise RuntimeError('unreachable code')
271
known_kinds = ('file', 'directory', 'symlink', 'root_directory')
273
def put_on_disk(self, dest, dp, tree):
274
"""Create a representation of self on disk in the prefix dest."""
275
fullpath = appendpath(dest, dp)
276
if self.kind == 'directory':
278
elif self.kind == 'file':
279
pumpfile(tree.get_file(self.file_id), file(fullpath, 'wb'))
280
if tree.is_executable(self.file_id):
281
os.chmod(fullpath, 0755)
282
elif self.kind == 'symlink':
284
os.symlink(self.symlink_target, fullpath)
286
raise BzrError("Failed to create symlink %r -> %r, error: %s" % (fullpath, self.symlink_target, e))
288
raise BzrError("don't know how to export {%s} of kind %r" % (self.file_id, self.kind))
289
mutter(" export {%s} kind %s to %s" % (self.file_id, self.kind, fullpath))
135
291
def sorted_children(self):
136
292
l = self.children.items()
297
def versionable_kind(kind):
298
return kind in ('file', 'directory', 'symlink')
300
def check(self, checker, rev_id, inv, tree):
301
if self.parent_id != None:
302
if not inv.has_id(self.parent_id):
303
raise BzrCheckError('missing parent {%s} in inventory for revision {%s}'
304
% (self.parent_id, rev_id))
305
if self.kind == 'file':
306
revision = self.revision
307
t = (self.file_id, revision)
308
if t in checker.checked_texts:
309
prev_sha = checker.checked_texts[t]
310
if prev_sha != self.text_sha1:
311
raise BzrCheckError('mismatched sha1 on {%s} in {%s}' %
312
(self.file_id, rev_id))
314
checker.repeated_text_cnt += 1
316
mutter('check version {%s} of {%s}', rev_id, self.file_id)
317
file_lines = tree.get_file_lines(self.file_id)
318
checker.checked_text_cnt += 1
319
if self.text_size != sum(map(len, file_lines)):
320
raise BzrCheckError('text {%s} wrong size' % self.text_id)
321
if self.text_sha1 != sha_strings(file_lines):
322
raise BzrCheckError('text {%s} wrong sha1' % self.text_id)
323
checker.checked_texts[t] = self.text_sha1
324
elif self.kind == 'directory':
325
if self.text_sha1 != None or self.text_size != None or self.text_id != None:
326
raise BzrCheckError('directory {%s} has text in revision {%s}'
327
% (self.file_id, rev_id))
328
elif self.kind == 'root_directory':
330
elif self.kind == 'symlink':
331
if self.text_sha1 != None or self.text_size != None or self.text_id != None:
332
raise BzrCheckError('symlink {%s} has text in revision {%s}'
333
% (self.file_id, rev_id))
334
if self.symlink_target == None:
335
raise BzrCheckError('symlink {%s} has no target in revision {%s}'
336
% (self.file_id, rev_id))
338
raise BzrCheckError('unknown entry kind %r in revision {%s}' %
142
343
other = InventoryEntry(self.file_id, self.name, self.kind,
143
self.parent_id, text_id=self.text_id)
345
other.executable = self.executable
346
other.text_id = self.text_id
144
347
other.text_sha1 = self.text_sha1
145
348
other.text_size = self.text_size
349
other.symlink_target = self.symlink_target
350
other.revision = self.revision
146
351
# note that children are *not* copied; they're pulled across when
147
352
# others are added
355
def _get_snapshot_change(self, previous_entries):
356
if len(previous_entries) > 1:
358
elif len(previous_entries) == 0:
361
return 'modified/renamed/reparented'
151
363
def __repr__(self):
152
364
return ("%s(%r, %r, kind=%r, parent_id=%r)"
160
def to_element(self):
161
"""Convert to XML element"""
162
from bzrlib.xml import Element
166
e.set('name', self.name)
167
e.set('file_id', self.file_id)
168
e.set('kind', self.kind)
170
if self.text_size != None:
171
e.set('text_size', '%d' % self.text_size)
173
for f in ['text_id', 'text_sha1']:
178
# to be conservative, we don't externalize the root pointers
179
# for now, leaving them as null in the xml form. in a future
180
# version it will be implied by nested elements.
181
if self.parent_id != ROOT_ID:
182
assert isinstance(self.parent_id, basestring)
183
e.set('parent_id', self.parent_id)
190
def from_element(cls, elt):
191
assert elt.tag == 'entry'
193
## original format inventories don't have a parent_id for
194
## nodes in the root directory, but it's cleaner to use one
196
parent_id = elt.get('parent_id')
197
if parent_id == None:
200
self = cls(elt.get('file_id'), elt.get('name'), elt.get('kind'), parent_id)
201
self.text_id = elt.get('text_id')
202
self.text_sha1 = elt.get('text_sha1')
204
## mutter("read inventoryentry: %r" % (elt.attrib))
206
v = elt.get('text_size')
207
self.text_size = v and int(v)
212
from_element = classmethod(from_element)
371
def snapshot(self, revision, path, previous_entries, work_tree,
373
"""Make a snapshot of this entry.
375
This means that all its fields are populated, that it has its
376
text stored in the text store or weave.
378
mutter('new parents of %s are %r', path, previous_entries)
379
self._read_tree_state(path, work_tree)
380
if len(previous_entries) == 1:
381
# cannot be unchanged unless there is only one parent file rev.
382
parent_ie = previous_entries.values()[0]
383
if self._unchanged(path, parent_ie, work_tree):
384
mutter("found unchanged entry")
385
self.revision = parent_ie.revision
387
mutter('new revision for {%s}', self.file_id)
388
self.revision = revision
389
change = self._get_snapshot_change(previous_entries)
390
if self.kind != 'file':
392
self._snapshot_text(previous_entries, work_tree, weave_store)
395
def _snapshot_text(self, file_parents, work_tree, weave_store):
396
mutter('storing file {%s} in revision {%s}',
397
self.file_id, self.revision)
398
# special case to avoid diffing on renames or
400
if (len(file_parents) == 1
401
and self.text_sha1 == file_parents.values()[0].text_sha1
402
and self.text_size == file_parents.values()[0].text_size):
403
previous_ie = file_parents.values()[0]
404
weave_store.add_identical_text(
405
self.file_id, previous_ie.revision,
406
self.revision, file_parents)
408
new_lines = work_tree.get_file(self.file_id).readlines()
409
self._add_text_to_weave(new_lines, file_parents, weave_store)
410
self.text_sha1 = sha_strings(new_lines)
411
self.text_size = sum(map(len, new_lines))
214
413
def __eq__(self, other):
215
414
if not isinstance(other, InventoryEntry):
216
415
return NotImplemented
218
return (self.file_id == other.file_id) \
219
and (self.name == other.name) \
220
and (self.text_sha1 == other.text_sha1) \
221
and (self.text_size == other.text_size) \
222
and (self.text_id == other.text_id) \
223
and (self.parent_id == other.parent_id) \
224
and (self.kind == other.kind)
417
return ((self.file_id == other.file_id)
418
and (self.name == other.name)
419
and (other.symlink_target == self.symlink_target)
420
and (self.text_sha1 == other.text_sha1)
421
and (self.text_size == other.text_size)
422
and (self.text_id == other.text_id)
423
and (self.parent_id == other.parent_id)
424
and (self.kind == other.kind)
425
and (self.revision == other.revision)
426
and (self.executable == other.executable)
227
429
def __ne__(self, other):
228
430
return not (self == other)
476
726
del self[ie.parent_id].children[ie.name]
479
def to_element(self):
480
"""Convert to XML Element"""
481
from bzrlib.xml import Element
483
e = Element('inventory')
485
if self.root.file_id not in (None, ROOT_ID):
486
e.set('file_id', self.root.file_id)
487
for path, ie in self.iter_entries():
488
e.append(ie.to_element())
492
def from_element(cls, elt):
493
"""Construct from XML Element
495
>>> inv = Inventory()
496
>>> inv.add(InventoryEntry('foo.c-123981239', 'foo.c', 'file', ROOT_ID))
497
>>> elt = inv.to_element()
498
>>> inv2 = Inventory.from_element(elt)
502
# XXXX: doctest doesn't run this properly under python2.3
503
assert elt.tag == 'inventory'
504
root_id = elt.get('file_id') or ROOT_ID
507
ie = InventoryEntry.from_element(e)
508
if ie.parent_id == ROOT_ID:
509
ie.parent_id = root_id
513
from_element = classmethod(from_element)
516
729
def __eq__(self, other):
517
730
"""Compare two sets by comparing their contents.