~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/inventory.py

  • Committer: mbp at sourcefrog
  • Date: 2005-03-09 04:08:15 UTC
  • Revision ID: mbp@sourcefrog.net-20050309040815-13242001617e4a06
import from baz patch-364

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# (C) 2005 Canonical Ltd
 
1
#! /usr/bin/env python
 
2
# -*- coding: UTF-8 -*-
2
3
 
3
4
# This program is free software; you can redistribute it and/or modify
4
5
# it under the terms of the GNU General Public License as published by
16
17
 
17
18
"""Inventories map files to their name in a revision."""
18
19
 
19
 
# TODO: Maybe store inventory_id in the file?  Not really needed.
20
20
 
21
21
__copyright__ = "Copyright (C) 2005 Canonical Ltd."
22
22
__author__ = "Martin Pool <mbp@canonical.com>"
23
23
 
24
 
import sys, os.path, types, re
 
24
import sys, os.path, types
25
25
from sets import Set
26
26
 
27
 
try:
28
 
    from cElementTree import Element, ElementTree, SubElement
29
 
except ImportError:
30
 
    from elementtree.ElementTree import Element, ElementTree, SubElement
31
 
 
32
27
from xml import XMLMixin
 
28
from ElementTree import ElementTree, Element
33
29
from errors import bailout
34
 
 
35
 
import bzrlib
36
 
from bzrlib.osutils import uuid, quotefn, splitpath, joinpath, appendpath
37
 
from bzrlib.trace import mutter
 
30
from osutils import uuid, quotefn, splitpath, joinpath, appendpath
 
31
from trace import mutter
38
32
 
39
33
class InventoryEntry(XMLMixin):
40
34
    """Description of a versioned file.
124
118
        self.parent_id = parent_id
125
119
        self.text_sha1 = None
126
120
        self.text_size = None
127
 
        if kind == 'directory':
128
 
            self.children = {}
129
 
 
130
 
 
131
 
    def sorted_children(self):
132
 
        l = self.children.items()
133
 
        l.sort()
134
 
        return l
135
121
 
136
122
 
137
123
    def copy(self):
205
191
 
206
192
 
207
193
 
208
 
class RootEntry(InventoryEntry):
209
 
    def __init__(self, file_id):
210
 
        self.file_id = file_id
211
 
        self.children = {}
212
 
        self.kind = 'root_directory'
213
 
        self.parent_id = None
214
 
        self.name = ''
215
 
 
216
 
    def __cmp__(self, other):
217
 
        if self is other:
218
 
            return 0
219
 
        if not isinstance(other, RootEntry):
220
 
            return NotImplemented
221
 
        return cmp(self.file_id, other.file_id) \
222
 
               or cmp(self.children, other.children)
223
 
 
224
 
 
225
 
 
226
194
class Inventory(XMLMixin):
227
195
    """Inventory of versioned files in a tree.
228
196
 
241
209
    returned quickly.
242
210
 
243
211
    InventoryEntry objects must not be modified after they are
244
 
    inserted, other than through the Inventory API.
 
212
    inserted.
245
213
 
246
214
    >>> inv = Inventory()
247
215
    >>> inv.write_xml(sys.stdout)
250
218
    >>> inv.add(InventoryEntry('123-123', 'hello.c'))
251
219
    >>> inv['123-123'].name
252
220
    'hello.c'
 
221
    >>> for file_id in inv: print file_id
 
222
    ...
 
223
    123-123
253
224
 
254
225
    May be treated as an iterator or set to look up file ids:
255
226
    
270
241
 
271
242
    """
272
243
 
 
244
    ## TODO: Clear up handling of files in subdirectories; we probably
 
245
    ## do want to be able to just look them up by name but this
 
246
    ## probably means gradually walking down the path, looking up as we go.
 
247
 
273
248
    ## TODO: Make sure only canonical filenames are stored.
274
249
 
275
250
    ## TODO: Do something sensible about the possible collisions on
276
251
    ## case-losing filesystems.  Perhaps we should just always forbid
277
252
    ## such collisions.
278
253
 
279
 
    ## TODO: No special cases for root, rather just give it a file id
280
 
    ## like everything else.
281
 
 
282
 
    ## TODO: Probably change XML serialization to use nesting
 
254
    ## _tree should probably just be stored as
 
255
    ## InventoryEntry._children on each directory.
283
256
 
284
257
    def __init__(self):
285
258
        """Create or read an inventory.
287
260
        If a working directory is specified, the inventory is read
288
261
        from there.  If the file is specified, read from that. If not,
289
262
        the inventory is created empty.
290
 
 
291
 
        The inventory is created with a default root directory, with
292
 
        an id of None.
293
263
        """
294
 
        self.root = RootEntry(None)
295
 
        self._byid = {None: self.root}
 
264
        self._byid = dict()
 
265
 
 
266
        # _tree is indexed by parent_id; at each level a map from name
 
267
        # to ie.  The None entry is the root.
 
268
        self._tree = {None: {}}
296
269
 
297
270
 
298
271
    def __iter__(self):
304
277
        return len(self._byid)
305
278
 
306
279
 
307
 
    def iter_entries(self, from_dir=None):
 
280
    def iter_entries(self, parent_id=None):
308
281
        """Return (path, entry) pairs, in order by name."""
309
 
        if from_dir == None:
310
 
            assert self.root
311
 
            from_dir = self.root
312
 
        elif isinstance(from_dir, basestring):
313
 
            from_dir = self._byid[from_dir]
314
 
            
315
 
        kids = from_dir.children.items()
 
282
        kids = self._tree[parent_id].items()
316
283
        kids.sort()
317
284
        for name, ie in kids:
318
285
            yield name, ie
319
286
            if ie.kind == 'directory':
320
 
                for cn, cie in self.iter_entries(from_dir=ie.file_id):
321
 
                    yield '/'.join((name, cn)), cie
 
287
                for cn, cie in self.iter_entries(parent_id=ie.file_id):
 
288
                    yield joinpath([name, cn]), cie
 
289
 
 
290
 
 
291
    def directories(self, include_root=True):
 
292
        """Return (path, entry) pairs for all directories.
 
293
        """
 
294
        if include_root:
 
295
            yield '', None
 
296
        for path, entry in self.iter_entries():
 
297
            if entry.kind == 'directory':
 
298
                yield path, entry
 
299
        
 
300
 
 
301
 
 
302
    def children(self, parent_id):
 
303
        """Return entries that are direct children of parent_id."""
 
304
        return self._tree[parent_id]
322
305
                    
323
306
 
324
307
 
325
 
    def directories(self, from_dir=None):
326
 
        """Return (path, entry) pairs for all directories.
327
 
        """
328
 
        def descend(parent_ie):
329
 
            parent_name = parent_ie.name
330
 
            yield parent_name, parent_ie
331
 
 
332
 
            # directory children in sorted order
333
 
            dn = []
334
 
            for ie in parent_ie.children.itervalues():
335
 
                if ie.kind == 'directory':
336
 
                    dn.append((ie.name, ie))
337
 
            dn.sort()
338
 
            
339
 
            for name, child_ie in dn:
340
 
                for sub_name, sub_ie in descend(child_ie):
341
 
                    yield appendpath(parent_name, sub_name), sub_ie
342
 
 
343
 
        for name, ie in descend(self.root):
344
 
            yield name, ie
345
 
        
 
308
    # TODO: return all paths and entries
346
309
 
347
310
 
348
311
    def __contains__(self, file_id):
369
332
        return self._byid[file_id]
370
333
 
371
334
 
372
 
    def get_child(self, parent_id, filename):
373
 
        return self[parent_id].children.get(filename)
374
 
 
375
 
 
376
335
    def add(self, entry):
377
336
        """Add entry to inventory.
378
337
 
379
338
        To add  a file to a branch ready to be committed, use Branch.add,
380
339
        which calls this."""
381
 
        if entry.file_id in self._byid:
 
340
        if entry.file_id in self:
382
341
            bailout("inventory already contains entry with id {%s}" % entry.file_id)
383
342
 
384
 
        try:
385
 
            parent = self._byid[entry.parent_id]
386
 
        except KeyError:
387
 
            bailout("parent_id %r not in inventory" % entry.parent_id)
388
 
 
389
 
        if parent.children.has_key(entry.name):
390
 
            bailout("%s is already versioned" %
391
 
                    appendpath(self.id2path(parent.file_id), entry.name))
 
343
        if entry.parent_id != None:
 
344
            if entry.parent_id not in self:
 
345
                bailout("parent_id %s of new entry not found in inventory"
 
346
                        % entry.parent_id)
 
347
            
 
348
        if self._tree[entry.parent_id].has_key(entry.name):
 
349
            bailout("%s is already versioned"
 
350
                    % appendpath(self.id2path(entry.parent_id), entry.name))
392
351
 
393
352
        self._byid[entry.file_id] = entry
394
 
        parent.children[entry.name] = entry
395
 
 
396
 
 
397
 
    def add_path(self, relpath, kind, file_id=None):
398
 
        """Add entry from a path.
399
 
 
400
 
        The immediate parent must already be versioned"""
401
 
        parts = bzrlib.osutils.splitpath(relpath)
402
 
        if len(parts) == 0:
403
 
            bailout("cannot re-add root of inventory")
404
 
 
405
 
        if file_id is None:
406
 
            file_id = bzrlib.branch.gen_file_id(relpath)
407
 
 
408
 
        parent_id = self.path2id(parts[:-1])
409
 
        ie = InventoryEntry(file_id, parts[-1],
410
 
                            kind=kind, parent_id=parent_id)
411
 
        return self.add(ie)
 
353
        self._tree[entry.parent_id][entry.name] = entry
 
354
 
 
355
        if entry.kind == 'directory':
 
356
            self._tree[entry.file_id] = {}
412
357
 
413
358
 
414
359
    def __delitem__(self, file_id):
424
369
        """
425
370
        ie = self[file_id]
426
371
 
427
 
        assert self[ie.parent_id].children[ie.name] == ie
 
372
        assert self._tree[ie.parent_id][ie.name] == ie
428
373
        
429
374
        # TODO: Test deleting all children; maybe hoist to a separate
430
375
        # deltree method?
431
376
        if ie.kind == 'directory':
432
 
            for cie in ie.children.values():
 
377
            for cie in self._tree[file_id].values():
433
378
                del self[cie.file_id]
434
 
            del ie.children
 
379
            del self._tree[file_id]
435
380
 
436
381
        del self._byid[file_id]
437
 
        del self[ie.parent_id].children[ie.name]
 
382
        del self._tree[ie.parent_id][ie.name]
438
383
 
439
384
 
440
385
    def id_set(self):
503
448
        """Return as a list the path to file_id."""
504
449
        p = []
505
450
        while file_id != None:
506
 
            ie = self._byid[file_id]
507
 
            p.insert(0, ie.name)
 
451
            ie = self[file_id]
 
452
            p = [ie.name] + p
508
453
            file_id = ie.parent_id
509
 
        return '/'.join(p)
 
454
        return joinpath(p)
510
455
            
511
456
 
512
457
 
519
464
        This returns the entry of the last component in the path,
520
465
        which may be either a file or a directory.
521
466
        """
522
 
        if isinstance(name, types.StringTypes):
523
 
            name = splitpath(name)
 
467
        assert isinstance(name, types.StringTypes)
524
468
 
525
 
        parent = self[None]
526
 
        for f in name:
 
469
        parent_id = None
 
470
        for f in splitpath(name):
527
471
            try:
528
 
                cie = parent.children[f]
 
472
                cie = self._tree[parent_id][f]
529
473
                assert cie.name == f
530
 
                parent = cie
 
474
                parent_id = cie.file_id
531
475
            except KeyError:
532
476
                # or raise an error?
533
477
                return None
534
478
 
535
 
        return parent.file_id
 
479
        return parent_id
 
480
 
 
481
 
 
482
    def get_child(self, parent_id, child_name):
 
483
        return self._tree[parent_id].get(child_name)
536
484
 
537
485
 
538
486
    def has_filename(self, names):
540
488
 
541
489
 
542
490
    def has_id(self, file_id):
 
491
        assert isinstance(file_id, str)
543
492
        return self._byid.has_key(file_id)
544
493
 
545
494
 
546
 
    def rename(self, file_id, new_parent_id, new_name):
547
 
        """Move a file within the inventory.
548
 
 
549
 
        This can change either the name, or the parent, or both.
550
 
 
551
 
        This does not move the working file."""
552
 
        if not is_valid_name(new_name):
553
 
            bailout("not an acceptable filename: %r" % new_name)
554
 
 
555
 
        new_parent = self._byid[new_parent_id]
556
 
        if new_name in new_parent.children:
557
 
            bailout("%r already exists in %r" % (new_name, self.id2path(new_parent_id)))
558
 
 
559
 
        file_ie = self._byid[file_id]
560
 
        old_parent = self._byid[file_ie.parent_id]
561
 
 
562
 
        # TODO: Don't leave things messed up if this fails
563
 
 
564
 
        del old_parent.children[file_ie.name]
565
 
        new_parent.children[new_name] = file_ie
566
 
        
567
 
        file_ie.name = new_name
568
 
        file_ie.parent_id = new_parent_id
569
 
 
570
 
 
571
 
 
572
 
 
573
 
_NAME_RE = re.compile(r'^[^/\\]+$')
574
 
 
575
 
def is_valid_name(name):
576
 
    return bool(_NAME_RE.match(name))
577
 
 
578
 
 
579
495
 
580
496
if __name__ == '__main__':
581
497
    import doctest, inventory