/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

  • Committer: Robert Collins
  • Date: 2005-10-03 05:54:35 UTC
  • mto: (1393.1.30)
  • mto: This revision was merged to the branch mainline in revision 1400.
  • Revision ID: robertc@robertcollins.net-20051003055434-c8ebd30d1de10247
move exporting functionality into inventory.py - uncovers bug in symlink support

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
 
 
18
# TODO: Maybe also keep the full path of the entry, and the children?
 
19
# But those depend on its position within a particular inventory, and
 
20
# it would be nice not to need to hold the backpointer here.
 
21
 
 
22
# TODO: Perhaps split InventoryEntry into subclasses for files,
 
23
# directories, etc etc.
 
24
 
 
25
 
18
26
# This should really be an id randomly assigned when the tree is
19
27
# created, but it's not for now.
20
28
ROOT_ID = "TREE_ROOT"
21
29
 
22
30
 
23
 
import sys, os.path, types, re
 
31
import os.path
 
32
import re
 
33
import sys
 
34
import tarfile
 
35
import types
24
36
 
25
37
import bzrlib
26
38
from bzrlib.errors import BzrError, BzrCheckError
27
39
 
28
 
from bzrlib.osutils import uuid, quotefn, splitpath, joinpath, appendpath
 
40
from bzrlib.osutils import (pumpfile, quotefn, splitpath, joinpath,
 
41
                            appendpath, sha_strings)
29
42
from bzrlib.trace import mutter
30
43
from bzrlib.errors import NotVersionedError
31
 
        
 
44
 
32
45
 
33
46
class InventoryEntry(object):
34
47
    """Description of a versioned file.
36
49
    An InventoryEntry has the following fields, which are also
37
50
    present in the XML inventory-entry element:
38
51
 
39
 
    * *file_id*
40
 
    * *name*: (only the basename within the directory, must not
41
 
      contain slashes)
42
 
    * *kind*: "directory" or "file"
43
 
    * *directory_id*: (if absent/null means the branch root directory)
44
 
    * *text_sha1*: only for files
45
 
    * *text_size*: in bytes, only for files 
46
 
    * *text_id*: identifier for the text version, only for files
47
 
 
48
 
    InventoryEntries can also exist inside a WorkingTree
49
 
    inventory, in which case they are not yet bound to a
50
 
    particular revision of the file.  In that case the text_sha1,
51
 
    text_size and text_id are absent.
52
 
 
 
52
    file_id
 
53
 
 
54
    name
 
55
        (within the parent directory)
 
56
 
 
57
    kind
 
58
        'directory' or 'file' or 'symlink'
 
59
 
 
60
    parent_id
 
61
        file_id of the parent directory, or ROOT_ID
 
62
 
 
63
    revision
 
64
        the revision_id in which this variation of this file was 
 
65
        introduced.
 
66
 
 
67
    executable
 
68
        Indicates that this file should be executable on systems
 
69
        that support it.
 
70
 
 
71
    text_sha1
 
72
        sha-1 of the text of the file
 
73
        
 
74
    text_size
 
75
        size in bytes of the text of the file
 
76
        
 
77
    (reading a version 4 tree created a text_id field.)
53
78
 
54
79
    >>> i = Inventory()
55
80
    >>> i.path2id('')
56
81
    'TREE_ROOT'
57
82
    >>> i.add(InventoryEntry('123', 'src', 'directory', ROOT_ID))
 
83
    InventoryEntry('123', 'src', kind='directory', parent_id='TREE_ROOT')
58
84
    >>> i.add(InventoryEntry('2323', 'hello.c', 'file', parent_id='123'))
 
85
    InventoryEntry('2323', 'hello.c', kind='file', parent_id='123')
59
86
    >>> for j in i.iter_entries():
60
87
    ...   print j
61
88
    ... 
66
93
    ...
67
94
    BzrError: inventory already contains entry with id {2323}
68
95
    >>> i.add(InventoryEntry('2324', 'bye.c', 'file', '123'))
 
96
    InventoryEntry('2324', 'bye.c', kind='file', parent_id='123')
69
97
    >>> i.add(InventoryEntry('2325', 'wibble', 'directory', '123'))
 
98
    InventoryEntry('2325', 'wibble', kind='directory', parent_id='123')
70
99
    >>> i.path2id('src/wibble')
71
100
    '2325'
72
101
    >>> '2325' in i
73
102
    True
74
103
    >>> i.add(InventoryEntry('2326', 'wibble.c', 'file', '2325'))
 
104
    InventoryEntry('2326', 'wibble.c', kind='file', parent_id='2325')
75
105
    >>> i['2326']
76
106
    InventoryEntry('2326', 'wibble.c', kind='file', parent_id='2325')
77
 
    >>> for j in i.iter_entries():
78
 
    ...     print j[0]
79
 
    ...     assert i.path2id(j[0])
 
107
    >>> for path, entry in i.iter_entries():
 
108
    ...     print path.replace('\\\\', '/')     # for win32 os.sep
 
109
    ...     assert i.path2id(path)
80
110
    ... 
81
111
    src
82
112
    src/bye.c
83
113
    src/hello.c
84
114
    src/wibble
85
115
    src/wibble/wibble.c
86
 
    >>> i.id2path('2326')
 
116
    >>> i.id2path('2326').replace('\\\\', '/')
87
117
    'src/wibble/wibble.c'
88
 
 
89
 
    TODO: Maybe also keep the full path of the entry, and the children?
90
 
           But those depend on its position within a particular inventory, and
91
 
           it would be nice not to need to hold the backpointer here.
92
118
    """
93
 
 
94
 
    # TODO: split InventoryEntry into subclasses for files,
95
 
    # directories, etc etc.
96
 
 
 
119
    
97
120
    __slots__ = ['text_sha1', 'text_size', 'file_id', 'name', 'kind',
98
 
                 'text_id', 'parent_id', 'children', ]
 
121
                 'text_id', 'parent_id', 'children', 'executable', 
 
122
                 'revision', 'symlink_target']
 
123
 
 
124
    def _add_text_to_weave(self, new_lines, parents, weave_store):
 
125
        weave_store.add_text(self.file_id, self.revision, new_lines, parents)
 
126
 
 
127
    def detect_changes(self, old_entry):
 
128
        """Return a (text_modified, meta_modified) from this to old_entry.
 
129
        
 
130
        _read_tree_state must have been called on self and old_entry prior to 
 
131
        calling detect_changes.
 
132
        """
 
133
        if self.kind == 'file':
 
134
            assert self.text_sha1 != None
 
135
            assert old_entry.text_sha1 != None
 
136
            text_modified = (self.text_sha1 != old_entry.text_sha1)
 
137
            meta_modified = (self.executable != old_entry.executable)
 
138
        elif self.kind == 'symlink':
 
139
            # FIXME: which _modified field should we use ? RBC 20051003
 
140
            text_modified = (self.symlink_target != old_entry.symlink_target)
 
141
            if text_modified:
 
142
                mutter("    symlink target changed")
 
143
            meta_modified = False
 
144
        else:
 
145
            text_modified = False
 
146
            meta_modified = False
 
147
        return text_modified, meta_modified
 
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 from this to to_entry.
 
152
 
 
153
        text_diff will be used for textual difference calculation.
 
154
        """
 
155
        self._read_tree_state(tree.id2path(self.file_id), tree)
 
156
        if to_entry:
 
157
            # cannot diff from one kind to another - you must do a removal
 
158
            # and an addif they do not match.
 
159
            assert self.kind == to_entry.kind
 
160
            to_entry._read_tree_state(to_tree.id2path(to_entry.file_id),
 
161
                                      to_tree)
 
162
        if self.kind == 'file':
 
163
            from_text = tree.get_file(self.file_id).readlines()
 
164
            if to_entry:
 
165
                to_text = to_tree.get_file(to_entry.file_id).readlines()
 
166
            else:
 
167
                to_text = []
 
168
            if not reverse:
 
169
                text_diff(from_label, from_text,
 
170
                          to_label, to_text, output_to)
 
171
            else:
 
172
                text_diff(to_label, to_text,
 
173
                          from_label, from_text, output_to)
 
174
        elif self.kind == 'symlink':
 
175
            from_text = self.symlink_target
 
176
            if to_entry is not None:
 
177
                to_text = to_entry.symlink_target
 
178
                if reverse:
 
179
                    temp = from_text
 
180
                    from_text = to_text
 
181
                    to_text = temp
 
182
                print >>output_to, '=== target changed %r => %r' % (from_text, to_text)
 
183
            else:
 
184
                if not reverse:
 
185
                    print >>output_to, '=== target was %r' % self.symlink_target
 
186
                else:
 
187
                    print >>output_to, '=== target is %r' % self.symlink_target
 
188
 
 
189
    def get_tar_item(self, root, dp, now, tree):
 
190
        item = tarfile.TarInfo(os.path.join(root, dp))
 
191
        # TODO: would be cool to actually set it to the timestamp of the
 
192
        # revision it was last changed
 
193
        item.mtime = now
 
194
        if self.kind == 'directory':
 
195
            item.type = tarfile.DIRTYPE
 
196
            fileobj = None
 
197
            item.name += '/'
 
198
            item.size = 0
 
199
            item.mode = 0755
 
200
        elif self.kind == 'file':
 
201
            item.type = tarfile.REGTYPE
 
202
            fileobj = tree.get_file(self.file_id)
 
203
            item.size = self.text_size
 
204
            if tree.is_executable(self.file_id):
 
205
                item.mode = 0755
 
206
            else:
 
207
                item.mode = 0644
 
208
        else:
 
209
            raise BzrError("don't know how to export {%s} of kind %r" %
 
210
                    (self.file_id, self.kind))
 
211
        return item, fileobj
 
212
 
 
213
    def has_text(self):
 
214
        """Return true if the object this entry represents has textual data.
 
215
 
 
216
        Note that textual data includes binary content.
 
217
        """
 
218
        if self.kind =='file':
 
219
            return True
 
220
        else:
 
221
            return False
99
222
 
100
223
    def __init__(self, file_id, name, kind, parent_id, text_id=None):
101
224
        """Create an InventoryEntry
112
235
        Traceback (most recent call last):
113
236
        BzrCheckError: InventoryEntry name 'src/hello.c' is invalid
114
237
        """
 
238
        assert isinstance(name, basestring), name
115
239
        if '/' in name or '\\' in name:
116
240
            raise BzrCheckError('InventoryEntry name %r is invalid' % name)
117
241
        
 
242
        self.executable = False
 
243
        self.revision = None
118
244
        self.text_sha1 = None
119
245
        self.text_size = None
120
 
    
121
246
        self.file_id = file_id
122
247
        self.name = name
123
248
        self.kind = kind
124
249
        self.text_id = text_id
125
250
        self.parent_id = parent_id
 
251
        self.symlink_target = None
126
252
        if kind == 'directory':
127
253
            self.children = {}
128
254
        elif kind == 'file':
129
255
            pass
 
256
        elif kind == 'symlink':
 
257
            pass
130
258
        else:
131
259
            raise BzrError("unhandled entry kind %r" % kind)
132
260
 
133
 
 
 
261
    def kind_character(self):
 
262
        """Return a short kind indicator useful for appending to names."""
 
263
        if self.kind == 'directory':
 
264
            return '/'
 
265
        if self.kind == 'file':
 
266
            return ''
 
267
        if self.kind == 'symlink':
 
268
            return ''
 
269
        raise RuntimeError('unreachable code')
 
270
 
 
271
    known_kinds = ('file', 'directory', 'symlink', 'root_directory')
 
272
 
 
273
    def put_on_disk(self, dest, dp, tree):
 
274
        """Create a representation of self on disk in the prefix dest."""
 
275
        fullpath = appendpath(dest, dp)
 
276
        if self.kind == 'directory':
 
277
            os.mkdir(fullpath)
 
278
        elif self.kind == 'file':
 
279
            pumpfile(tree.get_file(self.file_id), file(fullpath, 'wb'))
 
280
            if tree.is_executable(self.file_id):
 
281
                os.chmod(fullpath, 0755)
 
282
        elif self.kind == 'symlink':
 
283
            try:
 
284
                os.symlink(self.symlink_target, fullpath)
 
285
            except OSError,e:
 
286
                raise BzrError("Failed to create symlink %r -> %r, error: %s" % (fullpath, self.symlink_target, e))
 
287
        else:
 
288
            raise BzrError("don't know how to export {%s} of kind %r" % (self.file_id, self.kind))
 
289
        mutter("  export {%s} kind %s to %s" % (self.file_id, self.kind, fullpath))
134
290
 
135
291
    def sorted_children(self):
136
292
        l = self.children.items()
137
293
        l.sort()
138
294
        return l
139
295
 
 
296
    @staticmethod
 
297
    def versionable_kind(kind):
 
298
        return kind in ('file', 'directory', 'symlink')
 
299
 
 
300
    def check(self, checker, rev_id, inv, tree):
 
301
        if self.parent_id != None:
 
302
            if not inv.has_id(self.parent_id):
 
303
                raise BzrCheckError('missing parent {%s} in inventory for revision {%s}'
 
304
                        % (self.parent_id, rev_id))
 
305
        if self.kind == 'file':
 
306
            revision = self.revision
 
307
            t = (self.file_id, revision)
 
308
            if t in checker.checked_texts:
 
309
                prev_sha = checker.checked_texts[t] 
 
310
                if prev_sha != self.text_sha1:
 
311
                    raise BzrCheckError('mismatched sha1 on {%s} in {%s}' %
 
312
                                        (self.file_id, rev_id))
 
313
                else:
 
314
                    checker.repeated_text_cnt += 1
 
315
                    return
 
316
            mutter('check version {%s} of {%s}', rev_id, self.file_id)
 
317
            file_lines = tree.get_file_lines(self.file_id)
 
318
            checker.checked_text_cnt += 1 
 
319
            if self.text_size != sum(map(len, file_lines)):
 
320
                raise BzrCheckError('text {%s} wrong size' % self.text_id)
 
321
            if self.text_sha1 != sha_strings(file_lines):
 
322
                raise BzrCheckError('text {%s} wrong sha1' % self.text_id)
 
323
            checker.checked_texts[t] = self.text_sha1
 
324
        elif self.kind == 'directory':
 
325
            if self.text_sha1 != None or self.text_size != None or self.text_id != None:
 
326
                raise BzrCheckError('directory {%s} has text in revision {%s}'
 
327
                        % (self.file_id, rev_id))
 
328
        elif self.kind == 'root_directory':
 
329
            pass
 
330
        elif self.kind == 'symlink':
 
331
            if self.text_sha1 != None or self.text_size != None or self.text_id != None:
 
332
                raise BzrCheckError('symlink {%s} has text in revision {%s}'
 
333
                        % (self.file_id, rev_id))
 
334
            if self.symlink_target == None:
 
335
                raise BzrCheckError('symlink {%s} has no target in revision {%s}'
 
336
                        % (self.file_id, rev_id))
 
337
        else:
 
338
            raise BzrCheckError('unknown entry kind %r in revision {%s}' % 
 
339
                                (self.kind, rev_id))
 
340
 
140
341
 
141
342
    def copy(self):
142
343
        other = InventoryEntry(self.file_id, self.name, self.kind,
143
 
                               self.parent_id, text_id=self.text_id)
 
344
                               self.parent_id)
 
345
        other.executable = self.executable
 
346
        other.text_id = self.text_id
144
347
        other.text_sha1 = self.text_sha1
145
348
        other.text_size = self.text_size
 
349
        other.symlink_target = self.symlink_target
 
350
        other.revision = self.revision
146
351
        # note that children are *not* copied; they're pulled across when
147
352
        # others are added
148
353
        return other
149
354
 
 
355
    def _get_snapshot_change(self, previous_entries):
 
356
        if len(previous_entries) > 1:
 
357
            return 'merged'
 
358
        elif len(previous_entries) == 0:
 
359
            return 'added'
 
360
        else:
 
361
            return 'modified/renamed/reparented'
150
362
 
151
363
    def __repr__(self):
152
364
        return ("%s(%r, %r, kind=%r, parent_id=%r)"
156
368
                   self.kind,
157
369
                   self.parent_id))
158
370
 
159
 
    
160
 
    def to_element(self):
161
 
        """Convert to XML element"""
162
 
        from bzrlib.xml import Element
163
 
        
164
 
        e = Element('entry')
165
 
 
166
 
        e.set('name', self.name)
167
 
        e.set('file_id', self.file_id)
168
 
        e.set('kind', self.kind)
169
 
 
170
 
        if self.text_size != None:
171
 
            e.set('text_size', '%d' % self.text_size)
172
 
            
173
 
        for f in ['text_id', 'text_sha1']:
174
 
            v = getattr(self, f)
175
 
            if v != None:
176
 
                e.set(f, v)
177
 
 
178
 
        # to be conservative, we don't externalize the root pointers
179
 
        # for now, leaving them as null in the xml form.  in a future
180
 
        # version it will be implied by nested elements.
181
 
        if self.parent_id != ROOT_ID:
182
 
            assert isinstance(self.parent_id, basestring)
183
 
            e.set('parent_id', self.parent_id)
184
 
 
185
 
        e.tail = '\n'
186
 
            
187
 
        return e
188
 
 
189
 
 
190
 
    def from_element(cls, elt):
191
 
        assert elt.tag == 'entry'
192
 
 
193
 
        ## original format inventories don't have a parent_id for
194
 
        ## nodes in the root directory, but it's cleaner to use one
195
 
        ## internally.
196
 
        parent_id = elt.get('parent_id')
197
 
        if parent_id == None:
198
 
            parent_id = ROOT_ID
199
 
 
200
 
        self = cls(elt.get('file_id'), elt.get('name'), elt.get('kind'), parent_id)
201
 
        self.text_id = elt.get('text_id')
202
 
        self.text_sha1 = elt.get('text_sha1')
203
 
        
204
 
        ## mutter("read inventoryentry: %r" % (elt.attrib))
205
 
 
206
 
        v = elt.get('text_size')
207
 
        self.text_size = v and int(v)
208
 
 
209
 
        return self
210
 
            
211
 
 
212
 
    from_element = classmethod(from_element)
 
371
    def snapshot(self, revision, path, previous_entries, work_tree, 
 
372
                 weave_store):
 
373
        """Make a snapshot of this entry.
 
374
        
 
375
        This means that all its fields are populated, that it has its
 
376
        text stored in the text store or weave.
 
377
        """
 
378
        mutter('new parents of %s are %r', path, previous_entries)
 
379
        self._read_tree_state(path, work_tree)
 
380
        if len(previous_entries) == 1:
 
381
            # cannot be unchanged unless there is only one parent file rev.
 
382
            parent_ie = previous_entries.values()[0]
 
383
            if self._unchanged(path, parent_ie, work_tree):
 
384
                mutter("found unchanged entry")
 
385
                self.revision = parent_ie.revision
 
386
                return "unchanged"
 
387
        mutter('new revision for {%s}', self.file_id)
 
388
        self.revision = revision
 
389
        change = self._get_snapshot_change(previous_entries)
 
390
        if self.kind != 'file':
 
391
            return change
 
392
        self._snapshot_text(previous_entries, work_tree, weave_store)
 
393
        return change
 
394
 
 
395
    def _snapshot_text(self, file_parents, work_tree, weave_store): 
 
396
        mutter('storing file {%s} in revision {%s}',
 
397
               self.file_id, self.revision)
 
398
        # special case to avoid diffing on renames or 
 
399
        # reparenting
 
400
        if (len(file_parents) == 1
 
401
            and self.text_sha1 == file_parents.values()[0].text_sha1
 
402
            and self.text_size == file_parents.values()[0].text_size):
 
403
            previous_ie = file_parents.values()[0]
 
404
            weave_store.add_identical_text(
 
405
                self.file_id, previous_ie.revision, 
 
406
                self.revision, file_parents)
 
407
        else:
 
408
            new_lines = work_tree.get_file(self.file_id).readlines()
 
409
            self._add_text_to_weave(new_lines, file_parents, weave_store)
 
410
            self.text_sha1 = sha_strings(new_lines)
 
411
            self.text_size = sum(map(len, new_lines))
213
412
 
214
413
    def __eq__(self, other):
215
414
        if not isinstance(other, InventoryEntry):
216
415
            return NotImplemented
217
416
 
218
 
        return (self.file_id == other.file_id) \
219
 
               and (self.name == other.name) \
220
 
               and (self.text_sha1 == other.text_sha1) \
221
 
               and (self.text_size == other.text_size) \
222
 
               and (self.text_id == other.text_id) \
223
 
               and (self.parent_id == other.parent_id) \
224
 
               and (self.kind == other.kind)
225
 
 
 
417
        return ((self.file_id == other.file_id)
 
418
                and (self.name == other.name)
 
419
                and (other.symlink_target == self.symlink_target)
 
420
                and (self.text_sha1 == other.text_sha1)
 
421
                and (self.text_size == other.text_size)
 
422
                and (self.text_id == other.text_id)
 
423
                and (self.parent_id == other.parent_id)
 
424
                and (self.kind == other.kind)
 
425
                and (self.revision == other.revision)
 
426
                and (self.executable == other.executable)
 
427
                )
226
428
 
227
429
    def __ne__(self, other):
228
430
        return not (self == other)
230
432
    def __hash__(self):
231
433
        raise ValueError('not hashable')
232
434
 
 
435
    def _unchanged(self, path, previous_ie, work_tree):
 
436
        compatible = True
 
437
        # different inv parent
 
438
        if previous_ie.parent_id != self.parent_id:
 
439
            compatible = False
 
440
        # renamed
 
441
        elif previous_ie.name != self.name:
 
442
            compatible = False
 
443
        if self.kind == 'symlink':
 
444
            if self.symlink_target != previous_ie.symlink_target:
 
445
                compatible = False
 
446
        if self.kind == 'file':
 
447
            if self.text_sha1 != previous_ie.text_sha1:
 
448
                compatible = False
 
449
            else:
 
450
                # FIXME: 20050930 probe for the text size when getting sha1
 
451
                # in _read_tree_state
 
452
                self.text_size = previous_ie.text_size
 
453
        return compatible
 
454
 
 
455
    def _read_tree_state(self, path, work_tree):
 
456
        if self.kind == 'symlink':
 
457
            self.symlink_target = work_tree.get_symlink_target(self.file_id)
 
458
        if self.kind == 'file':
 
459
            self.text_sha1 = work_tree.get_file_sha1(self.file_id)
 
460
            self.executable = work_tree.is_executable(self.file_id)
233
461
 
234
462
 
235
463
class RootEntry(InventoryEntry):
268
496
 
269
497
    >>> inv = Inventory()
270
498
    >>> inv.add(InventoryEntry('123-123', 'hello.c', 'file', ROOT_ID))
 
499
    InventoryEntry('123-123', 'hello.c', kind='file', parent_id='TREE_ROOT')
271
500
    >>> inv['123-123'].name
272
501
    'hello.c'
273
502
 
284
513
    ['hello.c']
285
514
    >>> inv = Inventory('TREE_ROOT-12345678-12345678')
286
515
    >>> inv.add(InventoryEntry('123-123', 'hello.c', 'file', ROOT_ID))
 
516
    InventoryEntry('123-123', 'hello.c', kind='file', parent_id='TREE_ROOT-12345678-12345678')
287
517
    """
288
518
    def __init__(self, root_id=ROOT_ID):
289
519
        """Create or read an inventory.
295
525
        The inventory is created with a default root directory, with
296
526
        an id of None.
297
527
        """
298
 
        # We are letting Branch(init=True) create a unique inventory
 
528
        # We are letting Branch.initialize() create a unique inventory
299
529
        # root id. Rather than generating a random one here.
300
530
        #if root_id is None:
301
531
        #    root_id = bzrlib.branch.gen_file_id('TREE_ROOT')
303
533
        self._byid = {self.root.file_id: self.root}
304
534
 
305
535
 
 
536
    def copy(self):
 
537
        other = Inventory(self.root.file_id)
 
538
        # copy recursively so we know directories will be added before
 
539
        # their children.  There are more efficient ways than this...
 
540
        for path, entry in self.iter_entries():
 
541
            if entry == self.root:
 
542
                continue
 
543
            other.add(entry.copy())
 
544
        return other
 
545
 
 
546
 
306
547
    def __iter__(self):
307
548
        return iter(self._byid)
308
549
 
371
612
 
372
613
        >>> inv = Inventory()
373
614
        >>> inv.add(InventoryEntry('123', 'foo.c', 'file', ROOT_ID))
 
615
        InventoryEntry('123', 'foo.c', kind='file', parent_id='TREE_ROOT')
374
616
        >>> '123' in inv
375
617
        True
376
618
        >>> '456' in inv
384
626
 
385
627
        >>> inv = Inventory()
386
628
        >>> inv.add(InventoryEntry('123123', 'hello.c', 'file', ROOT_ID))
 
629
        InventoryEntry('123123', 'hello.c', kind='file', parent_id='TREE_ROOT')
387
630
        >>> inv['123123'].name
388
631
        'hello.c'
389
632
        """
407
650
        """Add entry to inventory.
408
651
 
409
652
        To add  a file to a branch ready to be committed, use Branch.add,
410
 
        which calls this."""
 
653
        which calls this.
 
654
 
 
655
        Returns the new entry object.
 
656
        """
411
657
        if entry.file_id in self._byid:
412
658
            raise BzrError("inventory already contains entry with id {%s}" % entry.file_id)
413
659
 
425
671
 
426
672
        self._byid[entry.file_id] = entry
427
673
        parent.children[entry.name] = entry
 
674
        return entry
428
675
 
429
676
 
430
677
    def add_path(self, relpath, kind, file_id=None):
431
678
        """Add entry from a path.
432
679
 
433
 
        The immediate parent must already be versioned"""
 
680
        The immediate parent must already be versioned.
 
681
 
 
682
        Returns the new entry object."""
434
683
        from bzrlib.branch import gen_file_id
435
684
        
436
685
        parts = bzrlib.osutils.splitpath(relpath)
455
704
 
456
705
        >>> inv = Inventory()
457
706
        >>> inv.add(InventoryEntry('123', 'foo.c', 'file', ROOT_ID))
 
707
        InventoryEntry('123', 'foo.c', kind='file', parent_id='TREE_ROOT')
458
708
        >>> '123' in inv
459
709
        True
460
710
        >>> del inv['123']
476
726
        del self[ie.parent_id].children[ie.name]
477
727
 
478
728
 
479
 
    def to_element(self):
480
 
        """Convert to XML Element"""
481
 
        from bzrlib.xml import Element
482
 
        
483
 
        e = Element('inventory')
484
 
        e.text = '\n'
485
 
        if self.root.file_id not in (None, ROOT_ID):
486
 
            e.set('file_id', self.root.file_id)
487
 
        for path, ie in self.iter_entries():
488
 
            e.append(ie.to_element())
489
 
        return e
490
 
    
491
 
 
492
 
    def from_element(cls, elt):
493
 
        """Construct from XML Element
494
 
        
495
 
        >>> inv = Inventory()
496
 
        >>> inv.add(InventoryEntry('foo.c-123981239', 'foo.c', 'file', ROOT_ID))
497
 
        >>> elt = inv.to_element()
498
 
        >>> inv2 = Inventory.from_element(elt)
499
 
        >>> inv2 == inv
500
 
        True
501
 
        """
502
 
        # XXXX: doctest doesn't run this properly under python2.3
503
 
        assert elt.tag == 'inventory'
504
 
        root_id = elt.get('file_id') or ROOT_ID
505
 
        o = cls(root_id)
506
 
        for e in elt:
507
 
            ie = InventoryEntry.from_element(e)
508
 
            if ie.parent_id == ROOT_ID:
509
 
                ie.parent_id = root_id
510
 
            o.add(ie)
511
 
        return o
512
 
        
513
 
    from_element = classmethod(from_element)
514
 
 
515
 
 
516
729
    def __eq__(self, other):
517
730
        """Compare two sets by comparing their contents.
518
731
 
521
734
        >>> i1 == i2
522
735
        True
523
736
        >>> i1.add(InventoryEntry('123', 'foo', 'file', ROOT_ID))
 
737
        InventoryEntry('123', 'foo', kind='file', parent_id='TREE_ROOT')
524
738
        >>> i1 == i2
525
739
        False
526
740
        >>> i2.add(InventoryEntry('123', 'foo', 'file', ROOT_ID))
 
741
        InventoryEntry('123', 'foo', kind='file', parent_id='TREE_ROOT')
527
742
        >>> i1 == i2
528
743
        True
529
744
        """
538
753
 
539
754
 
540
755
    def __ne__(self, other):
541
 
        return not (self == other)
 
756
        return not self.__eq__(other)
542
757
 
543
758
 
544
759
    def __hash__(self):
545
760
        raise ValueError('not hashable')
546
761
 
547
762
 
548
 
 
549
763
    def get_idpath(self, file_id):
550
764
        """Return a list of file_ids for the path to an entry.
551
765
 
644
858
 
645
859
 
646
860
 
647
 
_NAME_RE = re.compile(r'^[^/\\]+$')
 
861
_NAME_RE = None
648
862
 
649
863
def is_valid_name(name):
 
864
    global _NAME_RE
 
865
    if _NAME_RE == None:
 
866
        _NAME_RE = re.compile(r'^[^/\\]+$')
 
867
        
650
868
    return bool(_NAME_RE.match(name))