2
# -*- coding: UTF-8 -*-
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
"""Tree classes, representing directory at point in time.
22
import os.path, os, fnmatch
24
from inventory import Inventory
25
from trace import mutter, note
26
from osutils import pumpfile, compare_files, filesize, quotefn, sha_file, \
27
joinpath, splitpath, appendpath, isdir, isfile, file_kind
28
from errors import bailout
30
from stat import S_ISREG, S_ISDIR, ST_MODE, ST_SIZE
35
"""Abstract file tree.
37
There are several subclasses:
39
* `WorkingTree` exists as files on disk editable by the user.
41
* `RevisionTree` is a tree as recorded at some point in the past.
45
Trees contain an `Inventory` object, and also know how to retrieve
46
file texts mentioned in the inventory, either from a working
47
directory or from a store.
49
It is possible for trees to contain files that are not described
50
in their inventory or vice versa; for this use `filenames()`.
52
Trees can be compared, etc, regardless of whether they are working
53
trees or versioned trees.
56
def get_file(self, file_id):
57
"""Return an open file-like object for given file id."""
58
raise NotImplementedError()
60
def has_filename(self, filename):
61
"""True if the tree has given filename."""
62
raise NotImplementedError()
64
def has_id(self, file_id):
65
return self.inventory.has_id(file_id)
68
"""Return set of all ids in this tree."""
69
return self.inventory.id_set()
71
def id2path(self, file_id):
72
return self.inventory.id2path(file_id)
74
def _get_inventory(self):
75
return self._inventory
77
inventory = property(_get_inventory,
78
doc="Inventory of this Tree")
80
def _check_retrieved(self, ie, f):
81
# TODO: Test this check by damaging the store?
82
if ie.text_size is not None:
84
if fs != ie.text_size:
85
bailout("mismatched size for file %r in %r" % (ie.file_id, self._store),
86
["inventory expects %d bytes" % ie.text_size,
87
"file is actually %d bytes" % fs,
88
"store is probably damaged/corrupt"])
92
if ie.text_sha1 != f_hash:
93
bailout("wrong SHA-1 for file %r in %r" % (ie.file_id, self._store),
94
["inventory expects %s" % ie.text_sha1,
95
"file is actually %s" % f_hash,
96
"store is probably damaged/corrupt"])
99
def export(self, dest):
100
"""Export this tree to a new directory.
102
`dest` should not exist, and will be created holding the
103
contents of this tree.
105
:todo: To handle subdirectories we need to create the
108
:note: If the export fails, the destination directory will be
109
left in a half-assed state.
112
mutter('export version %r' % self)
114
for dp, ie in inv.iter_entries():
116
fullpath = appendpath(dest, dp)
117
if kind == 'directory':
120
pumpfile(self.get_file(ie.file_id), file(fullpath, 'wb'))
122
bailout("don't know how to export {%s} of kind %r", fid, kind)
123
mutter(" export {%s} kind %s to %s" % (ie.file_id, kind, fullpath))
127
class WorkingTree(Tree):
128
"""Working copy tree.
130
The inventory is held in the `Branch` working-inventory, and the
131
files are in a directory on disk.
133
It is possible for a `WorkingTree` to have a filename which is
134
not listed in the Inventory and vice versa.
136
def __init__(self, basedir, inv):
137
self._inventory = inv
138
self.basedir = basedir
139
self.path2id = inv.path2id
142
return "<%s of %s>" % (self.__class__.__name__,
145
def _rel(self, filename):
146
return os.path.join(self.basedir, filename)
148
def has_filename(self, filename):
149
return os.path.exists(self._rel(filename))
151
def get_file(self, file_id):
152
return file(self._get_store_filename(file_id), 'rb')
154
def _get_store_filename(self, file_id):
155
return self._rel(self.id2path(file_id))
157
def get_file_size(self, file_id):
158
return os.stat(self._get_store_filename(file_id))[ST_SIZE]
160
def get_file_sha1(self, file_id):
161
f = self.get_file(file_id)
165
def file_class(self, filename):
166
if self.path2id(filename):
168
elif self.is_ignored(filename):
174
def file_kind(self, filename):
175
if isfile(self._rel(filename)):
177
elif isdir(self._rel(filename)):
183
def list_files(self):
184
"""Recursively list all files as (path, class, kind, id).
186
Lists, but does not descend into unversioned directories.
188
This does not include files that have been deleted in this
191
Skips the control directory.
195
def descend(from_dir, from_dir_id, dp):
199
if bzrlib.BZRDIR == f:
203
fp = appendpath(from_dir, f)
206
fap = appendpath(dp, f)
208
f_ie = inv.get_child(from_dir_id, f)
211
elif self.is_ignored(fp):
220
bailout("file %r entered as kind %r id %r, now of kind %r"
221
% (fap, f_ie.kind, f_ie.file_id, fk))
223
yield fp, c, fk, (f_ie and f_ie.file_id)
225
if fk != 'directory':
229
# don't descend unversioned directories
232
for ff in descend(fp, f_ie.file_id, fap):
235
for f in descend('', None, self.basedir):
240
def unknowns(self, path='', dir_id=None):
241
"""Yield names of unknown files in this WorkingTree.
243
If there are any unknown directories then only the directory is
244
returned, not all its children. But if there are unknown files
245
under a versioned subdirectory, they are returned.
247
Currently returned depth-first, sorted by name within directories.
249
for fpath, fclass, fkind, fid in self.list_files():
254
def ignored_files(self):
255
for fpath, fclass, fkind, fid in self.list_files():
260
def is_ignored(self, filename):
261
"""Check whether the filename matches an ignore pattern."""
262
## TODO: Take them from a file, not hardcoded
263
## TODO: Use extended zsh-style globs maybe?
264
## TODO: Use '**' to match directories?
265
## TODO: Patterns without / should match in subdirectories?
266
for i in bzrlib.DEFAULT_IGNORE:
267
if fnmatch.fnmatchcase(filename, i):
275
class RevisionTree(Tree):
276
"""Tree viewing a previous revision.
278
File text can be retrieved from the text store.
280
:todo: Some kind of `__repr__` method, but a good one
281
probably means knowing the branch and revision number,
282
or at least passing a description to the constructor.
285
def __init__(self, store, inv):
287
self._inventory = inv
289
def get_file(self, file_id):
290
ie = self._inventory[file_id]
291
f = self._store[ie.text_id]
292
mutter(" get fileid{%s} from %r" % (file_id, self))
294
if ie.text_size is None:
295
note("warning: no text size recorded on %r" % ie)
296
self._check_retrieved(ie, f)
299
def get_file_size(self, file_id):
300
return self._inventory[file_id].text_size
302
def get_file_sha1(self, file_id):
303
ie = self._inventory[file_id]
306
def has_filename(self, filename):
307
return bool(self.inventory.path2id(filename))
309
def list_files(self):
310
# The only files returned by this are those from the version
311
for path, entry in self.inventory.iter_entries():
312
yield path, 'V', entry.kind, entry.file_id
315
class EmptyTree(Tree):
317
self._inventory = Inventory()
319
def has_filename(self, filename):
322
def list_files(self):
323
if False: # just to make it a generator
328
######################################################################
331
# TODO: Merge these two functions into a single one that can operate
332
# on either a whole tree or a set of files.
334
# TODO: Return the diff in order by filename, not by category or in
335
# random order. Can probably be done by lock-stepping through the
336
# filenames from both trees.
339
def file_status(filename, old_tree, new_tree):
340
"""Return single-letter status, old and new names for a file.
342
The complexity here is in deciding how to represent renames;
343
many complex cases are possible.
345
old_inv = old_tree.inventory
346
new_inv = new_tree.inventory
347
new_id = new_inv.path2id(filename)
348
old_id = old_inv.path2id(filename)
350
if not new_id and not old_id:
351
# easy: doesn't exist in either; not versioned at all
352
if new_tree.is_ignored(filename):
353
return 'I', None, None
355
return '?', None, None
357
# There is now a file of this name, great.
360
# There is no longer a file of this name, but we can describe
361
# what happened to the file that used to have
362
# this name. There are two possibilities: either it was
363
# deleted entirely, or renamed.
365
if new_inv.has_id(old_id):
366
return 'X', old_inv.id2path(old_id), new_inv.id2path(old_id)
368
return 'D', old_inv.id2path(old_id), None
370
# if the file_id is new in this revision, it is added
371
if new_id and not old_inv.has_id(new_id):
374
# if there used to be a file of this name, but that ID has now
375
# disappeared, it is deleted
376
if old_id and not new_inv.has_id(old_id):