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
__copyright__ = "Copyright (C) 2005 Canonical Ltd."
22
__author__ = "Martin Pool <mbp@canonical.com>"
24
import sys, os.path, types, re
28
from cElementTree import Element, ElementTree, SubElement
30
from elementtree.ElementTree import Element, ElementTree, SubElement
32
from xml import XMLMixin
33
from errors import bailout
36
from bzrlib.osutils import uuid, quotefn, splitpath, joinpath, appendpath
37
from bzrlib.trace import mutter
39
class InventoryEntry(XMLMixin):
40
"""Description of a versioned file.
42
An InventoryEntry has the following fields, which are also
43
present in the XML inventory-entry element:
46
* *name*: (only the basename within the directory, must not
48
* *kind*: "directory" or "file"
49
* *directory_id*: (if absent/null means the branch root directory)
50
* *text_sha1*: only for files
51
* *text_size*: in bytes, only for files
52
* *text_id*: identifier for the text version, only for files
54
InventoryEntries can also exist inside a WorkingTree
55
inventory, in which case they are not yet bound to a
56
particular revision of the file. In that case the text_sha1,
57
text_size and text_id are absent.
62
>>> i.add(InventoryEntry('123', 'src', kind='directory'))
63
>>> i.add(InventoryEntry('2323', 'hello.c', parent_id='123'))
64
>>> for j in i.iter_entries():
67
('src', InventoryEntry('123', 'src', kind='directory', parent_id=None))
68
('src/hello.c', InventoryEntry('2323', 'hello.c', kind='file', parent_id='123'))
69
>>> i.add(InventoryEntry('2323', 'bye.c', parent_id='123'))
70
Traceback (most recent call last):
72
BzrError: ('inventory already contains entry with id {2323}', [])
73
>>> i.add(InventoryEntry('2324', 'bye.c', parent_id='123'))
74
>>> i.add(InventoryEntry('2325', 'wibble', parent_id='123', kind='directory'))
75
>>> i.path2id('src/wibble')
79
>>> i.add(InventoryEntry('2326', 'wibble.c', parent_id='2325'))
81
InventoryEntry('2326', 'wibble.c', kind='file', parent_id='2325')
82
>>> for j in i.iter_entries():
84
... assert i.path2id(j[0])
94
:todo: Maybe also keep the full path of the entry, and the children?
95
But those depend on its position within a particular inventory, and
96
it would be nice not to need to hold the backpointer here.
98
def __init__(self, file_id, name, kind='file', text_id=None,
100
"""Create an InventoryEntry
102
The filename must be a single component, relative to the
103
parent directory; it cannot be a whole path or relative name.
105
>>> e = InventoryEntry('123', 'hello.c')
110
>>> e = InventoryEntry('123', 'src/hello.c')
111
Traceback (most recent call last):
112
BzrError: ("InventoryEntry name is not a simple filename: 'src/hello.c'", [])
115
if len(splitpath(name)) != 1:
116
bailout('InventoryEntry name is not a simple filename: %r'
119
self.file_id = file_id
121
assert kind in ['file', 'directory']
123
self.text_id = text_id
124
self.parent_id = parent_id
125
self.text_sha1 = None
126
self.text_size = None
127
if kind == 'directory':
131
def sorted_children(self):
132
l = self.children.items()
138
other = InventoryEntry(self.file_id, self.name, self.kind,
139
self.text_id, self.parent_id)
140
other.text_sha1 = self.text_sha1
141
other.text_size = self.text_size
146
return ("%s(%r, %r, kind=%r, parent_id=%r)"
147
% (self.__class__.__name__,
154
def to_element(self):
155
"""Convert to XML element"""
158
e.set('name', self.name)
159
e.set('file_id', self.file_id)
160
e.set('kind', self.kind)
162
if self.text_size is not None:
163
e.set('text_size', '%d' % self.text_size)
165
for f in ['text_id', 'text_sha1', 'parent_id']:
175
def from_element(cls, elt):
176
assert elt.tag == 'entry'
177
self = cls(elt.get('file_id'), elt.get('name'), elt.get('kind'))
178
self.text_id = elt.get('text_id')
179
self.text_sha1 = elt.get('text_sha1')
180
self.parent_id = elt.get('parent_id')
182
## mutter("read inventoryentry: %r" % (elt.attrib))
184
v = elt.get('text_size')
185
self.text_size = v and int(v)
190
from_element = classmethod(from_element)
192
def __cmp__(self, other):
195
if not isinstance(other, InventoryEntry):
196
return NotImplemented
198
return cmp(self.file_id, other.file_id) \
199
or cmp(self.name, other.name) \
200
or cmp(self.text_sha1, other.text_sha1) \
201
or cmp(self.text_size, other.text_size) \
202
or cmp(self.text_id, other.text_id) \
203
or cmp(self.parent_id, other.parent_id) \
204
or cmp(self.kind, other.kind)
208
class RootEntry(InventoryEntry):
209
def __init__(self, file_id):
210
self.file_id = file_id
212
self.kind = 'root_directory'
213
self.parent_id = None
216
def __cmp__(self, other):
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)
226
class Inventory(XMLMixin):
227
"""Inventory of versioned files in a tree.
229
An Inventory acts like a set of InventoryEntry items. You can
230
also look files up by their file_id or name.
232
May be read from and written to a metadata file in a tree. To
233
manipulate the inventory (for example to add a file), it is read
234
in, modified, and then written back out.
236
The inventory represents a typical unix file tree, with
237
directories containing files and subdirectories. We never store
238
the full path to a file, because renaming a directory implicitly
239
moves all of its contents. This class internally maintains a
240
lookup tree that allows the children under a directory to be
243
InventoryEntry objects must not be modified after they are
244
inserted, other than through the Inventory API.
246
>>> inv = Inventory()
247
>>> inv.write_xml(sys.stdout)
250
>>> inv.add(InventoryEntry('123-123', 'hello.c'))
251
>>> inv['123-123'].name
254
May be treated as an iterator or set to look up file ids:
256
>>> bool(inv.path2id('hello.c'))
261
May also look up by name:
263
>>> [x[0] for x in inv.iter_entries()]
266
>>> inv.write_xml(sys.stdout)
268
<entry file_id="123-123" kind="file" name="hello.c" />
273
## TODO: Make sure only canonical filenames are stored.
275
## TODO: Do something sensible about the possible collisions on
276
## case-losing filesystems. Perhaps we should just always forbid
279
## TODO: No special cases for root, rather just give it a file id
280
## like everything else.
282
## TODO: Probably change XML serialization to use nesting
285
"""Create or read an inventory.
287
If a working directory is specified, the inventory is read
288
from there. If the file is specified, read from that. If not,
289
the inventory is created empty.
291
The inventory is created with a default root directory, with
294
self.root = RootEntry(None)
295
self._byid = {None: self.root}
299
return iter(self._byid)
303
"""Returns number of entries."""
304
return len(self._byid)
307
def iter_entries(self, from_dir=None):
308
"""Return (path, entry) pairs, in order by name."""
312
elif isinstance(from_dir, basestring):
313
from_dir = self._byid[from_dir]
315
kids = from_dir.children.items()
317
for name, ie in kids:
319
if ie.kind == 'directory':
320
for cn, cie in self.iter_entries(from_dir=ie.file_id):
321
yield '/'.join((name, cn)), cie
325
def directories(self, from_dir=None):
326
"""Return (path, entry) pairs for all directories.
328
def descend(parent_ie):
329
parent_name = parent_ie.name
330
yield parent_name, parent_ie
332
# directory children in sorted order
334
for ie in parent_ie.children.itervalues():
335
if ie.kind == 'directory':
336
dn.append((ie.name, ie))
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
343
for name, ie in descend(self.root):
348
def __contains__(self, file_id):
349
"""True if this entry contains a file with given id.
351
>>> inv = Inventory()
352
>>> inv.add(InventoryEntry('123', 'foo.c'))
358
return file_id in self._byid
361
def __getitem__(self, file_id):
362
"""Return the entry for given file_id.
364
>>> inv = Inventory()
365
>>> inv.add(InventoryEntry('123123', 'hello.c'))
366
>>> inv['123123'].name
369
return self._byid[file_id]
372
def get_child(self, parent_id, filename):
373
return self[parent_id].children.get(filename)
376
def add(self, entry):
377
"""Add entry to inventory.
379
To add a file to a branch ready to be committed, use Branch.add,
381
if entry.file_id in self._byid:
382
bailout("inventory already contains entry with id {%s}" % entry.file_id)
385
parent = self._byid[entry.parent_id]
387
bailout("parent_id %r not in inventory" % entry.parent_id)
389
if parent.children.has_key(entry.name):
390
bailout("%s is already versioned" %
391
appendpath(self.id2path(parent.file_id), entry.name))
393
self._byid[entry.file_id] = entry
394
parent.children[entry.name] = entry
397
def add_path(self, relpath, kind, file_id=None):
398
"""Add entry from a path.
400
The immediate parent must already be versioned"""
401
parts = bzrlib.osutils.splitpath(relpath)
403
bailout("cannot re-add root of inventory")
406
file_id = bzrlib.branch.gen_file_id(relpath)
408
parent_id = self.path2id(parts[:-1])
409
ie = InventoryEntry(file_id, parts[-1],
410
kind=kind, parent_id=parent_id)
414
def __delitem__(self, file_id):
415
"""Remove entry by id.
417
>>> inv = Inventory()
418
>>> inv.add(InventoryEntry('123', 'foo.c'))
427
assert self[ie.parent_id].children[ie.name] == ie
429
# TODO: Test deleting all children; maybe hoist to a separate
431
if ie.kind == 'directory':
432
for cie in ie.children.values():
433
del self[cie.file_id]
436
del self._byid[file_id]
437
del self[ie.parent_id].children[ie.name]
441
return Set(self._byid)
444
def to_element(self):
445
"""Convert to XML Element"""
446
e = Element('inventory')
448
for path, ie in self.iter_entries():
449
e.append(ie.to_element())
453
def from_element(cls, elt):
454
"""Construct from XML Element
456
>>> inv = Inventory()
457
>>> inv.add(InventoryEntry('foo.c-123981239', 'foo.c'))
458
>>> elt = inv.to_element()
459
>>> inv2 = Inventory.from_element(elt)
463
assert elt.tag == 'inventory'
466
o.add(InventoryEntry.from_element(e))
469
from_element = classmethod(from_element)
472
def __cmp__(self, other):
473
"""Compare two sets by comparing their contents.
479
>>> i1.add(InventoryEntry('123', 'foo'))
482
>>> i2.add(InventoryEntry('123', 'foo'))
489
if not isinstance(other, Inventory):
490
return NotImplemented
492
if self.id_set() ^ other.id_set():
495
for file_id in self._byid:
496
c = cmp(self[file_id], other[file_id])
502
def get_idpath(self, file_id):
503
"""Return a list of file_ids for the path to an entry.
505
The list contains one element for each directory followed by
506
the id of the file itself. So the length of the returned list
507
is equal to the depth of the file in the tree, counting the
508
root directory as depth 0.
511
while file_id != None:
512
ie = self._byid[file_id]
513
p.insert(0, ie.file_id)
514
file_id = ie.parent_id
518
def id2path(self, file_id):
519
"""Return as a list the path to file_id."""
521
while file_id != None:
522
ie = self._byid[file_id]
524
file_id = ie.parent_id
529
def path2id(self, name):
530
"""Walk down through directories to return entry of last component.
532
names may be either a list of path components, or a single
533
string, in which case it is automatically split.
535
This returns the entry of the last component in the path,
536
which may be either a file or a directory.
538
if isinstance(name, types.StringTypes):
539
name = splitpath(name)
544
cie = parent.children[f]
551
return parent.file_id
554
def has_filename(self, names):
555
return bool(self.path2id(names))
558
def has_id(self, file_id):
559
return self._byid.has_key(file_id)
562
def rename(self, file_id, new_parent_id, new_name):
563
"""Move a file within the inventory.
565
This can change either the name, or the parent, or both.
567
This does not move the working file."""
568
if not is_valid_name(new_name):
569
bailout("not an acceptable filename: %r" % new_name)
571
new_parent = self._byid[new_parent_id]
572
if new_name in new_parent.children:
573
bailout("%r already exists in %r" % (new_name, self.id2path(new_parent_id)))
575
new_parent_idpath = self.get_idpath(new_parent_id)
576
if file_id in new_parent_idpath:
577
bailout("cannot move directory %r into a subdirectory of itself, %r"
578
% (self.id2path(file_id), self.id2path(new_parent_id)))
580
file_ie = self._byid[file_id]
581
old_parent = self._byid[file_ie.parent_id]
583
# TODO: Don't leave things messed up if this fails
585
del old_parent.children[file_ie.name]
586
new_parent.children[new_name] = file_ie
588
file_ie.name = new_name
589
file_ie.parent_id = new_parent_id
594
_NAME_RE = re.compile(r'^[^/\\]+$')
596
def is_valid_name(name):
597
return bool(_NAME_RE.match(name))
601
if __name__ == '__main__':
602
import doctest, inventory
603
doctest.testmod(inventory)