1
# Copyright (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
"""Tree classes, representing directory at point in time.
20
from osutils import pumpfile, appendpath, fingerprint_file
22
from bzrlib.trace import mutter, note
23
from bzrlib.errors import BzrError
30
"""Abstract file tree.
32
There are several subclasses:
34
* `WorkingTree` exists as files on disk editable by the user.
36
* `RevisionTree` is a tree as recorded at some point in the past.
40
Trees contain an `Inventory` object, and also know how to retrieve
41
file texts mentioned in the inventory, either from a working
42
directory or from a store.
44
It is possible for trees to contain files that are not described
45
in their inventory or vice versa; for this use `filenames()`.
47
Trees can be compared, etc, regardless of whether they are working
48
trees or versioned trees.
51
def has_filename(self, filename):
52
"""True if the tree has given filename."""
53
raise NotImplementedError()
55
def has_id(self, file_id):
56
return self.inventory.has_id(file_id)
61
return iter(self.inventory)
63
def id2path(self, file_id):
64
return self.inventory.id2path(file_id)
66
def _get_inventory(self):
67
return self._inventory
69
inventory = property(_get_inventory,
70
doc="Inventory of this Tree")
72
def _check_retrieved(self, ie, f):
73
fp = fingerprint_file(f)
76
if ie.text_size != None:
77
if ie.text_size != fp['size']:
78
raise BzrError("mismatched size for file %r in %r" % (ie.file_id, self._store),
79
["inventory expects %d bytes" % ie.text_size,
80
"file is actually %d bytes" % fp['size'],
81
"store is probably damaged/corrupt"])
83
if ie.text_sha1 != fp['sha1']:
84
raise BzrError("wrong SHA-1 for file %r in %r" % (ie.file_id, self._store),
85
["inventory expects %s" % ie.text_sha1,
86
"file is actually %s" % fp['sha1'],
87
"store is probably damaged/corrupt"])
90
def print_file(self, fileid):
91
"""Print file with id `fileid` to stdout."""
93
pumpfile(self.get_file(fileid), sys.stdout)
96
def export(self, dest, format='dir'):
97
"""Export this tree."""
99
exporter = exporters[format]
101
raise BzrCommandError("export format %r not supported" % format)
106
class RevisionTree(Tree):
107
"""Tree viewing a previous revision.
109
File text can be retrieved from the text store.
111
TODO: Some kind of `__repr__` method, but a good one
112
probably means knowing the branch and revision number,
113
or at least passing a description to the constructor.
116
def __init__(self, store, inv):
118
self._inventory = inv
120
def get_file(self, file_id):
121
ie = self._inventory[file_id]
122
f = self._store[ie.text_id]
123
mutter(" get fileid{%s} from %r" % (file_id, self))
124
self._check_retrieved(ie, f)
127
def get_file_size(self, file_id):
128
return self._inventory[file_id].text_size
130
def get_file_sha1(self, file_id):
131
ie = self._inventory[file_id]
134
def has_filename(self, filename):
135
return bool(self.inventory.path2id(filename))
137
def list_files(self):
138
# The only files returned by this are those from the version
139
for path, entry in self.inventory.iter_entries():
140
yield path, 'V', entry.kind, entry.file_id
143
class EmptyTree(Tree):
145
from bzrlib.inventory import Inventory
146
self._inventory = Inventory()
148
def has_filename(self, filename):
151
def list_files(self):
152
if False: # just to make it a generator
157
######################################################################
160
# TODO: Merge these two functions into a single one that can operate
161
# on either a whole tree or a set of files.
163
# TODO: Return the diff in order by filename, not by category or in
164
# random order. Can probably be done by lock-stepping through the
165
# filenames from both trees.
168
def file_status(filename, old_tree, new_tree):
169
"""Return single-letter status, old and new names for a file.
171
The complexity here is in deciding how to represent renames;
172
many complex cases are possible.
174
old_inv = old_tree.inventory
175
new_inv = new_tree.inventory
176
new_id = new_inv.path2id(filename)
177
old_id = old_inv.path2id(filename)
179
if not new_id and not old_id:
180
# easy: doesn't exist in either; not versioned at all
181
if new_tree.is_ignored(filename):
182
return 'I', None, None
184
return '?', None, None
186
# There is now a file of this name, great.
189
# There is no longer a file of this name, but we can describe
190
# what happened to the file that used to have
191
# this name. There are two possibilities: either it was
192
# deleted entirely, or renamed.
194
if new_inv.has_id(old_id):
195
return 'X', old_inv.id2path(old_id), new_inv.id2path(old_id)
197
return 'D', old_inv.id2path(old_id), None
199
# if the file_id is new in this revision, it is added
200
if new_id and not old_inv.has_id(new_id):
203
# if there used to be a file of this name, but that ID has now
204
# disappeared, it is deleted
205
if old_id and not new_inv.has_id(old_id):
212
def find_renames(old_inv, new_inv):
213
for file_id in old_inv:
214
if file_id not in new_inv:
216
old_name = old_inv.id2path(file_id)
217
new_name = new_inv.id2path(file_id)
218
if old_name != new_name:
219
yield (old_name, new_name)
223
######################################################################
226
def dir_exporter(tree, dest):
227
"""Export this tree to a new directory.
229
`dest` should not exist, and will be created holding the
230
contents of this tree.
232
TODO: To handle subdirectories we need to create the
235
:note: If the export fails, the destination directory will be
236
left in a half-assed state.
240
mutter('export version %r' % tree)
242
for dp, ie in inv.iter_entries():
244
fullpath = appendpath(dest, dp)
245
if kind == 'directory':
248
pumpfile(tree.get_file(ie.file_id), file(fullpath, 'wb'))
250
raise BzrError("don't know how to export {%s} of kind %r" % (ie.file_id, kind))
251
mutter(" export {%s} kind %s to %s" % (ie.file_id, kind, fullpath))
252
exporters['dir'] = dir_exporter
259
def tar_exporter(tree, dest, compression=None):
260
"""Export this tree to a new tar file.
262
`dest` will be created holding the contents of this tree; if it
263
already exists, it will be clobbered, like with "tar -c".
265
from time import time
267
compression = str(compression or '')
269
ball = tarfile.open(dest, 'w:' + compression)
270
except tarfile.CompressionError, e:
271
raise BzrError(str(e))
272
mutter('export version %r' % tree)
274
for dp, ie in inv.iter_entries():
275
mutter(" export {%s} kind %s to %s" % (ie.file_id, ie.kind, dest))
276
item = tarfile.TarInfo(dp)
277
# TODO: would be cool to actually set it to the timestamp of the
278
# revision it was last changed
280
if ie.kind == 'directory':
281
item.type = tarfile.DIRTYPE
286
elif ie.kind == 'file':
287
item.type = tarfile.REGTYPE
288
fileobj = tree.get_file(ie.file_id)
289
item.size = _find_file_size(fileobj)
292
raise BzrError("don't know how to export {%s} of kind %r" %
293
(ie.file_id, ie.kind))
295
ball.addfile(item, fileobj)
297
exporters['tar'] = tar_exporter
299
def tgz_exporter(tree, dest):
300
tar_exporter(tree, dest, compression='gz')
301
exporters['tgz'] = tgz_exporter
303
def tbz_exporter(tree, dest):
304
tar_exporter(tree, dest, compression='bz2')
305
exporters['tbz2'] = tbz_exporter
308
def _find_file_size(fileobj):
309
offset = fileobj.tell()
312
size = fileobj.tell()
314
# gzip doesn't accept second argument to seek()
318
nread = len(fileobj.read())