~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/inventory.py

  • Committer: Robert Collins
  • Date: 2005-10-03 14:28:37 UTC
  • mto: (1393.1.30)
  • mto: This revision was merged to the branch mainline in revision 1400.
  • Revision ID: robertc@robertcollins.net-20051003142837-78bf906d4edcbd62
factor out inventory directory logic into 'InventoryDirectory' class

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# (C) 2005 Canonical Ltd
2
 
#
 
2
 
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
7
 
#
 
7
 
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
11
# GNU General Public License for more details.
12
 
#
 
12
 
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
 
# FIXME: This refactoring of the workingtree code doesn't seem to keep 
18
 
# the WorkingTree's copy of the inventory in sync with the branch.  The
19
 
# branch modifies its working inventory when it does a commit to make
20
 
# missing files permanently removed.
21
17
 
22
18
# TODO: Maybe also keep the full path of the entry, and the children?
23
19
# But those depend on its position within a particular inventory, and
35
31
import types
36
32
 
37
33
import bzrlib
 
34
from bzrlib.errors import BzrError, BzrCheckError
 
35
 
38
36
from bzrlib.osutils import (pumpfile, quotefn, splitpath, joinpath,
39
37
                            appendpath, sha_strings)
40
38
from bzrlib.trace import mutter
41
 
from bzrlib.errors import (NotVersionedError, InvalidEntryName,
42
 
                           BzrError, BzrCheckError)
 
39
from bzrlib.errors import NotVersionedError
43
40
 
44
41
 
45
42
class InventoryEntry(object):
53
50
    name
54
51
        (within the parent directory)
55
52
 
 
53
    kind
 
54
        'directory' or 'file' or 'symlink'
 
55
 
56
56
    parent_id
57
57
        file_id of the parent directory, or ROOT_ID
58
58
 
77
77
    'TREE_ROOT'
78
78
    >>> i.add(InventoryDirectory('123', 'src', ROOT_ID))
79
79
    InventoryDirectory('123', 'src', parent_id='TREE_ROOT')
80
 
    >>> i.add(InventoryFile('2323', 'hello.c', parent_id='123'))
81
 
    InventoryFile('2323', 'hello.c', parent_id='123')
 
80
    >>> i.add(InventoryEntry('2323', 'hello.c', 'file', parent_id='123'))
 
81
    InventoryEntry('2323', 'hello.c', kind='file', parent_id='123')
82
82
    >>> for j in i.iter_entries():
83
83
    ...   print j
84
84
    ... 
85
85
    ('src', InventoryDirectory('123', 'src', parent_id='TREE_ROOT'))
86
 
    ('src/hello.c', InventoryFile('2323', 'hello.c', parent_id='123'))
87
 
    >>> i.add(InventoryFile('2323', 'bye.c', '123'))
 
86
    ('src/hello.c', InventoryEntry('2323', 'hello.c', kind='file', parent_id='123'))
 
87
    >>> i.add(InventoryEntry('2323', 'bye.c', 'file', '123'))
88
88
    Traceback (most recent call last):
89
89
    ...
90
90
    BzrError: inventory already contains entry with id {2323}
91
 
    >>> i.add(InventoryFile('2324', 'bye.c', '123'))
92
 
    InventoryFile('2324', 'bye.c', parent_id='123')
 
91
    >>> i.add(InventoryEntry('2324', 'bye.c', 'file', '123'))
 
92
    InventoryEntry('2324', 'bye.c', kind='file', parent_id='123')
93
93
    >>> i.add(InventoryDirectory('2325', 'wibble', '123'))
94
94
    InventoryDirectory('2325', 'wibble', parent_id='123')
95
95
    >>> i.path2id('src/wibble')
96
96
    '2325'
97
97
    >>> '2325' in i
98
98
    True
99
 
    >>> i.add(InventoryFile('2326', 'wibble.c', '2325'))
100
 
    InventoryFile('2326', 'wibble.c', parent_id='2325')
 
99
    >>> i.add(InventoryEntry('2326', 'wibble.c', 'file', '2325'))
 
100
    InventoryEntry('2326', 'wibble.c', kind='file', parent_id='2325')
101
101
    >>> i['2326']
102
 
    InventoryFile('2326', 'wibble.c', parent_id='2325')
 
102
    InventoryEntry('2326', 'wibble.c', kind='file', parent_id='2325')
103
103
    >>> for path, entry in i.iter_entries():
104
104
    ...     print path.replace('\\\\', '/')     # for win32 os.sep
105
105
    ...     assert i.path2id(path)
115
115
    
116
116
    __slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
117
117
                 'text_id', 'parent_id', 'children', 'executable', 
118
 
                 'revision']
 
118
                 'revision', 'symlink_target']
119
119
 
120
 
    def _add_text_to_weave(self, new_lines, parents, weave_store, transaction):
121
 
        weave_store.add_text(self.file_id, self.revision, new_lines, parents,
122
 
                             transaction)
 
120
    def _add_text_to_weave(self, new_lines, parents, weave_store):
 
121
        weave_store.add_text(self.file_id, self.revision, new_lines, parents)
123
122
 
124
123
    def detect_changes(self, old_entry):
125
124
        """Return a (text_modified, meta_modified) from this to old_entry.
127
126
        _read_tree_state must have been called on self and old_entry prior to 
128
127
        calling detect_changes.
129
128
        """
130
 
        return False, False
 
129
        if self.kind == 'file':
 
130
            assert self.text_sha1 != None
 
131
            assert old_entry.text_sha1 != None
 
132
            text_modified = (self.text_sha1 != old_entry.text_sha1)
 
133
            meta_modified = (self.executable != old_entry.executable)
 
134
        elif self.kind == 'symlink':
 
135
            # FIXME: which _modified field should we use ? RBC 20051003
 
136
            text_modified = (self.symlink_target != old_entry.symlink_target)
 
137
            if text_modified:
 
138
                mutter("    symlink target changed")
 
139
            meta_modified = False
 
140
        else:
 
141
            text_modified = False
 
142
            meta_modified = False
 
143
        return text_modified, meta_modified
131
144
 
132
145
    def diff(self, text_diff, from_label, tree, to_label, to_entry, to_tree,
133
146
             output_to, reverse=False):
134
147
        """Perform a diff from this to to_entry.
135
148
 
136
149
        text_diff will be used for textual difference calculation.
137
 
        This is a template method, override _diff in child classes.
138
150
        """
139
151
        self._read_tree_state(tree.id2path(self.file_id), tree)
140
152
        if to_entry:
143
155
            assert self.kind == to_entry.kind
144
156
            to_entry._read_tree_state(to_tree.id2path(to_entry.file_id),
145
157
                                      to_tree)
146
 
        self._diff(text_diff, from_label, tree, to_label, to_entry, to_tree,
147
 
                   output_to, reverse)
148
 
 
149
 
    def _diff(self, text_diff, from_label, tree, to_label, to_entry, to_tree,
150
 
             output_to, reverse=False):
151
 
        """Perform a diff between two entries of the same kind."""
152
 
 
153
 
    def find_previous_heads(self, previous_inventories, entry_weave):
154
 
        """Return the revisions and entries that directly preceed this.
155
 
 
156
 
        Returned as a map from revision to inventory entry.
157
 
 
158
 
        This is a map containing the file revisions in all parents
159
 
        for which the file exists, and its revision is not a parent of
160
 
        any other. If the file is new, the set will be empty.
161
 
        """
162
 
        def get_ancestors(weave, entry):
163
 
            return set(map(weave.idx_to_name,
164
 
                           weave.inclusions([weave.lookup(entry.revision)])))
165
 
        heads = {}
166
 
        head_ancestors = {}
167
 
        for inv in previous_inventories:
168
 
            if self.file_id in inv:
169
 
                ie = inv[self.file_id]
170
 
                assert ie.file_id == self.file_id
171
 
                if ie.revision in heads:
172
 
                    # fixup logic, there was a bug in revision updates.
173
 
                    # with x bit support.
174
 
                    try:
175
 
                        if heads[ie.revision].executable != ie.executable:
176
 
                            heads[ie.revision].executable = False
177
 
                            ie.executable = False
178
 
                    except AttributeError:
179
 
                        pass
180
 
                    assert heads[ie.revision] == ie
 
158
        if self.kind == 'file':
 
159
            from_text = tree.get_file(self.file_id).readlines()
 
160
            if to_entry:
 
161
                to_text = to_tree.get_file(to_entry.file_id).readlines()
 
162
            else:
 
163
                to_text = []
 
164
            if not reverse:
 
165
                text_diff(from_label, from_text,
 
166
                          to_label, to_text, output_to)
 
167
            else:
 
168
                text_diff(to_label, to_text,
 
169
                          from_label, from_text, output_to)
 
170
        elif self.kind == 'symlink':
 
171
            from_text = self.symlink_target
 
172
            if to_entry is not None:
 
173
                to_text = to_entry.symlink_target
 
174
                if reverse:
 
175
                    temp = from_text
 
176
                    from_text = to_text
 
177
                    to_text = temp
 
178
                print >>output_to, '=== target changed %r => %r' % (from_text, to_text)
 
179
            else:
 
180
                if not reverse:
 
181
                    print >>output_to, '=== target was %r' % self.symlink_target
181
182
                else:
182
 
                    # may want to add it.
183
 
                    # may already be covered:
184
 
                    already_present = 0 != len(
185
 
                        [head for head in heads 
186
 
                         if ie.revision in head_ancestors[head]])
187
 
                    if already_present:
188
 
                        # an ancestor of a known head.
189
 
                        continue
190
 
                    # definately a head:
191
 
                    ancestors = get_ancestors(entry_weave, ie)
192
 
                    # may knock something else out:
193
 
                    check_heads = list(heads.keys())
194
 
                    for head in check_heads:
195
 
                        if head in ancestors:
196
 
                            # this head is not really a head
197
 
                            heads.pop(head)
198
 
                    head_ancestors[ie.revision] = ancestors
199
 
                    heads[ie.revision] = ie
200
 
        return heads
 
183
                    print >>output_to, '=== target is %r' % self.symlink_target
201
184
 
202
185
    def get_tar_item(self, root, dp, now, tree):
203
186
        """Get a tarfile item and a file stream for its content."""
212
195
        """Return true if the object this entry represents has textual data.
213
196
 
214
197
        Note that textual data includes binary content.
215
 
 
216
 
        Also note that all entries get weave files created for them.
217
 
        This attribute is primarily used when upgrading from old trees that
218
 
        did not have the weave index for all inventory entries.
219
198
        """
220
 
        return False
 
199
        if self.kind =='file':
 
200
            return True
 
201
        else:
 
202
            return False
221
203
 
222
 
    def __init__(self, file_id, name, parent_id, text_id=None):
 
204
    def __init__(self, file_id, name, kind, parent_id, text_id=None):
223
205
        """Create an InventoryEntry
224
206
        
225
207
        The filename must be a single component, relative to the
226
208
        parent directory; it cannot be a whole path or relative name.
227
209
 
228
 
        >>> e = InventoryFile('123', 'hello.c', ROOT_ID)
 
210
        >>> e = InventoryEntry('123', 'hello.c', 'file', ROOT_ID)
229
211
        >>> e.name
230
212
        'hello.c'
231
213
        >>> e.file_id
232
214
        '123'
233
 
        >>> e = InventoryFile('123', 'src/hello.c', ROOT_ID)
 
215
        >>> e = InventoryEntry('123', 'src/hello.c', 'file', ROOT_ID)
234
216
        Traceback (most recent call last):
235
 
        InvalidEntryName: Invalid entry name: src/hello.c
 
217
        BzrCheckError: InventoryEntry name 'src/hello.c' is invalid
236
218
        """
237
219
        assert isinstance(name, basestring), name
238
220
        if '/' in name or '\\' in name:
239
 
            raise InvalidEntryName(name=name)
 
221
            raise BzrCheckError('InventoryEntry name %r is invalid' % name)
 
222
        
240
223
        self.executable = False
241
224
        self.revision = None
242
225
        self.text_sha1 = None
243
226
        self.text_size = None
244
227
        self.file_id = file_id
245
228
        self.name = name
 
229
        self.kind = kind
246
230
        self.text_id = text_id
247
231
        self.parent_id = parent_id
248
232
        self.symlink_target = None
 
233
        if kind not in ('directory', 'file', 'symlink'):
 
234
            raise BzrError("unhandled entry kind %r" % kind)
249
235
 
250
236
    def kind_character(self):
251
237
        """Return a short kind indicator useful for appending to names."""
252
 
        raise BzrError('unknown kind %r' % self.kind)
 
238
        if self.kind == 'file':
 
239
            return ''
 
240
        if self.kind == 'symlink':
 
241
            return ''
 
242
        raise RuntimeError('unreachable code')
253
243
 
254
244
    known_kinds = ('file', 'directory', 'symlink', 'root_directory')
255
245
 
 
246
    def __new__(cls, file_id, name, kind, parent_id, text_id=None):
 
247
        """Factory method to return the appropriate concrete class."""
 
248
        return object.__new__(InventoryEntry, file_id, name, kind, parent_id,
 
249
                              text_id)
 
250
 
256
251
    def _put_in_tar(self, item, tree):
257
252
        """populate item for stashing in a tar, and return the content stream.
258
253
 
259
254
        If no content is available, return None.
260
255
        """
261
 
        raise BzrError("don't know how to export {%s} of kind %r" %
262
 
                       (self.file_id, self.kind))
 
256
        if self.kind == 'file':
 
257
            item.type = tarfile.REGTYPE
 
258
            fileobj = tree.get_file(self.file_id)
 
259
            item.size = self.text_size
 
260
            if tree.is_executable(self.file_id):
 
261
                item.mode = 0755
 
262
            else:
 
263
                item.mode = 0644
 
264
        elif self.kind == 'symlink':
 
265
            iterm.type = tarfile.SYMTYPE
 
266
            fileobj = None
 
267
            item.size = 0
 
268
            item.mode = 0755
 
269
            item.linkname = self.symlink_target
 
270
        else:
 
271
            raise BzrError("don't know how to export {%s} of kind %r" %
 
272
                    (self.file_id, self.kind))
 
273
        return fileobj
263
274
 
264
275
    def put_on_disk(self, dest, dp, tree):
265
276
        """Create a representation of self on disk in the prefix dest.
272
283
 
273
284
    def _put_on_disk(self, fullpath, tree):
274
285
        """Put this entry onto disk at fullpath, from tree tree."""
275
 
        raise BzrError("don't know how to export {%s} of kind %r" % (self.file_id, self.kind))
 
286
        if self.kind == 'file':
 
287
            pumpfile(tree.get_file(self.file_id), file(fullpath, 'wb'))
 
288
            if tree.is_executable(self.file_id):
 
289
                os.chmod(fullpath, 0755)
 
290
        elif self.kind == 'symlink':
 
291
            try:
 
292
                os.symlink(self.symlink_target, fullpath)
 
293
            except OSError,e:
 
294
                raise BzrError("Failed to create symlink %r -> %r, error: %s" % (fullpath, self.symlink_target, e))
 
295
        else:
 
296
            raise BzrError("don't know how to export {%s} of kind %r" % (self.file_id, self.kind))
276
297
 
277
298
    def sorted_children(self):
278
299
        l = self.children.items()
297
318
 
298
319
    def _check(self, checker, rev_id, tree):
299
320
        """Check this inventory entry for kind specific errors."""
300
 
        raise BzrCheckError('unknown entry kind %r in revision {%s}' % 
301
 
                            (self.kind, rev_id))
 
321
        if self.kind == 'file':
 
322
            revision = self.revision
 
323
            t = (self.file_id, revision)
 
324
            if t in checker.checked_texts:
 
325
                prev_sha = checker.checked_texts[t] 
 
326
                if prev_sha != self.text_sha1:
 
327
                    raise BzrCheckError('mismatched sha1 on {%s} in {%s}' %
 
328
                                        (self.file_id, rev_id))
 
329
                else:
 
330
                    checker.repeated_text_cnt += 1
 
331
                    return
 
332
            mutter('check version {%s} of {%s}', rev_id, self.file_id)
 
333
            file_lines = tree.get_file_lines(self.file_id)
 
334
            checker.checked_text_cnt += 1 
 
335
            if self.text_size != sum(map(len, file_lines)):
 
336
                raise BzrCheckError('text {%s} wrong size' % self.text_id)
 
337
            if self.text_sha1 != sha_strings(file_lines):
 
338
                raise BzrCheckError('text {%s} wrong sha1' % self.text_id)
 
339
            checker.checked_texts[t] = self.text_sha1
 
340
        elif self.kind == 'symlink':
 
341
            if self.text_sha1 != None or self.text_size != None or self.text_id != None:
 
342
                raise BzrCheckError('symlink {%s} has text in revision {%s}'
 
343
                        % (self.file_id, rev_id))
 
344
            if self.symlink_target == None:
 
345
                raise BzrCheckError('symlink {%s} has no target in revision {%s}'
 
346
                        % (self.file_id, rev_id))
 
347
        else:
 
348
            raise BzrCheckError('unknown entry kind %r in revision {%s}' % 
 
349
                                (self.kind, rev_id))
302
350
 
303
351
 
304
352
    def copy(self):
305
 
        """Clone this inventory entry."""
306
 
        raise NotImplementedError
 
353
        other = InventoryEntry(self.file_id, self.name, self.kind,
 
354
                               self.parent_id)
 
355
        other.executable = self.executable
 
356
        other.text_id = self.text_id
 
357
        other.text_sha1 = self.text_sha1
 
358
        other.text_size = self.text_size
 
359
        other.symlink_target = self.symlink_target
 
360
        other.revision = self.revision
 
361
        # note that children are *not* copied; they're pulled across when
 
362
        # others are added
 
363
        return other
307
364
 
308
365
    def _get_snapshot_change(self, previous_entries):
309
366
        if len(previous_entries) > 1:
314
371
            return 'modified/renamed/reparented'
315
372
 
316
373
    def __repr__(self):
317
 
        return ("%s(%r, %r, parent_id=%r)"
 
374
        return ("%s(%r, %r, kind=%r, parent_id=%r)"
318
375
                % (self.__class__.__name__,
319
376
                   self.file_id,
320
377
                   self.name,
 
378
                   self.kind,
321
379
                   self.parent_id))
322
380
 
323
 
    def snapshot(self, revision, path, previous_entries,
324
 
                 work_tree, weave_store, transaction):
325
 
        """Make a snapshot of this entry which may or may not have changed.
 
381
    def snapshot(self, revision, path, previous_entries, work_tree, 
 
382
                 weave_store):
 
383
        """Make a snapshot of this entry.
326
384
        
327
385
        This means that all its fields are populated, that it has its
328
386
        text stored in the text store or weave.
332
390
        if len(previous_entries) == 1:
333
391
            # cannot be unchanged unless there is only one parent file rev.
334
392
            parent_ie = previous_entries.values()[0]
335
 
            if self._unchanged(parent_ie):
 
393
            if self._unchanged(path, parent_ie, work_tree):
336
394
                mutter("found unchanged entry")
337
395
                self.revision = parent_ie.revision
338
396
                return "unchanged"
339
 
        return self.snapshot_revision(revision, previous_entries, 
340
 
                                      work_tree, weave_store, transaction)
341
 
 
342
 
    def snapshot_revision(self, revision, previous_entries, work_tree,
343
 
                          weave_store, transaction):
344
 
        """Record this revision unconditionally."""
345
397
        mutter('new revision for {%s}', self.file_id)
346
398
        self.revision = revision
347
399
        change = self._get_snapshot_change(previous_entries)
348
 
        self._snapshot_text(previous_entries, work_tree, weave_store,
349
 
                            transaction)
 
400
        if self.kind != 'file':
 
401
            return change
 
402
        self._snapshot_text(previous_entries, work_tree, weave_store)
350
403
        return change
351
404
 
352
 
    def _snapshot_text(self, file_parents, work_tree, weave_store, transaction): 
353
 
        """Record the 'text' of this entry, whatever form that takes.
354
 
        
355
 
        This default implementation simply adds an empty text.
356
 
        """
 
405
    def _snapshot_text(self, file_parents, work_tree, weave_store): 
357
406
        mutter('storing file {%s} in revision {%s}',
358
407
               self.file_id, self.revision)
359
 
        self._add_text_to_weave([], file_parents, weave_store, transaction)
 
408
        # special case to avoid diffing on renames or 
 
409
        # reparenting
 
410
        if (len(file_parents) == 1
 
411
            and self.text_sha1 == file_parents.values()[0].text_sha1
 
412
            and self.text_size == file_parents.values()[0].text_size):
 
413
            previous_ie = file_parents.values()[0]
 
414
            weave_store.add_identical_text(
 
415
                self.file_id, previous_ie.revision, 
 
416
                self.revision, file_parents)
 
417
        else:
 
418
            new_lines = work_tree.get_file(self.file_id).readlines()
 
419
            self._add_text_to_weave(new_lines, file_parents, weave_store)
 
420
            self.text_sha1 = sha_strings(new_lines)
 
421
            self.text_size = sum(map(len, new_lines))
360
422
 
361
423
    def __eq__(self, other):
362
424
        if not isinstance(other, InventoryEntry):
380
442
    def __hash__(self):
381
443
        raise ValueError('not hashable')
382
444
 
383
 
    def _unchanged(self, previous_ie):
384
 
        """Has this entry changed relative to previous_ie.
385
 
 
386
 
        This method should be overriden in child classes.
387
 
        """
 
445
    def _unchanged(self, path, previous_ie, work_tree):
388
446
        compatible = True
389
447
        # different inv parent
390
448
        if previous_ie.parent_id != self.parent_id:
392
450
        # renamed
393
451
        elif previous_ie.name != self.name:
394
452
            compatible = False
 
453
        if self.kind == 'symlink':
 
454
            if self.symlink_target != previous_ie.symlink_target:
 
455
                compatible = False
 
456
        if self.kind == 'file':
 
457
            if self.text_sha1 != previous_ie.text_sha1:
 
458
                compatible = False
 
459
            else:
 
460
                # FIXME: 20050930 probe for the text size when getting sha1
 
461
                # in _read_tree_state
 
462
                self.text_size = previous_ie.text_size
395
463
        return compatible
396
464
 
397
465
    def _read_tree_state(self, path, work_tree):
398
 
        """Populate fields in the inventory entry from the given tree.
399
 
        
400
 
        Note that this should be modified to be a noop on virtual trees
401
 
        as all entries created there are prepopulated.
402
 
        """
403
 
        # TODO: Rather than running this manually, we should check the 
404
 
        # working sha1 and other expensive properties when they're
405
 
        # first requested, or preload them if they're already known
406
 
        pass            # nothing to do by default
 
466
        if self.kind == 'symlink':
 
467
            self.symlink_target = work_tree.get_symlink_target(self.file_id)
 
468
        if self.kind == 'file':
 
469
            self.text_sha1 = work_tree.get_file_sha1(self.file_id)
 
470
            self.executable = work_tree.is_executable(self.file_id)
407
471
 
408
472
 
409
473
class RootEntry(InventoryEntry):
418
482
        self.parent_id = None
419
483
        self.name = ''
420
484
 
 
485
    def __new__(cls, file_id):
 
486
        """Only present until the InventoryEntry.__new__ can go away."""
 
487
        return object.__new__(RootEntry, file_id)
 
488
 
421
489
    def __eq__(self, other):
422
490
        if not isinstance(other, RootEntry):
423
491
            return NotImplemented
443
511
        return other
444
512
 
445
513
    def __init__(self, file_id, name, parent_id):
446
 
        super(InventoryDirectory, self).__init__(file_id, name, parent_id)
 
514
        super(InventoryDirectory, self).__init__(file_id, name, 'directory',
 
515
                                                 parent_id)
447
516
        self.children = {}
448
 
        self.kind = 'directory'
449
517
 
450
518
    def kind_character(self):
451
519
        """See InventoryEntry.kind_character."""
452
520
        return '/'
453
521
 
 
522
    def __new__(cls, file_id, name, parent_id):
 
523
        """Only present until the InventoryEntry.__new__ can go away."""
 
524
        result = object.__new__(InventoryDirectory, file_id, name, 'directory',
 
525
                                parent_id)
 
526
        # type.__call__ is strange, it doesn't __init__ when the returned type
 
527
        # differs
 
528
        #result.__init__(file_id, name, 'directory', parent_id)
 
529
        return result
 
530
 
454
531
    def _put_in_tar(self, item, tree):
455
532
        """See InventoryEntry._put_in_tar."""
456
533
        item.type = tarfile.DIRTYPE
464
541
        """See InventoryEntry._put_on_disk."""
465
542
        os.mkdir(fullpath)
466
543
 
467
 
 
468
 
class InventoryFile(InventoryEntry):
469
 
    """A file in an inventory."""
470
 
 
471
 
    def _check(self, checker, rev_id, tree):
472
 
        """See InventoryEntry._check"""
473
 
        revision = self.revision
474
 
        t = (self.file_id, revision)
475
 
        if t in checker.checked_texts:
476
 
            prev_sha = checker.checked_texts[t] 
477
 
            if prev_sha != self.text_sha1:
478
 
                raise BzrCheckError('mismatched sha1 on {%s} in {%s}' %
479
 
                                    (self.file_id, rev_id))
480
 
            else:
481
 
                checker.repeated_text_cnt += 1
482
 
                return
483
 
        mutter('check version {%s} of {%s}', rev_id, self.file_id)
484
 
        file_lines = tree.get_file_lines(self.file_id)
485
 
        checker.checked_text_cnt += 1 
486
 
        if self.text_size != sum(map(len, file_lines)):
487
 
            raise BzrCheckError('text {%s} wrong size' % self.text_id)
488
 
        if self.text_sha1 != sha_strings(file_lines):
489
 
            raise BzrCheckError('text {%s} wrong sha1' % self.text_id)
490
 
        checker.checked_texts[t] = self.text_sha1
491
 
 
492
 
    def copy(self):
493
 
        other = InventoryFile(self.file_id, self.name, self.parent_id)
494
 
        other.executable = self.executable
495
 
        other.text_id = self.text_id
496
 
        other.text_sha1 = self.text_sha1
497
 
        other.text_size = self.text_size
498
 
        other.revision = self.revision
499
 
        return other
500
 
 
501
 
    def detect_changes(self, old_entry):
502
 
        """See InventoryEntry.detect_changes."""
503
 
        assert self.text_sha1 != None
504
 
        assert old_entry.text_sha1 != None
505
 
        text_modified = (self.text_sha1 != old_entry.text_sha1)
506
 
        meta_modified = (self.executable != old_entry.executable)
507
 
        return text_modified, meta_modified
508
 
 
509
 
    def _diff(self, text_diff, from_label, tree, to_label, to_entry, to_tree,
510
 
             output_to, reverse=False):
511
 
        """See InventoryEntry._diff."""
512
 
        from_text = tree.get_file(self.file_id).readlines()
513
 
        if to_entry:
514
 
            to_text = to_tree.get_file(to_entry.file_id).readlines()
515
 
        else:
516
 
            to_text = []
517
 
        if not reverse:
518
 
            text_diff(from_label, from_text,
519
 
                      to_label, to_text, output_to)
520
 
        else:
521
 
            text_diff(to_label, to_text,
522
 
                      from_label, from_text, output_to)
523
 
 
524
 
    def has_text(self):
525
 
        """See InventoryEntry.has_text."""
526
 
        return True
527
 
 
528
 
    def __init__(self, file_id, name, parent_id):
529
 
        super(InventoryFile, self).__init__(file_id, name, parent_id)
530
 
        self.kind = 'file'
531
 
 
532
 
    def kind_character(self):
533
 
        """See InventoryEntry.kind_character."""
534
 
        return ''
535
 
 
536
 
    def _put_in_tar(self, item, tree):
537
 
        """See InventoryEntry._put_in_tar."""
538
 
        item.type = tarfile.REGTYPE
539
 
        fileobj = tree.get_file(self.file_id)
540
 
        item.size = self.text_size
541
 
        if tree.is_executable(self.file_id):
542
 
            item.mode = 0755
543
 
        else:
544
 
            item.mode = 0644
545
 
        return fileobj
546
 
 
547
 
    def _put_on_disk(self, fullpath, tree):
548
 
        """See InventoryEntry._put_on_disk."""
549
 
        pumpfile(tree.get_file(self.file_id), file(fullpath, 'wb'))
550
 
        if tree.is_executable(self.file_id):
551
 
            os.chmod(fullpath, 0755)
552
 
 
553
 
    def _read_tree_state(self, path, work_tree):
554
 
        """See InventoryEntry._read_tree_state."""
555
 
        self.text_sha1 = work_tree.get_file_sha1(self.file_id)
556
 
        self.executable = work_tree.is_executable(self.file_id)
557
 
 
558
 
    def _snapshot_text(self, file_parents, work_tree, weave_store, transaction):
559
 
        """See InventoryEntry._snapshot_text."""
560
 
        mutter('storing file {%s} in revision {%s}',
561
 
               self.file_id, self.revision)
562
 
        # special case to avoid diffing on renames or 
563
 
        # reparenting
564
 
        if (len(file_parents) == 1
565
 
            and self.text_sha1 == file_parents.values()[0].text_sha1
566
 
            and self.text_size == file_parents.values()[0].text_size):
567
 
            previous_ie = file_parents.values()[0]
568
 
            weave_store.add_identical_text(
569
 
                self.file_id, previous_ie.revision, 
570
 
                self.revision, file_parents, transaction)
571
 
        else:
572
 
            new_lines = work_tree.get_file(self.file_id).readlines()
573
 
            self._add_text_to_weave(new_lines, file_parents, weave_store,
574
 
                                    transaction)
575
 
            self.text_sha1 = sha_strings(new_lines)
576
 
            self.text_size = sum(map(len, new_lines))
577
 
 
578
 
 
579
 
    def _unchanged(self, previous_ie):
580
 
        """See InventoryEntry._unchanged."""
581
 
        compatible = super(InventoryFile, self)._unchanged(previous_ie)
582
 
        if self.text_sha1 != previous_ie.text_sha1:
583
 
            compatible = False
584
 
        else:
585
 
            # FIXME: 20050930 probe for the text size when getting sha1
586
 
            # in _read_tree_state
587
 
            self.text_size = previous_ie.text_size
588
 
        if self.executable != previous_ie.executable:
589
 
            compatible = False
590
 
        return compatible
591
 
 
592
 
 
593
 
class InventoryLink(InventoryEntry):
594
 
    """A file in an inventory."""
595
 
 
596
 
    __slots__ = ['symlink_target']
597
 
 
598
 
    def _check(self, checker, rev_id, tree):
599
 
        """See InventoryEntry._check"""
600
 
        if self.text_sha1 != None or self.text_size != None or self.text_id != None:
601
 
            raise BzrCheckError('symlink {%s} has text in revision {%s}'
602
 
                    % (self.file_id, rev_id))
603
 
        if self.symlink_target == None:
604
 
            raise BzrCheckError('symlink {%s} has no target in revision {%s}'
605
 
                    % (self.file_id, rev_id))
606
 
 
607
 
    def copy(self):
608
 
        other = InventoryLink(self.file_id, self.name, self.parent_id)
609
 
        other.symlink_target = self.symlink_target
610
 
        other.revision = self.revision
611
 
        return other
612
 
 
613
 
    def detect_changes(self, old_entry):
614
 
        """See InventoryEntry.detect_changes."""
615
 
        # FIXME: which _modified field should we use ? RBC 20051003
616
 
        text_modified = (self.symlink_target != old_entry.symlink_target)
617
 
        if text_modified:
618
 
            mutter("    symlink target changed")
619
 
        meta_modified = False
620
 
        return text_modified, meta_modified
621
 
 
622
 
    def _diff(self, text_diff, from_label, tree, to_label, to_entry, to_tree,
623
 
             output_to, reverse=False):
624
 
        """See InventoryEntry._diff."""
625
 
        from_text = self.symlink_target
626
 
        if to_entry is not None:
627
 
            to_text = to_entry.symlink_target
628
 
            if reverse:
629
 
                temp = from_text
630
 
                from_text = to_text
631
 
                to_text = temp
632
 
            print >>output_to, '=== target changed %r => %r' % (from_text, to_text)
633
 
        else:
634
 
            if not reverse:
635
 
                print >>output_to, '=== target was %r' % self.symlink_target
636
 
            else:
637
 
                print >>output_to, '=== target is %r' % self.symlink_target
638
 
 
639
 
    def __init__(self, file_id, name, parent_id):
640
 
        super(InventoryLink, self).__init__(file_id, name, parent_id)
641
 
        self.kind = 'symlink'
642
 
 
643
 
    def kind_character(self):
644
 
        """See InventoryEntry.kind_character."""
645
 
        return ''
646
 
 
647
 
    def _put_in_tar(self, item, tree):
648
 
        """See InventoryEntry._put_in_tar."""
649
 
        iterm.type = tarfile.SYMTYPE
650
 
        fileobj = None
651
 
        item.size = 0
652
 
        item.mode = 0755
653
 
        item.linkname = self.symlink_target
654
 
        return fileobj
655
 
 
656
 
    def _put_on_disk(self, fullpath, tree):
657
 
        """See InventoryEntry._put_on_disk."""
658
 
        try:
659
 
            os.symlink(self.symlink_target, fullpath)
660
 
        except OSError,e:
661
 
            raise BzrError("Failed to create symlink %r -> %r, error: %s" % (fullpath, self.symlink_target, e))
662
 
 
663
 
    def _read_tree_state(self, path, work_tree):
664
 
        """See InventoryEntry._read_tree_state."""
665
 
        self.symlink_target = work_tree.get_symlink_target(self.file_id)
666
 
 
667
 
    def _unchanged(self, previous_ie):
668
 
        """See InventoryEntry._unchanged."""
669
 
        compatible = super(InventoryLink, self)._unchanged(previous_ie)
670
 
        if self.symlink_target != previous_ie.symlink_target:
671
 
            compatible = False
672
 
        return compatible
 
544
    def __repr__(self):
 
545
        return ("%s(%r, %r, parent_id=%r)"
 
546
                % (self.__class__.__name__,
 
547
                   self.file_id,
 
548
                   self.name,
 
549
                   self.parent_id))
673
550
 
674
551
 
675
552
class Inventory(object):
690
567
    inserted, other than through the Inventory API.
691
568
 
692
569
    >>> inv = Inventory()
693
 
    >>> inv.add(InventoryFile('123-123', 'hello.c', ROOT_ID))
694
 
    InventoryFile('123-123', 'hello.c', parent_id='TREE_ROOT')
 
570
    >>> inv.add(InventoryEntry('123-123', 'hello.c', 'file', ROOT_ID))
 
571
    InventoryEntry('123-123', 'hello.c', kind='file', parent_id='TREE_ROOT')
695
572
    >>> inv['123-123'].name
696
573
    'hello.c'
697
574
 
707
584
    >>> [x[0] for x in inv.iter_entries()]
708
585
    ['hello.c']
709
586
    >>> inv = Inventory('TREE_ROOT-12345678-12345678')
710
 
    >>> inv.add(InventoryFile('123-123', 'hello.c', ROOT_ID))
711
 
    InventoryFile('123-123', 'hello.c', parent_id='TREE_ROOT-12345678-12345678')
 
587
    >>> inv.add(InventoryEntry('123-123', 'hello.c', 'file', ROOT_ID))
 
588
    InventoryEntry('123-123', 'hello.c', kind='file', parent_id='TREE_ROOT-12345678-12345678')
712
589
    """
713
590
    def __init__(self, root_id=ROOT_ID):
714
591
        """Create or read an inventory.
806
683
        """True if this entry contains a file with given id.
807
684
 
808
685
        >>> inv = Inventory()
809
 
        >>> inv.add(InventoryFile('123', 'foo.c', ROOT_ID))
810
 
        InventoryFile('123', 'foo.c', parent_id='TREE_ROOT')
 
686
        >>> inv.add(InventoryEntry('123', 'foo.c', 'file', ROOT_ID))
 
687
        InventoryEntry('123', 'foo.c', kind='file', parent_id='TREE_ROOT')
811
688
        >>> '123' in inv
812
689
        True
813
690
        >>> '456' in inv
820
697
        """Return the entry for given file_id.
821
698
 
822
699
        >>> inv = Inventory()
823
 
        >>> inv.add(InventoryFile('123123', 'hello.c', ROOT_ID))
824
 
        InventoryFile('123123', 'hello.c', parent_id='TREE_ROOT')
 
700
        >>> inv.add(InventoryEntry('123123', 'hello.c', 'file', ROOT_ID))
 
701
        InventoryEntry('123123', 'hello.c', kind='file', parent_id='TREE_ROOT')
825
702
        >>> inv['123123'].name
826
703
        'hello.c'
827
704
        """
887
764
        parent_path = parts[:-1]
888
765
        parent_id = self.path2id(parent_path)
889
766
        if parent_id == None:
890
 
            raise NotVersionedError(path=parent_path)
 
767
            raise NotVersionedError(parent_path)
 
768
 
891
769
        if kind == 'directory':
892
770
            ie = InventoryDirectory(file_id, parts[-1], parent_id)
893
 
        elif kind == 'file':
894
 
            ie = InventoryFile(file_id, parts[-1], parent_id)
895
 
        elif kind == 'symlink':
896
 
            ie = InventoryLink(file_id, parts[-1], parent_id)
897
771
        else:
898
 
            raise BzrError("unknown kind %r" % kind)
 
772
            ie = InventoryEntry(file_id, parts[-1],
 
773
                                kind=kind, parent_id=parent_id)
899
774
        return self.add(ie)
900
775
 
901
776
 
903
778
        """Remove entry by id.
904
779
 
905
780
        >>> inv = Inventory()
906
 
        >>> inv.add(InventoryFile('123', 'foo.c', ROOT_ID))
907
 
        InventoryFile('123', 'foo.c', parent_id='TREE_ROOT')
 
781
        >>> inv.add(InventoryEntry('123', 'foo.c', 'file', ROOT_ID))
 
782
        InventoryEntry('123', 'foo.c', kind='file', parent_id='TREE_ROOT')
908
783
        >>> '123' in inv
909
784
        True
910
785
        >>> del inv['123']
933
808
        >>> i2 = Inventory()
934
809
        >>> i1 == i2
935
810
        True
936
 
        >>> i1.add(InventoryFile('123', 'foo', ROOT_ID))
937
 
        InventoryFile('123', 'foo', parent_id='TREE_ROOT')
 
811
        >>> i1.add(InventoryEntry('123', 'foo', 'file', ROOT_ID))
 
812
        InventoryEntry('123', 'foo', kind='file', parent_id='TREE_ROOT')
938
813
        >>> i1 == i2
939
814
        False
940
 
        >>> i2.add(InventoryFile('123', 'foo', ROOT_ID))
941
 
        InventoryFile('123', 'foo', parent_id='TREE_ROOT')
 
815
        >>> i2.add(InventoryEntry('123', 'foo', 'file', ROOT_ID))
 
816
        InventoryEntry('123', 'foo', kind='file', parent_id='TREE_ROOT')
942
817
        >>> i1 == i2
943
818
        True
944
819
        """
980
855
 
981
856
 
982
857
    def id2path(self, file_id):
983
 
        """Return as a list the path to file_id.
984
 
        
985
 
        >>> i = Inventory()
986
 
        >>> e = i.add(InventoryDirectory('src-id', 'src', ROOT_ID))
987
 
        >>> e = i.add(InventoryFile('foo-id', 'foo.c', parent_id='src-id'))
988
 
        >>> print i.id2path('foo-id').replace(os.sep, '/')
989
 
        src/foo.c
990
 
        """
 
858
        """Return as a list the path to file_id."""
 
859
 
991
860
        # get all names, skipping root
992
861
        p = [self._byid[fid].name for fid in self.get_idpath(file_id)[1:]]
993
862
        return os.sep.join(p)