1
# (C) 2005 Canonical Ltd
 
 
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.
 
 
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.
 
 
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
 
 
17
"""Inventories map files to their name in a revision."""
 
 
19
# TODO: Maybe store inventory_id in the file?  Not really needed.
 
 
21
__author__ = "Martin Pool <mbp@canonical.com>"
 
 
24
# This should really be an id randomly assigned when the tree is
 
 
25
# created, but it's not for now.
 
 
29
import sys, os.path, types, re
 
 
33
    from cElementTree import Element, ElementTree, SubElement
 
 
35
    from elementtree.ElementTree import Element, ElementTree, SubElement
 
 
37
from xml import XMLMixin
 
 
38
from errors import bailout, BzrError
 
 
41
from bzrlib.osutils import uuid, quotefn, splitpath, joinpath, appendpath
 
 
42
from bzrlib.trace import mutter
 
 
44
class InventoryEntry(XMLMixin):
 
 
45
    """Description of a versioned file.
 
 
47
    An InventoryEntry has the following fields, which are also
 
 
48
    present in the XML inventory-entry element:
 
 
51
    * *name*: (only the basename within the directory, must not
 
 
53
    * *kind*: "directory" or "file"
 
 
54
    * *directory_id*: (if absent/null means the branch root directory)
 
 
55
    * *text_sha1*: only for files
 
 
56
    * *text_size*: in bytes, only for files 
 
 
57
    * *text_id*: identifier for the text version, only for files
 
 
59
    InventoryEntries can also exist inside a WorkingTree
 
 
60
    inventory, in which case they are not yet bound to a
 
 
61
    particular revision of the file.  In that case the text_sha1,
 
 
62
    text_size and text_id are absent.
 
 
68
    >>> i.add(InventoryEntry('123', 'src', 'directory', ROOT_ID))
 
 
69
    >>> i.add(InventoryEntry('2323', 'hello.c', 'file', parent_id='123'))
 
 
70
    >>> for j in i.iter_entries():
 
 
73
    ('src', InventoryEntry('123', 'src', kind='directory', parent_id='TREE_ROOT'))
 
 
74
    ('src/hello.c', InventoryEntry('2323', 'hello.c', kind='file', parent_id='123'))
 
 
75
    >>> i.add(InventoryEntry('2323', 'bye.c', 'file', '123'))
 
 
76
    Traceback (most recent call last):
 
 
78
    BzrError: ('inventory already contains entry with id {2323}', [])
 
 
79
    >>> i.add(InventoryEntry('2324', 'bye.c', 'file', '123'))
 
 
80
    >>> i.add(InventoryEntry('2325', 'wibble', 'directory', '123'))
 
 
81
    >>> i.path2id('src/wibble')
 
 
85
    >>> i.add(InventoryEntry('2326', 'wibble.c', 'file', '2325'))
 
 
87
    InventoryEntry('2326', 'wibble.c', kind='file', parent_id='2325')
 
 
88
    >>> for j in i.iter_entries():
 
 
90
    ...     assert i.path2id(j[0])
 
 
100
    :todo: Maybe also keep the full path of the entry, and the children?
 
 
101
           But those depend on its position within a particular inventory, and
 
 
102
           it would be nice not to need to hold the backpointer here.
 
 
105
    # TODO: split InventoryEntry into subclasses for files,
 
 
106
    # directories, etc etc.
 
 
108
    def __init__(self, file_id, name, kind, parent_id, text_id=None):
 
 
109
        """Create an InventoryEntry
 
 
111
        The filename must be a single component, relative to the
 
 
112
        parent directory; it cannot be a whole path or relative name.
 
 
114
        >>> e = InventoryEntry('123', 'hello.c', 'file', ROOT_ID)
 
 
119
        >>> e = InventoryEntry('123', 'src/hello.c', 'file', ROOT_ID)
 
 
120
        Traceback (most recent call last):
 
 
121
        BzrError: ("InventoryEntry name is not a simple filename: 'src/hello.c'", [])
 
 
124
        if len(splitpath(name)) != 1:
 
 
125
            bailout('InventoryEntry name is not a simple filename: %r'
 
 
128
        self.file_id = file_id
 
 
130
        assert kind in ['file', 'directory']
 
 
132
        self.text_id = text_id
 
 
133
        self.parent_id = parent_id
 
 
134
        self.text_sha1 = None
 
 
135
        self.text_size = None
 
 
136
        if kind == 'directory':
 
 
139
            assert kind == 'file'
 
 
142
    def sorted_children(self):
 
 
143
        l = self.children.items()
 
 
149
        other = InventoryEntry(self.file_id, self.name, self.kind,
 
 
150
                               self.parent_id, text_id=self.text_id)
 
 
151
        other.text_sha1 = self.text_sha1
 
 
152
        other.text_size = self.text_size
 
 
157
        return ("%s(%r, %r, kind=%r, parent_id=%r)"
 
 
158
                % (self.__class__.__name__,
 
 
165
    def to_element(self):
 
 
166
        """Convert to XML element"""
 
 
169
        e.set('name', self.name)
 
 
170
        e.set('file_id', self.file_id)
 
 
171
        e.set('kind', self.kind)
 
 
173
        if self.text_size != None:
 
 
174
            e.set('text_size', '%d' % self.text_size)
 
 
176
        for f in ['text_id', 'text_sha1']:
 
 
181
        # to be conservative, we don't externalize the root pointers
 
 
182
        # for now, leaving them as null in the xml form.  in a future
 
 
183
        # version it will be implied by nested elements.
 
 
184
        if self.parent_id != ROOT_ID:
 
 
185
            assert isinstance(self.parent_id, basestring)
 
 
186
            e.set('parent_id', self.parent_id)
 
 
193
    def from_element(cls, elt):
 
 
194
        assert elt.tag == 'entry'
 
 
196
        ## original format inventories don't have a parent_id for
 
 
197
        ## nodes in the root directory, but it's cleaner to use one
 
 
199
        parent_id = elt.get('parent_id')
 
 
200
        if parent_id == None:
 
 
203
        self = cls(elt.get('file_id'), elt.get('name'), elt.get('kind'), parent_id)
 
 
204
        self.text_id = elt.get('text_id')
 
 
205
        self.text_sha1 = elt.get('text_sha1')
 
 
207
        ## mutter("read inventoryentry: %r" % (elt.attrib))
 
 
209
        v = elt.get('text_size')
 
 
210
        self.text_size = v and int(v)
 
 
215
    from_element = classmethod(from_element)
 
 
217
    def __cmp__(self, other):
 
 
220
        if not isinstance(other, InventoryEntry):
 
 
221
            return NotImplemented
 
 
223
        return cmp(self.file_id, other.file_id) \
 
 
224
               or cmp(self.name, other.name) \
 
 
225
               or cmp(self.text_sha1, other.text_sha1) \
 
 
226
               or cmp(self.text_size, other.text_size) \
 
 
227
               or cmp(self.text_id, other.text_id) \
 
 
228
               or cmp(self.parent_id, other.parent_id) \
 
 
229
               or cmp(self.kind, other.kind)
 
 
233
class RootEntry(InventoryEntry):
 
 
234
    def __init__(self, file_id):
 
 
235
        self.file_id = file_id
 
 
237
        self.kind = 'root_directory'
 
 
238
        self.parent_id = None
 
 
241
    def __cmp__(self, other):
 
 
244
        if not isinstance(other, RootEntry):
 
 
245
            return NotImplemented
 
 
246
        return cmp(self.file_id, other.file_id) \
 
 
247
               or cmp(self.children, other.children)
 
 
251
class Inventory(XMLMixin):
 
 
252
    """Inventory of versioned files in a tree.
 
 
254
    An Inventory acts like a set of InventoryEntry items.  You can
 
 
255
    also look files up by their file_id or name.
 
 
257
    May be read from and written to a metadata file in a tree.  To
 
 
258
    manipulate the inventory (for example to add a file), it is read
 
 
259
    in, modified, and then written back out.
 
 
261
    The inventory represents a typical unix file tree, with
 
 
262
    directories containing files and subdirectories.  We never store
 
 
263
    the full path to a file, because renaming a directory implicitly
 
 
264
    moves all of its contents.  This class internally maintains a
 
 
265
    lookup tree that allows the children under a directory to be
 
 
268
    InventoryEntry objects must not be modified after they are
 
 
269
    inserted, other than through the Inventory API.
 
 
271
    >>> inv = Inventory()
 
 
272
    >>> inv.write_xml(sys.stdout)
 
 
275
    >>> inv.add(InventoryEntry('123-123', 'hello.c', 'file', ROOT_ID))
 
 
276
    >>> inv['123-123'].name
 
 
279
    May be treated as an iterator or set to look up file ids:
 
 
281
    >>> bool(inv.path2id('hello.c'))
 
 
286
    May also look up by name:
 
 
288
    >>> [x[0] for x in inv.iter_entries()]
 
 
291
    >>> inv.write_xml(sys.stdout)
 
 
293
    <entry file_id="123-123" kind="file" name="hello.c" />
 
 
298
    ## TODO: Make sure only canonical filenames are stored.
 
 
300
    ## TODO: Do something sensible about the possible collisions on
 
 
301
    ## case-losing filesystems.  Perhaps we should just always forbid
 
 
304
    ## TODO: No special cases for root, rather just give it a file id
 
 
305
    ## like everything else.
 
 
307
    ## TODO: Probably change XML serialization to use nesting
 
 
310
        """Create or read an inventory.
 
 
312
        If a working directory is specified, the inventory is read
 
 
313
        from there.  If the file is specified, read from that. If not,
 
 
314
        the inventory is created empty.
 
 
316
        The inventory is created with a default root directory, with
 
 
319
        self.root = RootEntry(ROOT_ID)
 
 
320
        self._byid = {self.root.file_id: self.root}
 
 
324
        return iter(self._byid)
 
 
328
        """Returns number of entries."""
 
 
329
        return len(self._byid)
 
 
332
    def iter_entries(self, from_dir=None):
 
 
333
        """Return (path, entry) pairs, in order by name."""
 
 
337
        elif isinstance(from_dir, basestring):
 
 
338
            from_dir = self._byid[from_dir]
 
 
340
        kids = from_dir.children.items()
 
 
342
        for name, ie in kids:
 
 
344
            if ie.kind == 'directory':
 
 
345
                for cn, cie in self.iter_entries(from_dir=ie.file_id):
 
 
346
                    yield '/'.join((name, cn)), cie
 
 
350
    def directories(self):
 
 
351
        """Return (path, entry) pairs for all directories.
 
 
353
        def descend(parent_ie):
 
 
354
            parent_name = parent_ie.name
 
 
355
            yield parent_name, parent_ie
 
 
357
            # directory children in sorted order
 
 
359
            for ie in parent_ie.children.itervalues():
 
 
360
                if ie.kind == 'directory':
 
 
361
                    dn.append((ie.name, ie))
 
 
364
            for name, child_ie in dn:
 
 
365
                for sub_name, sub_ie in descend(child_ie):
 
 
366
                    yield appendpath(parent_name, sub_name), sub_ie
 
 
368
        for name, ie in descend(self.root):
 
 
373
    def __contains__(self, file_id):
 
 
374
        """True if this entry contains a file with given id.
 
 
376
        >>> inv = Inventory()
 
 
377
        >>> inv.add(InventoryEntry('123', 'foo.c', 'file', ROOT_ID))
 
 
383
        return file_id in self._byid
 
 
386
    def __getitem__(self, file_id):
 
 
387
        """Return the entry for given file_id.
 
 
389
        >>> inv = Inventory()
 
 
390
        >>> inv.add(InventoryEntry('123123', 'hello.c', 'file', ROOT_ID))
 
 
391
        >>> inv['123123'].name
 
 
395
            raise BzrError("can't look up file_id None")
 
 
398
            return self._byid[file_id]
 
 
400
            raise BzrError("file_id {%s} not in inventory" % file_id)
 
 
403
    def get_child(self, parent_id, filename):
 
 
404
        return self[parent_id].children.get(filename)
 
 
407
    def add(self, entry):
 
 
408
        """Add entry to inventory.
 
 
410
        To add  a file to a branch ready to be committed, use Branch.add,
 
 
412
        if entry.file_id in self._byid:
 
 
413
            bailout("inventory already contains entry with id {%s}" % entry.file_id)
 
 
416
            parent = self._byid[entry.parent_id]
 
 
418
            bailout("parent_id {%s} not in inventory" % entry.parent_id)
 
 
420
        if parent.children.has_key(entry.name):
 
 
421
            bailout("%s is already versioned" %
 
 
422
                    appendpath(self.id2path(parent.file_id), entry.name))
 
 
424
        self._byid[entry.file_id] = entry
 
 
425
        parent.children[entry.name] = entry
 
 
428
    def add_path(self, relpath, kind, file_id=None):
 
 
429
        """Add entry from a path.
 
 
431
        The immediate parent must already be versioned"""
 
 
432
        parts = bzrlib.osutils.splitpath(relpath)
 
 
434
            bailout("cannot re-add root of inventory")
 
 
437
            file_id = bzrlib.branch.gen_file_id(relpath)
 
 
439
        parent_id = self.path2id(parts[:-1])
 
 
440
        assert parent_id != None
 
 
441
        ie = InventoryEntry(file_id, parts[-1],
 
 
442
                            kind=kind, parent_id=parent_id)
 
 
446
    def __delitem__(self, file_id):
 
 
447
        """Remove entry by id.
 
 
449
        >>> inv = Inventory()
 
 
450
        >>> inv.add(InventoryEntry('123', 'foo.c', 'file', ROOT_ID))
 
 
459
        assert self[ie.parent_id].children[ie.name] == ie
 
 
461
        # TODO: Test deleting all children; maybe hoist to a separate
 
 
463
        if ie.kind == 'directory':
 
 
464
            for cie in ie.children.values():
 
 
465
                del self[cie.file_id]
 
 
468
        del self._byid[file_id]
 
 
469
        del self[ie.parent_id].children[ie.name]
 
 
473
        return Set(self._byid)
 
 
476
    def to_element(self):
 
 
477
        """Convert to XML Element"""
 
 
478
        e = Element('inventory')
 
 
480
        for path, ie in self.iter_entries():
 
 
481
            e.append(ie.to_element())
 
 
485
    def from_element(cls, elt):
 
 
486
        """Construct from XML Element
 
 
488
        >>> inv = Inventory()
 
 
489
        >>> inv.add(InventoryEntry('foo.c-123981239', 'foo.c', 'file', ROOT_ID))
 
 
490
        >>> elt = inv.to_element()
 
 
491
        >>> inv2 = Inventory.from_element(elt)
 
 
495
        assert elt.tag == 'inventory'
 
 
498
            o.add(InventoryEntry.from_element(e))
 
 
501
    from_element = classmethod(from_element)
 
 
504
    def __cmp__(self, other):
 
 
505
        """Compare two sets by comparing their contents.
 
 
511
        >>> i1.add(InventoryEntry('123', 'foo', 'file', ROOT_ID))
 
 
514
        >>> i2.add(InventoryEntry('123', 'foo', 'file', ROOT_ID))
 
 
521
        if not isinstance(other, Inventory):
 
 
522
            return NotImplemented
 
 
524
        if self.id_set() ^ other.id_set():
 
 
527
        for file_id in self._byid:
 
 
528
            c = cmp(self[file_id], other[file_id])
 
 
534
    def get_idpath(self, file_id):
 
 
535
        """Return a list of file_ids for the path to an entry.
 
 
537
        The list contains one element for each directory followed by
 
 
538
        the id of the file itself.  So the length of the returned list
 
 
539
        is equal to the depth of the file in the tree, counting the
 
 
540
        root directory as depth 1.
 
 
543
        while file_id != None:
 
 
545
                ie = self._byid[file_id]
 
 
547
                bailout("file_id {%s} not found in inventory" % file_id)
 
 
548
            p.insert(0, ie.file_id)
 
 
549
            file_id = ie.parent_id
 
 
553
    def id2path(self, file_id):
 
 
554
        """Return as a list the path to file_id."""
 
 
556
        # get all names, skipping root
 
 
557
        p = [self[fid].name for fid in self.get_idpath(file_id)[1:]]
 
 
562
    def path2id(self, name):
 
 
563
        """Walk down through directories to return entry of last component.
 
 
565
        names may be either a list of path components, or a single
 
 
566
        string, in which case it is automatically split.
 
 
568
        This returns the entry of the last component in the path,
 
 
569
        which may be either a file or a directory.
 
 
571
        Returns None iff the path is not found.
 
 
573
        if isinstance(name, types.StringTypes):
 
 
574
            name = splitpath(name)
 
 
576
        mutter("lookup path %r" % name)
 
 
581
                cie = parent.children[f]
 
 
583
                assert cie.parent_id == parent.file_id
 
 
589
        return parent.file_id
 
 
592
    def has_filename(self, names):
 
 
593
        return bool(self.path2id(names))
 
 
596
    def has_id(self, file_id):
 
 
597
        return self._byid.has_key(file_id)
 
 
600
    def rename(self, file_id, new_parent_id, new_name):
 
 
601
        """Move a file within the inventory.
 
 
603
        This can change either the name, or the parent, or both.
 
 
605
        This does not move the working file."""
 
 
606
        if not is_valid_name(new_name):
 
 
607
            bailout("not an acceptable filename: %r" % new_name)
 
 
609
        new_parent = self._byid[new_parent_id]
 
 
610
        if new_name in new_parent.children:
 
 
611
            bailout("%r already exists in %r" % (new_name, self.id2path(new_parent_id)))
 
 
613
        new_parent_idpath = self.get_idpath(new_parent_id)
 
 
614
        if file_id in new_parent_idpath:
 
 
615
            bailout("cannot move directory %r into a subdirectory of itself, %r"
 
 
616
                    % (self.id2path(file_id), self.id2path(new_parent_id)))
 
 
618
        file_ie = self._byid[file_id]
 
 
619
        old_parent = self._byid[file_ie.parent_id]
 
 
621
        # TODO: Don't leave things messed up if this fails
 
 
623
        del old_parent.children[file_ie.name]
 
 
624
        new_parent.children[new_name] = file_ie
 
 
626
        file_ie.name = new_name
 
 
627
        file_ie.parent_id = new_parent_id
 
 
632
_NAME_RE = re.compile(r'^[^/\\]+$')
 
 
634
def is_valid_name(name):
 
 
635
    return bool(_NAME_RE.match(name))