/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/inventory.py

Merge bzr.dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
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
 
 
22
# TODO: Maybe also keep the full path of the entry, and the children?
 
23
# But those depend on its position within a particular inventory, and
 
24
# it would be nice not to need to hold the backpointer here.
 
25
 
 
26
# This should really be an id randomly assigned when the tree is
 
27
# created, but it's not for now.
 
28
ROOT_ID = "TREE_ROOT"
 
29
 
 
30
import os
 
31
import re
 
32
import sys
 
33
 
 
34
from bzrlib.lazy_import import lazy_import
 
35
lazy_import(globals(), """
 
36
import collections
 
37
import tarfile
 
38
 
 
39
import bzrlib
 
40
from bzrlib import (
 
41
    errors,
 
42
    generate_ids,
 
43
    osutils,
 
44
    symbol_versioning,
 
45
    workingtree,
 
46
    )
 
47
""")
 
48
 
 
49
from bzrlib.errors import (
 
50
    BzrCheckError,
 
51
    BzrError,
 
52
    )
 
53
from bzrlib.trace import mutter
 
54
 
 
55
 
 
56
class InventoryEntry(object):
 
57
    """Description of a versioned file.
 
58
 
 
59
    An InventoryEntry has the following fields, which are also
 
60
    present in the XML inventory-entry element:
 
61
 
 
62
    file_id
 
63
 
 
64
    name
 
65
        (within the parent directory)
 
66
 
 
67
    parent_id
 
68
        file_id of the parent directory, or ROOT_ID
 
69
 
 
70
    revision
 
71
        the revision_id in which this variation of this file was 
 
72
        introduced.
 
73
 
 
74
    executable
 
75
        Indicates that this file should be executable on systems
 
76
        that support it.
 
77
 
 
78
    text_sha1
 
79
        sha-1 of the text of the file
 
80
        
 
81
    text_size
 
82
        size in bytes of the text of the file
 
83
        
 
84
    (reading a version 4 tree created a text_id field.)
 
85
 
 
86
    >>> i = Inventory()
 
87
    >>> i.path2id('')
 
88
    'TREE_ROOT'
 
89
    >>> i.add(InventoryDirectory('123', 'src', ROOT_ID))
 
90
    InventoryDirectory('123', 'src', parent_id='TREE_ROOT', revision=None)
 
91
    >>> i.add(InventoryFile('2323', 'hello.c', parent_id='123'))
 
92
    InventoryFile('2323', 'hello.c', parent_id='123', sha1=None, len=None)
 
93
    >>> shouldbe = {0: '', 1: 'src', 2: 'src/hello.c'}
 
94
    >>> for ix, j in enumerate(i.iter_entries()):
 
95
    ...   print (j[0] == shouldbe[ix], j[1])
 
96
    ... 
 
97
    (True, InventoryDirectory('TREE_ROOT', u'', parent_id=None, revision=None))
 
98
    (True, InventoryDirectory('123', 'src', parent_id='TREE_ROOT', revision=None))
 
99
    (True, InventoryFile('2323', 'hello.c', parent_id='123', sha1=None, len=None))
 
100
    >>> i.add(InventoryFile('2324', 'bye.c', '123'))
 
101
    InventoryFile('2324', 'bye.c', parent_id='123', sha1=None, len=None)
 
102
    >>> i.add(InventoryDirectory('2325', 'wibble', '123'))
 
103
    InventoryDirectory('2325', 'wibble', parent_id='123', revision=None)
 
104
    >>> i.path2id('src/wibble')
 
105
    '2325'
 
106
    >>> '2325' in i
 
107
    True
 
108
    >>> i.add(InventoryFile('2326', 'wibble.c', '2325'))
 
109
    InventoryFile('2326', 'wibble.c', parent_id='2325', sha1=None, len=None)
 
110
    >>> i['2326']
 
111
    InventoryFile('2326', 'wibble.c', parent_id='2325', sha1=None, len=None)
 
112
    >>> for path, entry in i.iter_entries():
 
113
    ...     print path
 
114
    ...     assert i.path2id(path)
 
115
    ... 
 
116
    <BLANKLINE>
 
117
    src
 
118
    src/bye.c
 
119
    src/hello.c
 
120
    src/wibble
 
121
    src/wibble/wibble.c
 
122
    >>> i.id2path('2326')
 
123
    'src/wibble/wibble.c'
 
124
    """
 
125
 
 
126
    # Constants returned by describe_change()
 
127
    #
 
128
    # TODO: These should probably move to some kind of FileChangeDescription 
 
129
    # class; that's like what's inside a TreeDelta but we want to be able to 
 
130
    # generate them just for one file at a time.
 
131
    RENAMED = 'renamed'
 
132
    MODIFIED_AND_RENAMED = 'modified and renamed'
 
133
    
 
134
    __slots__ = []
 
135
 
 
136
    def detect_changes(self, old_entry):
 
137
        """Return a (text_modified, meta_modified) from this to old_entry.
 
138
        
 
139
        _read_tree_state must have been called on self and old_entry prior to 
 
140
        calling detect_changes.
 
141
        """
 
142
        return False, False
 
143
 
 
144
    def diff(self, text_diff, from_label, tree, to_label, to_entry, to_tree,
 
145
             output_to, reverse=False):
 
146
        """Perform a diff from this to to_entry.
 
147
 
 
148
        text_diff will be used for textual difference calculation.
 
149
        This is a template method, override _diff in child classes.
 
150
        """
 
151
        self._read_tree_state(tree.id2path(self.file_id), tree)
 
152
        if to_entry:
 
153
            # cannot diff from one kind to another - you must do a removal
 
154
            # and an addif they do not match.
 
155
            assert self.kind == to_entry.kind
 
156
            to_entry._read_tree_state(to_tree.id2path(to_entry.file_id),
 
157
                                      to_tree)
 
158
        self._diff(text_diff, from_label, tree, to_label, to_entry, to_tree,
 
159
                   output_to, reverse)
 
160
 
 
161
    def _diff(self, text_diff, from_label, tree, to_label, to_entry, to_tree,
 
162
             output_to, reverse=False):
 
163
        """Perform a diff between two entries of the same kind."""
 
164
 
 
165
    def find_previous_heads(self, previous_inventories,
 
166
                            versioned_file_store,
 
167
                            transaction,
 
168
                            entry_vf=None):
 
169
        """Return the revisions and entries that directly precede this.
 
170
 
 
171
        Returned as a map from revision to inventory entry.
 
172
 
 
173
        This is a map containing the file revisions in all parents
 
174
        for which the file exists, and its revision is not a parent of
 
175
        any other. If the file is new, the set will be empty.
 
176
 
 
177
        :param versioned_file_store: A store where ancestry data on this
 
178
                                     file id can be queried.
 
179
        :param transaction: The transaction that queries to the versioned 
 
180
                            file store should be completed under.
 
181
        :param entry_vf: The entry versioned file, if its already available.
 
182
        """
 
183
        def get_ancestors(weave, entry):
 
184
            return set(weave.get_ancestry(entry.revision, topo_sorted=False))
 
185
        # revision:ie mapping for each ie found in previous_inventories.
 
186
        candidates = {}
 
187
        # revision:ie mapping with one revision for each head.
 
188
        heads = {}
 
189
        # revision: ancestor list for each head
 
190
        head_ancestors = {}
 
191
        # identify candidate head revision ids.
 
192
        for inv in previous_inventories:
 
193
            if self.file_id in inv:
 
194
                ie = inv[self.file_id]
 
195
                assert ie.file_id == self.file_id
 
196
                if ie.kind != self.kind:
 
197
                    # Can't be a candidate if the kind has changed.
 
198
                    continue
 
199
                if ie.revision in candidates:
 
200
                    # same revision value in two different inventories:
 
201
                    # correct possible inconsistencies:
 
202
                    #     * there was a bug in revision updates with 'x' bit 
 
203
                    #       support.
 
204
                    try:
 
205
                        if candidates[ie.revision].executable != ie.executable:
 
206
                            candidates[ie.revision].executable = False
 
207
                            ie.executable = False
 
208
                    except AttributeError:
 
209
                        pass
 
210
                    # must now be the same.
 
211
                    assert candidates[ie.revision] == ie
 
212
                else:
 
213
                    # add this revision as a candidate.
 
214
                    candidates[ie.revision] = ie
 
215
 
 
216
        # common case optimisation
 
217
        if len(candidates) == 1:
 
218
            # if there is only one candidate revision found
 
219
            # then we can opening the versioned file to access ancestry:
 
220
            # there cannot be any ancestors to eliminate when there is 
 
221
            # only one revision available.
 
222
            heads[ie.revision] = ie
 
223
            return heads
 
224
 
 
225
        # eliminate ancestors amongst the available candidates:
 
226
        # heads are those that are not an ancestor of any other candidate
 
227
        # - this provides convergence at a per-file level.
 
228
        for ie in candidates.values():
 
229
            # may be an ancestor of a known head:
 
230
            already_present = 0 != len(
 
231
                [head for head in heads 
 
232
                 if ie.revision in head_ancestors[head]])
 
233
            if already_present:
 
234
                # an ancestor of an analyzed candidate.
 
235
                continue
 
236
            # not an ancestor of a known head:
 
237
            # load the versioned file for this file id if needed
 
238
            if entry_vf is None:
 
239
                entry_vf = versioned_file_store.get_weave_or_empty(
 
240
                    self.file_id, transaction)
 
241
            ancestors = get_ancestors(entry_vf, ie)
 
242
            # may knock something else out:
 
243
            check_heads = list(heads.keys())
 
244
            for head in check_heads:
 
245
                if head in ancestors:
 
246
                    # this previously discovered 'head' is not
 
247
                    # really a head - its an ancestor of the newly 
 
248
                    # found head,
 
249
                    heads.pop(head)
 
250
            head_ancestors[ie.revision] = ancestors
 
251
            heads[ie.revision] = ie
 
252
        return heads
 
253
 
 
254
    def get_tar_item(self, root, dp, now, tree):
 
255
        """Get a tarfile item and a file stream for its content."""
 
256
        item = tarfile.TarInfo(osutils.pathjoin(root, dp).encode('utf8'))
 
257
        # TODO: would be cool to actually set it to the timestamp of the
 
258
        # revision it was last changed
 
259
        item.mtime = now
 
260
        fileobj = self._put_in_tar(item, tree)
 
261
        return item, fileobj
 
262
 
 
263
    def has_text(self):
 
264
        """Return true if the object this entry represents has textual data.
 
265
 
 
266
        Note that textual data includes binary content.
 
267
 
 
268
        Also note that all entries get weave files created for them.
 
269
        This attribute is primarily used when upgrading from old trees that
 
270
        did not have the weave index for all inventory entries.
 
271
        """
 
272
        return False
 
273
 
 
274
    def __init__(self, file_id, name, parent_id, text_id=None):
 
275
        """Create an InventoryEntry
 
276
        
 
277
        The filename must be a single component, relative to the
 
278
        parent directory; it cannot be a whole path or relative name.
 
279
 
 
280
        >>> e = InventoryFile('123', 'hello.c', ROOT_ID)
 
281
        >>> e.name
 
282
        'hello.c'
 
283
        >>> e.file_id
 
284
        '123'
 
285
        >>> e = InventoryFile('123', 'src/hello.c', ROOT_ID)
 
286
        Traceback (most recent call last):
 
287
        InvalidEntryName: Invalid entry name: src/hello.c
 
288
        """
 
289
        assert isinstance(name, basestring), name
 
290
        if '/' in name or '\\' in name:
 
291
            raise errors.InvalidEntryName(name=name)
 
292
        self.executable = False
 
293
        self.revision = None
 
294
        self.text_sha1 = None
 
295
        self.text_size = None
 
296
        self.file_id = file_id
 
297
        assert isinstance(file_id, (str, None.__class__)), \
 
298
            'bad type %r for %r' % (type(file_id), file_id)
 
299
        self.name = name
 
300
        self.text_id = text_id
 
301
        self.parent_id = parent_id
 
302
        self.symlink_target = None
 
303
        self.reference_revision = None
 
304
 
 
305
    def kind_character(self):
 
306
        """Return a short kind indicator useful for appending to names."""
 
307
        raise BzrError('unknown kind %r' % self.kind)
 
308
 
 
309
    known_kinds = ('file', 'directory', 'symlink')
 
310
 
 
311
    def _put_in_tar(self, item, tree):
 
312
        """populate item for stashing in a tar, and return the content stream.
 
313
 
 
314
        If no content is available, return None.
 
315
        """
 
316
        raise BzrError("don't know how to export {%s} of kind %r" %
 
317
                       (self.file_id, self.kind))
 
318
 
 
319
    def put_on_disk(self, dest, dp, tree):
 
320
        """Create a representation of self on disk in the prefix dest.
 
321
        
 
322
        This is a template method - implement _put_on_disk in subclasses.
 
323
        """
 
324
        fullpath = osutils.pathjoin(dest, dp)
 
325
        self._put_on_disk(fullpath, tree)
 
326
        # mutter("  export {%s} kind %s to %s", self.file_id,
 
327
        #         self.kind, fullpath)
 
328
 
 
329
    def _put_on_disk(self, fullpath, tree):
 
330
        """Put this entry onto disk at fullpath, from tree tree."""
 
331
        raise BzrError("don't know how to export {%s} of kind %r" % (self.file_id, self.kind))
 
332
 
 
333
    def sorted_children(self):
 
334
        return sorted(self.children.items())
 
335
 
 
336
    @staticmethod
 
337
    def versionable_kind(kind):
 
338
        return (kind in ('file', 'directory', 'symlink', 'tree-reference'))
 
339
 
 
340
    def check(self, checker, rev_id, inv, tree):
 
341
        """Check this inventory entry is intact.
 
342
 
 
343
        This is a template method, override _check for kind specific
 
344
        tests.
 
345
 
 
346
        :param checker: Check object providing context for the checks; 
 
347
             can be used to find out what parts of the repository have already
 
348
             been checked.
 
349
        :param rev_id: Revision id from which this InventoryEntry was loaded.
 
350
             Not necessarily the last-changed revision for this file.
 
351
        :param inv: Inventory from which the entry was loaded.
 
352
        :param tree: RevisionTree for this entry.
 
353
        """
 
354
        if self.parent_id is not None:
 
355
            if not inv.has_id(self.parent_id):
 
356
                raise BzrCheckError('missing parent {%s} in inventory for revision {%s}'
 
357
                        % (self.parent_id, rev_id))
 
358
        self._check(checker, rev_id, tree)
 
359
 
 
360
    def _check(self, checker, rev_id, tree):
 
361
        """Check this inventory entry for kind specific errors."""
 
362
        raise BzrCheckError('unknown entry kind %r in revision {%s}' % 
 
363
                            (self.kind, rev_id))
 
364
 
 
365
    def copy(self):
 
366
        """Clone this inventory entry."""
 
367
        raise NotImplementedError
 
368
 
 
369
    @staticmethod
 
370
    def describe_change(old_entry, new_entry):
 
371
        """Describe the change between old_entry and this.
 
372
        
 
373
        This smells of being an InterInventoryEntry situation, but as its
 
374
        the first one, we're making it a static method for now.
 
375
 
 
376
        An entry with a different parent, or different name is considered 
 
377
        to be renamed. Reparenting is an internal detail.
 
378
        Note that renaming the parent does not trigger a rename for the
 
379
        child entry itself.
 
380
        """
 
381
        # TODO: Perhaps return an object rather than just a string
 
382
        if old_entry is new_entry:
 
383
            # also the case of both being None
 
384
            return 'unchanged'
 
385
        elif old_entry is None:
 
386
            return 'added'
 
387
        elif new_entry is None:
 
388
            return 'removed'
 
389
        if old_entry.kind != new_entry.kind:
 
390
            return 'modified'
 
391
        text_modified, meta_modified = new_entry.detect_changes(old_entry)
 
392
        if text_modified or meta_modified:
 
393
            modified = True
 
394
        else:
 
395
            modified = False
 
396
        # TODO 20060511 (mbp, rbc) factor out 'detect_rename' here.
 
397
        if old_entry.parent_id != new_entry.parent_id:
 
398
            renamed = True
 
399
        elif old_entry.name != new_entry.name:
 
400
            renamed = True
 
401
        else:
 
402
            renamed = False
 
403
        if renamed and not modified:
 
404
            return InventoryEntry.RENAMED
 
405
        if modified and not renamed:
 
406
            return 'modified'
 
407
        if modified and renamed:
 
408
            return InventoryEntry.MODIFIED_AND_RENAMED
 
409
        return 'unchanged'
 
410
 
 
411
    def __repr__(self):
 
412
        return ("%s(%r, %r, parent_id=%r, revision=%r)"
 
413
                % (self.__class__.__name__,
 
414
                   self.file_id,
 
415
                   self.name,
 
416
                   self.parent_id,
 
417
                   self.revision))
 
418
 
 
419
    def snapshot(self, revision, path, previous_entries,
 
420
                 work_tree, commit_builder):
 
421
        """Make a snapshot of this entry which may or may not have changed.
 
422
        
 
423
        This means that all its fields are populated, that it has its
 
424
        text stored in the text store or weave.
 
425
 
 
426
        :return: True if anything was recorded
 
427
        """
 
428
        # cannot be unchanged unless there is only one parent file rev.
 
429
        self._read_tree_state(path, work_tree)
 
430
        if len(previous_entries) == 1:
 
431
            parent_ie = previous_entries.values()[0]
 
432
            if self._unchanged(parent_ie):
 
433
                self.revision = parent_ie.revision
 
434
                return False
 
435
        self.revision = revision
 
436
        return self._snapshot_text(previous_entries, work_tree, commit_builder)
 
437
 
 
438
    def _snapshot_text(self, file_parents, work_tree, commit_builder): 
 
439
        """Record the 'text' of this entry, whatever form that takes.
 
440
 
 
441
        :return: True if anything was recorded
 
442
        """
 
443
        raise NotImplementedError(self._snapshot_text)
 
444
 
 
445
    def __eq__(self, other):
 
446
        if not isinstance(other, InventoryEntry):
 
447
            return NotImplemented
 
448
 
 
449
        return ((self.file_id == other.file_id)
 
450
                and (self.name == other.name)
 
451
                and (other.symlink_target == self.symlink_target)
 
452
                and (self.text_sha1 == other.text_sha1)
 
453
                and (self.text_size == other.text_size)
 
454
                and (self.text_id == other.text_id)
 
455
                and (self.parent_id == other.parent_id)
 
456
                and (self.kind == other.kind)
 
457
                and (self.revision == other.revision)
 
458
                and (self.executable == other.executable)
 
459
                and (self.reference_revision == other.reference_revision)
 
460
                )
 
461
 
 
462
    def __ne__(self, other):
 
463
        return not (self == other)
 
464
 
 
465
    def __hash__(self):
 
466
        raise ValueError('not hashable')
 
467
 
 
468
    def _unchanged(self, previous_ie):
 
469
        """Has this entry changed relative to previous_ie.
 
470
 
 
471
        This method should be overridden in child classes.
 
472
        """
 
473
        compatible = True
 
474
        # different inv parent
 
475
        if previous_ie.parent_id != self.parent_id:
 
476
            compatible = False
 
477
        # renamed
 
478
        elif previous_ie.name != self.name:
 
479
            compatible = False
 
480
        elif previous_ie.kind != self.kind:
 
481
            compatible = False
 
482
        return compatible
 
483
 
 
484
    def _read_tree_state(self, path, work_tree):
 
485
        """Populate fields in the inventory entry from the given tree.
 
486
        
 
487
        Note that this should be modified to be a noop on virtual trees
 
488
        as all entries created there are prepopulated.
 
489
        """
 
490
        # TODO: Rather than running this manually, we should check the 
 
491
        # working sha1 and other expensive properties when they're
 
492
        # first requested, or preload them if they're already known
 
493
        pass            # nothing to do by default
 
494
 
 
495
    def _forget_tree_state(self):
 
496
        pass
 
497
 
 
498
 
 
499
class RootEntry(InventoryEntry):
 
500
 
 
501
    __slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
 
502
                 'text_id', 'parent_id', 'children', 'executable',
 
503
                 'revision', 'symlink_target', 'reference_revision']
 
504
 
 
505
    def _check(self, checker, rev_id, tree):
 
506
        """See InventoryEntry._check"""
 
507
 
 
508
    def __init__(self, file_id):
 
509
        self.file_id = file_id
 
510
        self.children = {}
 
511
        self.kind = 'directory'
 
512
        self.parent_id = None
 
513
        self.name = u''
 
514
        self.revision = None
 
515
        symbol_versioning.warn('RootEntry is deprecated as of bzr 0.10.'
 
516
                               '  Please use InventoryDirectory instead.',
 
517
                               DeprecationWarning, stacklevel=2)
 
518
 
 
519
    def __eq__(self, other):
 
520
        if not isinstance(other, RootEntry):
 
521
            return NotImplemented
 
522
        
 
523
        return (self.file_id == other.file_id) \
 
524
               and (self.children == other.children)
 
525
 
 
526
 
 
527
class InventoryDirectory(InventoryEntry):
 
528
    """A directory in an inventory."""
 
529
 
 
530
    __slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
 
531
                 'text_id', 'parent_id', 'children', 'executable',
 
532
                 'revision', 'symlink_target', 'reference_revision']
 
533
 
 
534
    def _check(self, checker, rev_id, tree):
 
535
        """See InventoryEntry._check"""
 
536
        if self.text_sha1 is not None or self.text_size is not None or self.text_id is not None:
 
537
            raise BzrCheckError('directory {%s} has text in revision {%s}'
 
538
                                % (self.file_id, rev_id))
 
539
 
 
540
    def copy(self):
 
541
        other = InventoryDirectory(self.file_id, self.name, self.parent_id)
 
542
        other.revision = self.revision
 
543
        # note that children are *not* copied; they're pulled across when
 
544
        # others are added
 
545
        return other
 
546
 
 
547
    def __init__(self, file_id, name, parent_id):
 
548
        super(InventoryDirectory, self).__init__(file_id, name, parent_id)
 
549
        self.children = {}
 
550
        self.kind = 'directory'
 
551
 
 
552
    def kind_character(self):
 
553
        """See InventoryEntry.kind_character."""
 
554
        return '/'
 
555
 
 
556
    def _put_in_tar(self, item, tree):
 
557
        """See InventoryEntry._put_in_tar."""
 
558
        item.type = tarfile.DIRTYPE
 
559
        fileobj = None
 
560
        item.name += '/'
 
561
        item.size = 0
 
562
        item.mode = 0755
 
563
        return fileobj
 
564
 
 
565
    def _put_on_disk(self, fullpath, tree):
 
566
        """See InventoryEntry._put_on_disk."""
 
567
        os.mkdir(fullpath)
 
568
 
 
569
    def _snapshot_text(self, file_parents, work_tree, commit_builder):
 
570
        """See InventoryEntry._snapshot_text."""
 
571
        commit_builder.modified_directory(self.file_id, file_parents)
 
572
        return True
 
573
 
 
574
 
 
575
class InventoryFile(InventoryEntry):
 
576
    """A file in an inventory."""
 
577
 
 
578
    __slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
 
579
                 'text_id', 'parent_id', 'children', 'executable',
 
580
                 'revision', 'symlink_target', 'reference_revision']
 
581
 
 
582
    def _check(self, checker, tree_revision_id, tree):
 
583
        """See InventoryEntry._check"""
 
584
        t = (self.file_id, self.revision)
 
585
        if t in checker.checked_texts:
 
586
            prev_sha = checker.checked_texts[t]
 
587
            if prev_sha != self.text_sha1:
 
588
                raise BzrCheckError('mismatched sha1 on {%s} in {%s}' %
 
589
                                    (self.file_id, tree_revision_id))
 
590
            else:
 
591
                checker.repeated_text_cnt += 1
 
592
                return
 
593
 
 
594
        if self.file_id not in checker.checked_weaves:
 
595
            mutter('check weave {%s}', self.file_id)
 
596
            w = tree._get_weave(self.file_id)
 
597
            # Not passing a progress bar, because it creates a new
 
598
            # progress, which overwrites the current progress,
 
599
            # and doesn't look nice
 
600
            w.check()
 
601
            checker.checked_weaves[self.file_id] = True
 
602
        else:
 
603
            w = tree._get_weave(self.file_id)
 
604
 
 
605
        mutter('check version {%s} of {%s}', tree_revision_id, self.file_id)
 
606
        checker.checked_text_cnt += 1
 
607
        # We can't check the length, because Weave doesn't store that
 
608
        # information, and the whole point of looking at the weave's
 
609
        # sha1sum is that we don't have to extract the text.
 
610
        if self.text_sha1 != w.get_sha1(self.revision):
 
611
            raise BzrCheckError('text {%s} version {%s} wrong sha1' 
 
612
                                % (self.file_id, self.revision))
 
613
        checker.checked_texts[t] = self.text_sha1
 
614
 
 
615
    def copy(self):
 
616
        other = InventoryFile(self.file_id, self.name, self.parent_id)
 
617
        other.executable = self.executable
 
618
        other.text_id = self.text_id
 
619
        other.text_sha1 = self.text_sha1
 
620
        other.text_size = self.text_size
 
621
        other.revision = self.revision
 
622
        return other
 
623
 
 
624
    def detect_changes(self, old_entry):
 
625
        """See InventoryEntry.detect_changes."""
 
626
        assert self.text_sha1 is not None
 
627
        assert old_entry.text_sha1 is not None
 
628
        text_modified = (self.text_sha1 != old_entry.text_sha1)
 
629
        meta_modified = (self.executable != old_entry.executable)
 
630
        return text_modified, meta_modified
 
631
 
 
632
    def _diff(self, text_diff, from_label, tree, to_label, to_entry, to_tree,
 
633
             output_to, reverse=False):
 
634
        """See InventoryEntry._diff."""
 
635
        try:
 
636
            from_text = tree.get_file(self.file_id).readlines()
 
637
            if to_entry:
 
638
                to_text = to_tree.get_file(to_entry.file_id).readlines()
 
639
            else:
 
640
                to_text = []
 
641
            if not reverse:
 
642
                text_diff(from_label, from_text,
 
643
                          to_label, to_text, output_to)
 
644
            else:
 
645
                text_diff(to_label, to_text,
 
646
                          from_label, from_text, output_to)
 
647
        except errors.BinaryFile:
 
648
            if reverse:
 
649
                label_pair = (to_label, from_label)
 
650
            else:
 
651
                label_pair = (from_label, to_label)
 
652
            print >> output_to, \
 
653
                  ("Binary files %s and %s differ" % label_pair).encode('utf8')
 
654
 
 
655
    def has_text(self):
 
656
        """See InventoryEntry.has_text."""
 
657
        return True
 
658
 
 
659
    def __init__(self, file_id, name, parent_id):
 
660
        super(InventoryFile, self).__init__(file_id, name, parent_id)
 
661
        self.kind = 'file'
 
662
 
 
663
    def kind_character(self):
 
664
        """See InventoryEntry.kind_character."""
 
665
        return ''
 
666
 
 
667
    def _put_in_tar(self, item, tree):
 
668
        """See InventoryEntry._put_in_tar."""
 
669
        item.type = tarfile.REGTYPE
 
670
        fileobj = tree.get_file(self.file_id)
 
671
        item.size = self.text_size
 
672
        if tree.is_executable(self.file_id):
 
673
            item.mode = 0755
 
674
        else:
 
675
            item.mode = 0644
 
676
        return fileobj
 
677
 
 
678
    def _put_on_disk(self, fullpath, tree):
 
679
        """See InventoryEntry._put_on_disk."""
 
680
        osutils.pumpfile(tree.get_file(self.file_id), file(fullpath, 'wb'))
 
681
        if tree.is_executable(self.file_id):
 
682
            os.chmod(fullpath, 0755)
 
683
 
 
684
    def _read_tree_state(self, path, work_tree):
 
685
        """See InventoryEntry._read_tree_state."""
 
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)
 
690
 
 
691
    def __repr__(self):
 
692
        return ("%s(%r, %r, parent_id=%r, sha1=%r, len=%s)"
 
693
                % (self.__class__.__name__,
 
694
                   self.file_id,
 
695
                   self.name,
 
696
                   self.parent_id,
 
697
                   self.text_sha1,
 
698
                   self.text_size))
 
699
 
 
700
    def _forget_tree_state(self):
 
701
        self.text_sha1 = None
 
702
 
 
703
    def snapshot(self, revision, path, previous_entries,
 
704
                 work_tree, commit_builder):
 
705
        """See InventoryEntry.snapshot."""
 
706
        # Note: We use a custom implementation of this method for files
 
707
        # because it's a performance critical part of commit.
 
708
 
 
709
        # If this is the initial commit for this file, we know the sha is
 
710
        # coming later so skip caluculating it now (in _read_tree_state())
 
711
        if len(previous_entries) == 0:
 
712
            self.executable = work_tree.is_executable(self.file_id, path=path)
 
713
        else:
 
714
            self._read_tree_state(path, work_tree)
 
715
 
 
716
        # If nothing is changed from the sole parent, there's nothing to do
 
717
        if len(previous_entries) == 1:
 
718
            parent_ie = previous_entries.values()[0]
 
719
            if self._unchanged(parent_ie):
 
720
                self.revision = parent_ie.revision
 
721
                return False
 
722
 
 
723
        # Add the file to the repository
 
724
        self.revision = revision
 
725
        def get_content_byte_lines():
 
726
            return work_tree.get_file(self.file_id, path).readlines()
 
727
        self.text_sha1, self.text_size = commit_builder.modified_file_text(
 
728
            self.file_id, previous_entries, get_content_byte_lines,
 
729
            self.text_sha1, self.text_size)
 
730
        return True
 
731
 
 
732
    def _unchanged(self, previous_ie):
 
733
        """See InventoryEntry._unchanged."""
 
734
        compatible = super(InventoryFile, self)._unchanged(previous_ie)
 
735
        if self.text_sha1 != previous_ie.text_sha1:
 
736
            compatible = False
 
737
        else:
 
738
            # FIXME: 20050930 probe for the text size when getting sha1
 
739
            # in _read_tree_state
 
740
            self.text_size = previous_ie.text_size
 
741
        if self.executable != previous_ie.executable:
 
742
            compatible = False
 
743
        return compatible
 
744
 
 
745
 
 
746
class InventoryLink(InventoryEntry):
 
747
    """A file in an inventory."""
 
748
 
 
749
    __slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
 
750
                 'text_id', 'parent_id', 'children', 'executable',
 
751
                 'revision', 'symlink_target', 'reference_revision']
 
752
 
 
753
    def _check(self, checker, rev_id, tree):
 
754
        """See InventoryEntry._check"""
 
755
        if self.text_sha1 is not None or self.text_size is not None or self.text_id is not None:
 
756
            raise BzrCheckError('symlink {%s} has text in revision {%s}'
 
757
                    % (self.file_id, rev_id))
 
758
        if self.symlink_target is None:
 
759
            raise BzrCheckError('symlink {%s} has no target in revision {%s}'
 
760
                    % (self.file_id, rev_id))
 
761
 
 
762
    def copy(self):
 
763
        other = InventoryLink(self.file_id, self.name, self.parent_id)
 
764
        other.symlink_target = self.symlink_target
 
765
        other.revision = self.revision
 
766
        return other
 
767
 
 
768
    def detect_changes(self, old_entry):
 
769
        """See InventoryEntry.detect_changes."""
 
770
        # FIXME: which _modified field should we use ? RBC 20051003
 
771
        text_modified = (self.symlink_target != old_entry.symlink_target)
 
772
        if text_modified:
 
773
            mutter("    symlink target changed")
 
774
        meta_modified = False
 
775
        return text_modified, meta_modified
 
776
 
 
777
    def _diff(self, text_diff, from_label, tree, to_label, to_entry, to_tree,
 
778
             output_to, reverse=False):
 
779
        """See InventoryEntry._diff."""
 
780
        from_text = self.symlink_target
 
781
        if to_entry is not None:
 
782
            to_text = to_entry.symlink_target
 
783
            if reverse:
 
784
                temp = from_text
 
785
                from_text = to_text
 
786
                to_text = temp
 
787
            print >>output_to, '=== target changed %r => %r' % (from_text, to_text)
 
788
        else:
 
789
            if not reverse:
 
790
                print >>output_to, '=== target was %r' % self.symlink_target
 
791
            else:
 
792
                print >>output_to, '=== target is %r' % self.symlink_target
 
793
 
 
794
    def __init__(self, file_id, name, parent_id):
 
795
        super(InventoryLink, self).__init__(file_id, name, parent_id)
 
796
        self.kind = 'symlink'
 
797
 
 
798
    def kind_character(self):
 
799
        """See InventoryEntry.kind_character."""
 
800
        return ''
 
801
 
 
802
    def _put_in_tar(self, item, tree):
 
803
        """See InventoryEntry._put_in_tar."""
 
804
        item.type = tarfile.SYMTYPE
 
805
        fileobj = None
 
806
        item.size = 0
 
807
        item.mode = 0755
 
808
        item.linkname = self.symlink_target
 
809
        return fileobj
 
810
 
 
811
    def _put_on_disk(self, fullpath, tree):
 
812
        """See InventoryEntry._put_on_disk."""
 
813
        try:
 
814
            os.symlink(self.symlink_target, fullpath)
 
815
        except OSError,e:
 
816
            raise BzrError("Failed to create symlink %r -> %r, error: %s" % (fullpath, self.symlink_target, e))
 
817
 
 
818
    def _read_tree_state(self, path, work_tree):
 
819
        """See InventoryEntry._read_tree_state."""
 
820
        self.symlink_target = work_tree.get_symlink_target(self.file_id)
 
821
 
 
822
    def _forget_tree_state(self):
 
823
        self.symlink_target = None
 
824
 
 
825
    def _unchanged(self, previous_ie):
 
826
        """See InventoryEntry._unchanged."""
 
827
        compatible = super(InventoryLink, self)._unchanged(previous_ie)
 
828
        if self.symlink_target != previous_ie.symlink_target:
 
829
            compatible = False
 
830
        return compatible
 
831
 
 
832
    def _snapshot_text(self, file_parents, work_tree, commit_builder):
 
833
        """See InventoryEntry._snapshot_text."""
 
834
        commit_builder.modified_link(
 
835
            self.file_id, file_parents, self.symlink_target)
 
836
        return True
 
837
 
 
838
 
 
839
class TreeReference(InventoryEntry):
 
840
    
 
841
    kind = 'tree-reference'
 
842
    
 
843
    def __init__(self, file_id, name, parent_id, revision=None,
 
844
                 reference_revision=None):
 
845
        InventoryEntry.__init__(self, file_id, name, parent_id)
 
846
        self.revision = revision
 
847
        self.reference_revision = reference_revision
 
848
 
 
849
    def copy(self):
 
850
        return TreeReference(self.file_id, self.name, self.parent_id,
 
851
                             self.revision, self.reference_revision)
 
852
 
 
853
    def _snapshot_text(self, file_parents, work_tree, commit_builder):
 
854
        commit_builder.modified_reference(self.file_id, file_parents)
 
855
        return True
 
856
 
 
857
    def _read_tree_state(self, path, work_tree):
 
858
        """Populate fields in the inventory entry from the given tree.
 
859
        """
 
860
        self.reference_revision = work_tree.get_reference_revision(
 
861
            self.file_id, path)
 
862
 
 
863
    def _forget_tree_state(self):
 
864
        self.reference_revision = None 
 
865
 
 
866
 
 
867
class Inventory(object):
 
868
    """Inventory of versioned files in a tree.
 
869
 
 
870
    This describes which file_id is present at each point in the tree,
 
871
    and possibly the SHA-1 or other information about the file.
 
872
    Entries can be looked up either by path or by file_id.
 
873
 
 
874
    The inventory represents a typical unix file tree, with
 
875
    directories containing files and subdirectories.  We never store
 
876
    the full path to a file, because renaming a directory implicitly
 
877
    moves all of its contents.  This class internally maintains a
 
878
    lookup tree that allows the children under a directory to be
 
879
    returned quickly.
 
880
 
 
881
    InventoryEntry objects must not be modified after they are
 
882
    inserted, other than through the Inventory API.
 
883
 
 
884
    >>> inv = Inventory()
 
885
    >>> inv.add(InventoryFile('123-123', 'hello.c', ROOT_ID))
 
886
    InventoryFile('123-123', 'hello.c', parent_id='TREE_ROOT', sha1=None, len=None)
 
887
    >>> inv['123-123'].name
 
888
    'hello.c'
 
889
 
 
890
    May be treated as an iterator or set to look up file ids:
 
891
    
 
892
    >>> bool(inv.path2id('hello.c'))
 
893
    True
 
894
    >>> '123-123' in inv
 
895
    True
 
896
 
 
897
    May also look up by name:
 
898
 
 
899
    >>> [x[0] for x in inv.iter_entries()]
 
900
    ['', u'hello.c']
 
901
    >>> inv = Inventory('TREE_ROOT-12345678-12345678')
 
902
    >>> inv.add(InventoryFile('123-123', 'hello.c', ROOT_ID))
 
903
    Traceback (most recent call last):
 
904
    BzrError: parent_id {TREE_ROOT} not in inventory
 
905
    >>> inv.add(InventoryFile('123-123', 'hello.c', 'TREE_ROOT-12345678-12345678'))
 
906
    InventoryFile('123-123', 'hello.c', parent_id='TREE_ROOT-12345678-12345678', sha1=None, len=None)
 
907
    """
 
908
    def __init__(self, root_id=ROOT_ID, revision_id=None):
 
909
        """Create or read an inventory.
 
910
 
 
911
        If a working directory is specified, the inventory is read
 
912
        from there.  If the file is specified, read from that. If not,
 
913
        the inventory is created empty.
 
914
 
 
915
        The inventory is created with a default root directory, with
 
916
        an id of None.
 
917
        """
 
918
        if root_id is not None:
 
919
            assert root_id.__class__ == str
 
920
            self._set_root(InventoryDirectory(root_id, u'', None))
 
921
        else:
 
922
            self.root = None
 
923
            self._byid = {}
 
924
        self.revision_id = revision_id
 
925
 
 
926
    def _set_root(self, ie):
 
927
        self.root = ie
 
928
        self._byid = {self.root.file_id: self.root}
 
929
 
 
930
    def copy(self):
 
931
        # TODO: jam 20051218 Should copy also copy the revision_id?
 
932
        entries = self.iter_entries()
 
933
        other = Inventory(entries.next()[1].file_id)
 
934
        # copy recursively so we know directories will be added before
 
935
        # their children.  There are more efficient ways than this...
 
936
        for path, entry in entries():
 
937
            other.add(entry.copy())
 
938
        return other
 
939
 
 
940
    def __iter__(self):
 
941
        return iter(self._byid)
 
942
 
 
943
    def __len__(self):
 
944
        """Returns number of entries."""
 
945
        return len(self._byid)
 
946
 
 
947
    def iter_entries(self, from_dir=None):
 
948
        """Return (path, entry) pairs, in order by name."""
 
949
        if from_dir is None:
 
950
            if self.root is None:
 
951
                return
 
952
            from_dir = self.root
 
953
            yield '', self.root
 
954
        elif isinstance(from_dir, basestring):
 
955
            from_dir = self._byid[from_dir]
 
956
            
 
957
        # unrolling the recursive called changed the time from
 
958
        # 440ms/663ms (inline/total) to 116ms/116ms
 
959
        children = from_dir.children.items()
 
960
        children.sort()
 
961
        children = collections.deque(children)
 
962
        stack = [(u'', children)]
 
963
        while stack:
 
964
            from_dir_relpath, children = stack[-1]
 
965
 
 
966
            while children:
 
967
                name, ie = children.popleft()
 
968
 
 
969
                # we know that from_dir_relpath never ends in a slash
 
970
                # and 'f' doesn't begin with one, we can do a string op, rather
 
971
                # than the checks of pathjoin(), though this means that all paths
 
972
                # start with a slash
 
973
                path = from_dir_relpath + '/' + name
 
974
 
 
975
                yield path[1:], ie
 
976
 
 
977
                if ie.kind != 'directory':
 
978
                    continue
 
979
 
 
980
                # But do this child first
 
981
                new_children = ie.children.items()
 
982
                new_children.sort()
 
983
                new_children = collections.deque(new_children)
 
984
                stack.append((path, new_children))
 
985
                # Break out of inner loop, so that we start outer loop with child
 
986
                break
 
987
            else:
 
988
                # if we finished all children, pop it off the stack
 
989
                stack.pop()
 
990
 
 
991
    def iter_entries_by_dir(self, from_dir=None, specific_file_ids=None):
 
992
        """Iterate over the entries in a directory first order.
 
993
 
 
994
        This returns all entries for a directory before returning
 
995
        the entries for children of a directory. This is not
 
996
        lexicographically sorted order, and is a hybrid between
 
997
        depth-first and breadth-first.
 
998
 
 
999
        :return: This yields (path, entry) pairs
 
1000
        """
 
1001
        if specific_file_ids:
 
1002
            safe = osutils.safe_file_id
 
1003
            specific_file_ids = set(safe(fid) for fid in specific_file_ids)
 
1004
        # TODO? Perhaps this should return the from_dir so that the root is
 
1005
        # yielded? or maybe an option?
 
1006
        if from_dir is None:
 
1007
            if self.root is None:
 
1008
                return
 
1009
            # Optimize a common case
 
1010
            if specific_file_ids is not None and len(specific_file_ids) == 1:
 
1011
                file_id = list(specific_file_ids)[0]
 
1012
                if file_id in self:
 
1013
                    yield self.id2path(file_id), self[file_id]
 
1014
                return 
 
1015
            from_dir = self.root
 
1016
            if (specific_file_ids is None or 
 
1017
                self.root.file_id in specific_file_ids):
 
1018
                yield u'', self.root
 
1019
        elif isinstance(from_dir, basestring):
 
1020
            from_dir = self._byid[from_dir]
 
1021
 
 
1022
        if specific_file_ids is not None:
 
1023
            # TODO: jam 20070302 This could really be done as a loop rather
 
1024
            #       than a bunch of recursive calls.
 
1025
            parents = set()
 
1026
            byid = self._byid
 
1027
            def add_ancestors(file_id):
 
1028
                if file_id not in byid:
 
1029
                    return
 
1030
                parent_id = byid[file_id].parent_id
 
1031
                if parent_id is None:
 
1032
                    return
 
1033
                if parent_id not in parents:
 
1034
                    parents.add(parent_id)
 
1035
                    add_ancestors(parent_id)
 
1036
            for file_id in specific_file_ids:
 
1037
                add_ancestors(file_id)
 
1038
        else:
 
1039
            parents = None
 
1040
            
 
1041
        stack = [(u'', from_dir)]
 
1042
        while stack:
 
1043
            cur_relpath, cur_dir = stack.pop()
 
1044
 
 
1045
            child_dirs = []
 
1046
            for child_name, child_ie in sorted(cur_dir.children.iteritems()):
 
1047
 
 
1048
                child_relpath = cur_relpath + child_name
 
1049
 
 
1050
                if (specific_file_ids is None or 
 
1051
                    child_ie.file_id in specific_file_ids):
 
1052
                    yield child_relpath, child_ie
 
1053
 
 
1054
                if child_ie.kind == 'directory':
 
1055
                    if parents is None or child_ie.file_id in parents:
 
1056
                        child_dirs.append((child_relpath+'/', child_ie))
 
1057
            stack.extend(reversed(child_dirs))
 
1058
 
 
1059
    def make_entry(self, kind, name, parent_id, file_id=None):
 
1060
        """Simple thunk to bzrlib.inventory.make_entry."""
 
1061
        return make_entry(kind, name, parent_id, file_id)
 
1062
 
 
1063
    def entries(self):
 
1064
        """Return list of (path, ie) for all entries except the root.
 
1065
 
 
1066
        This may be faster than iter_entries.
 
1067
        """
 
1068
        accum = []
 
1069
        def descend(dir_ie, dir_path):
 
1070
            kids = dir_ie.children.items()
 
1071
            kids.sort()
 
1072
            for name, ie in kids:
 
1073
                child_path = osutils.pathjoin(dir_path, name)
 
1074
                accum.append((child_path, ie))
 
1075
                if ie.kind == 'directory':
 
1076
                    descend(ie, child_path)
 
1077
 
 
1078
        descend(self.root, u'')
 
1079
        return accum
 
1080
 
 
1081
    def directories(self):
 
1082
        """Return (path, entry) pairs for all directories, including the root.
 
1083
        """
 
1084
        accum = []
 
1085
        def descend(parent_ie, parent_path):
 
1086
            accum.append((parent_path, parent_ie))
 
1087
            
 
1088
            kids = [(ie.name, ie) for ie in parent_ie.children.itervalues() if ie.kind == 'directory']
 
1089
            kids.sort()
 
1090
 
 
1091
            for name, child_ie in kids:
 
1092
                child_path = osutils.pathjoin(parent_path, name)
 
1093
                descend(child_ie, child_path)
 
1094
        descend(self.root, u'')
 
1095
        return accum
 
1096
        
 
1097
    def __contains__(self, file_id):
 
1098
        """True if this entry contains a file with given id.
 
1099
 
 
1100
        >>> inv = Inventory()
 
1101
        >>> inv.add(InventoryFile('123', 'foo.c', ROOT_ID))
 
1102
        InventoryFile('123', 'foo.c', parent_id='TREE_ROOT', sha1=None, len=None)
 
1103
        >>> '123' in inv
 
1104
        True
 
1105
        >>> '456' in inv
 
1106
        False
 
1107
        """
 
1108
        file_id = osutils.safe_file_id(file_id)
 
1109
        return (file_id in self._byid)
 
1110
 
 
1111
    def __getitem__(self, file_id):
 
1112
        """Return the entry for given file_id.
 
1113
 
 
1114
        >>> inv = Inventory()
 
1115
        >>> inv.add(InventoryFile('123123', 'hello.c', ROOT_ID))
 
1116
        InventoryFile('123123', 'hello.c', parent_id='TREE_ROOT', sha1=None, len=None)
 
1117
        >>> inv['123123'].name
 
1118
        'hello.c'
 
1119
        """
 
1120
        file_id = osutils.safe_file_id(file_id)
 
1121
        try:
 
1122
            return self._byid[file_id]
 
1123
        except KeyError:
 
1124
            # really we're passing an inventory, not a tree...
 
1125
            raise errors.NoSuchId(self, file_id)
 
1126
 
 
1127
    def get_file_kind(self, file_id):
 
1128
        file_id = osutils.safe_file_id(file_id)
 
1129
        return self._byid[file_id].kind
 
1130
 
 
1131
    def get_child(self, parent_id, filename):
 
1132
        parent_id = osutils.safe_file_id(parent_id)
 
1133
        return self[parent_id].children.get(filename)
 
1134
 
 
1135
    def _add_child(self, entry):
 
1136
        """Add an entry to the inventory, without adding it to its parent"""
 
1137
        if entry.file_id in self._byid:
 
1138
            raise BzrError("inventory already contains entry with id {%s}" %
 
1139
                           entry.file_id)
 
1140
        self._byid[entry.file_id] = entry
 
1141
        for child in getattr(entry, 'children', {}).itervalues():
 
1142
            self._add_child(child)
 
1143
        return entry
 
1144
 
 
1145
    def add(self, entry):
 
1146
        """Add entry to inventory.
 
1147
 
 
1148
        To add  a file to a branch ready to be committed, use Branch.add,
 
1149
        which calls this.
 
1150
 
 
1151
        Returns the new entry object.
 
1152
        """
 
1153
        if entry.file_id in self._byid:
 
1154
            raise errors.DuplicateFileId(entry.file_id,
 
1155
                                         self._byid[entry.file_id])
 
1156
 
 
1157
        if entry.parent_id is None:
 
1158
            assert self.root is None and len(self._byid) == 0
 
1159
            self.root = entry
 
1160
        else:
 
1161
            try:
 
1162
                parent = self._byid[entry.parent_id]
 
1163
            except KeyError:
 
1164
                raise BzrError("parent_id {%s} not in inventory" %
 
1165
                               entry.parent_id)
 
1166
 
 
1167
            if entry.name in parent.children:
 
1168
                raise BzrError("%s is already versioned" %
 
1169
                        osutils.pathjoin(self.id2path(parent.file_id),
 
1170
                        entry.name).encode('utf-8'))
 
1171
            parent.children[entry.name] = entry
 
1172
        return self._add_child(entry)
 
1173
 
 
1174
    def add_path(self, relpath, kind, file_id=None, parent_id=None):
 
1175
        """Add entry from a path.
 
1176
 
 
1177
        The immediate parent must already be versioned.
 
1178
 
 
1179
        Returns the new entry object."""
 
1180
        
 
1181
        parts = osutils.splitpath(relpath)
 
1182
 
 
1183
        if len(parts) == 0:
 
1184
            if file_id is None:
 
1185
                file_id = generate_ids.gen_root_id()
 
1186
            else:
 
1187
                file_id = osutils.safe_file_id(file_id)
 
1188
            self.root = InventoryDirectory(file_id, '', None)
 
1189
            self._byid = {self.root.file_id: self.root}
 
1190
            return self.root
 
1191
        else:
 
1192
            parent_path = parts[:-1]
 
1193
            parent_id = self.path2id(parent_path)
 
1194
            if parent_id is None:
 
1195
                raise errors.NotVersionedError(path=parent_path)
 
1196
        ie = make_entry(kind, parts[-1], parent_id, file_id)
 
1197
        return self.add(ie)
 
1198
 
 
1199
    def __delitem__(self, file_id):
 
1200
        """Remove entry by id.
 
1201
 
 
1202
        >>> inv = Inventory()
 
1203
        >>> inv.add(InventoryFile('123', 'foo.c', ROOT_ID))
 
1204
        InventoryFile('123', 'foo.c', parent_id='TREE_ROOT', sha1=None, len=None)
 
1205
        >>> '123' in inv
 
1206
        True
 
1207
        >>> del inv['123']
 
1208
        >>> '123' in inv
 
1209
        False
 
1210
        """
 
1211
        file_id = osutils.safe_file_id(file_id)
 
1212
        ie = self[file_id]
 
1213
 
 
1214
        assert ie.parent_id is None or \
 
1215
            self[ie.parent_id].children[ie.name] == ie
 
1216
        
 
1217
        del self._byid[file_id]
 
1218
        if ie.parent_id is not None:
 
1219
            del self[ie.parent_id].children[ie.name]
 
1220
 
 
1221
    def __eq__(self, other):
 
1222
        """Compare two sets by comparing their contents.
 
1223
 
 
1224
        >>> i1 = Inventory()
 
1225
        >>> i2 = Inventory()
 
1226
        >>> i1 == i2
 
1227
        True
 
1228
        >>> i1.add(InventoryFile('123', 'foo', ROOT_ID))
 
1229
        InventoryFile('123', 'foo', parent_id='TREE_ROOT', sha1=None, len=None)
 
1230
        >>> i1 == i2
 
1231
        False
 
1232
        >>> i2.add(InventoryFile('123', 'foo', ROOT_ID))
 
1233
        InventoryFile('123', 'foo', parent_id='TREE_ROOT', sha1=None, len=None)
 
1234
        >>> i1 == i2
 
1235
        True
 
1236
        """
 
1237
        if not isinstance(other, Inventory):
 
1238
            return NotImplemented
 
1239
 
 
1240
        return self._byid == other._byid
 
1241
 
 
1242
    def __ne__(self, other):
 
1243
        return not self.__eq__(other)
 
1244
 
 
1245
    def __hash__(self):
 
1246
        raise ValueError('not hashable')
 
1247
 
 
1248
    def _iter_file_id_parents(self, file_id):
 
1249
        """Yield the parents of file_id up to the root."""
 
1250
        file_id = osutils.safe_file_id(file_id)
 
1251
        while file_id is not None:
 
1252
            try:
 
1253
                ie = self._byid[file_id]
 
1254
            except KeyError:
 
1255
                raise errors.NoSuchId(tree=None, file_id=file_id)
 
1256
            yield ie
 
1257
            file_id = ie.parent_id
 
1258
 
 
1259
    def get_idpath(self, file_id):
 
1260
        """Return a list of file_ids for the path to an entry.
 
1261
 
 
1262
        The list contains one element for each directory followed by
 
1263
        the id of the file itself.  So the length of the returned list
 
1264
        is equal to the depth of the file in the tree, counting the
 
1265
        root directory as depth 1.
 
1266
        """
 
1267
        file_id = osutils.safe_file_id(file_id)
 
1268
        p = []
 
1269
        for parent in self._iter_file_id_parents(file_id):
 
1270
            p.insert(0, parent.file_id)
 
1271
        return p
 
1272
 
 
1273
    def id2path(self, file_id):
 
1274
        """Return as a string the path to file_id.
 
1275
        
 
1276
        >>> i = Inventory()
 
1277
        >>> e = i.add(InventoryDirectory('src-id', 'src', ROOT_ID))
 
1278
        >>> e = i.add(InventoryFile('foo-id', 'foo.c', parent_id='src-id'))
 
1279
        >>> print i.id2path('foo-id')
 
1280
        src/foo.c
 
1281
        """
 
1282
        file_id = osutils.safe_file_id(file_id)
 
1283
        # get all names, skipping root
 
1284
        return '/'.join(reversed(
 
1285
            [parent.name for parent in 
 
1286
             self._iter_file_id_parents(file_id)][:-1]))
 
1287
            
 
1288
    def path2id(self, name):
 
1289
        """Walk down through directories to return entry of last component.
 
1290
 
 
1291
        names may be either a list of path components, or a single
 
1292
        string, in which case it is automatically split.
 
1293
 
 
1294
        This returns the entry of the last component in the path,
 
1295
        which may be either a file or a directory.
 
1296
 
 
1297
        Returns None IFF the path is not found.
 
1298
        """
 
1299
        if isinstance(name, basestring):
 
1300
            name = osutils.splitpath(name)
 
1301
 
 
1302
        # mutter("lookup path %r" % name)
 
1303
 
 
1304
        parent = self.root
 
1305
        if parent is None:
 
1306
            return None
 
1307
        for f in name:
 
1308
            try:
 
1309
                children = getattr(parent, 'children', None)
 
1310
                if children is None:
 
1311
                    return None
 
1312
                cie = children[f]
 
1313
                assert cie.name == f
 
1314
                assert cie.parent_id == parent.file_id
 
1315
                parent = cie
 
1316
            except KeyError:
 
1317
                # or raise an error?
 
1318
                return None
 
1319
 
 
1320
        return parent.file_id
 
1321
 
 
1322
    def has_filename(self, names):
 
1323
        return bool(self.path2id(names))
 
1324
 
 
1325
    def has_id(self, file_id):
 
1326
        file_id = osutils.safe_file_id(file_id)
 
1327
        return (file_id in self._byid)
 
1328
 
 
1329
    def remove_recursive_id(self, file_id):
 
1330
        """Remove file_id, and children, from the inventory.
 
1331
        
 
1332
        :param file_id: A file_id to remove.
 
1333
        """
 
1334
        file_id = osutils.safe_file_id(file_id)
 
1335
        to_find_delete = [self._byid[file_id]]
 
1336
        to_delete = []
 
1337
        while to_find_delete:
 
1338
            ie = to_find_delete.pop()
 
1339
            to_delete.append(ie.file_id)
 
1340
            if ie.kind == 'directory':
 
1341
                to_find_delete.extend(ie.children.values())
 
1342
        for file_id in reversed(to_delete):
 
1343
            ie = self[file_id]
 
1344
            del self._byid[file_id]
 
1345
        if ie.parent_id is not None:
 
1346
            del self[ie.parent_id].children[ie.name]
 
1347
        else:
 
1348
            self.root = None
 
1349
 
 
1350
    def rename(self, file_id, new_parent_id, new_name):
 
1351
        """Move a file within the inventory.
 
1352
 
 
1353
        This can change either the name, or the parent, or both.
 
1354
 
 
1355
        This does not move the working file.
 
1356
        """
 
1357
        file_id = osutils.safe_file_id(file_id)
 
1358
        if not is_valid_name(new_name):
 
1359
            raise BzrError("not an acceptable filename: %r" % new_name)
 
1360
 
 
1361
        new_parent = self._byid[new_parent_id]
 
1362
        if new_name in new_parent.children:
 
1363
            raise BzrError("%r already exists in %r" % (new_name, self.id2path(new_parent_id)))
 
1364
 
 
1365
        new_parent_idpath = self.get_idpath(new_parent_id)
 
1366
        if file_id in new_parent_idpath:
 
1367
            raise BzrError("cannot move directory %r into a subdirectory of itself, %r"
 
1368
                    % (self.id2path(file_id), self.id2path(new_parent_id)))
 
1369
 
 
1370
        file_ie = self._byid[file_id]
 
1371
        old_parent = self._byid[file_ie.parent_id]
 
1372
 
 
1373
        # TODO: Don't leave things messed up if this fails
 
1374
 
 
1375
        del old_parent.children[file_ie.name]
 
1376
        new_parent.children[new_name] = file_ie
 
1377
        
 
1378
        file_ie.name = new_name
 
1379
        file_ie.parent_id = new_parent_id
 
1380
 
 
1381
    def is_root(self, file_id):
 
1382
        file_id = osutils.safe_file_id(file_id)
 
1383
        return self.root is not None and file_id == self.root.file_id
 
1384
 
 
1385
 
 
1386
entry_factory = {
 
1387
    'directory': InventoryDirectory,
 
1388
    'file': InventoryFile,
 
1389
    'symlink': InventoryLink,
 
1390
    'tree-reference': TreeReference
 
1391
}
 
1392
 
 
1393
def make_entry(kind, name, parent_id, file_id=None):
 
1394
    """Create an inventory entry.
 
1395
 
 
1396
    :param kind: the type of inventory entry to create.
 
1397
    :param name: the basename of the entry.
 
1398
    :param parent_id: the parent_id of the entry.
 
1399
    :param file_id: the file_id to use. if None, one will be created.
 
1400
    """
 
1401
    if file_id is None:
 
1402
        file_id = generate_ids.gen_file_id(name)
 
1403
    else:
 
1404
        file_id = osutils.safe_file_id(file_id)
 
1405
 
 
1406
    #------- This has been copied to bzrlib.dirstate.DirState.add, please
 
1407
    # keep them synchronised.
 
1408
    # we dont import normalized_filename directly because we want to be
 
1409
    # able to change the implementation at runtime for tests.
 
1410
    norm_name, can_access = osutils.normalized_filename(name)
 
1411
    if norm_name != name:
 
1412
        if can_access:
 
1413
            name = norm_name
 
1414
        else:
 
1415
            # TODO: jam 20060701 This would probably be more useful
 
1416
            #       if the error was raised with the full path
 
1417
            raise errors.InvalidNormalization(name)
 
1418
 
 
1419
    try:
 
1420
        factory = entry_factory[kind]
 
1421
    except KeyError:
 
1422
        raise BzrError("unknown kind %r" % kind)
 
1423
    return factory(file_id, name, parent_id)
 
1424
 
 
1425
 
 
1426
_NAME_RE = None
 
1427
 
 
1428
def is_valid_name(name):
 
1429
    global _NAME_RE
 
1430
    if _NAME_RE is None:
 
1431
        _NAME_RE = re.compile(r'^[^/\\]+$')
 
1432
        
 
1433
    return bool(_NAME_RE.match(name))