/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tree.py

  • Committer: Martin Pool
  • Date: 2005-06-29 04:11:40 UTC
  • Revision ID: mbp@sourcefrog.net-20050629041140-6b17e65a23ffdf47
Merge John's log patch:

implements bzr log --forward --verbose
optimizes so that only logs to be printed are read (rather than reading
all and filtering out unwanted).

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005 Canonical Ltd
 
2
 
 
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.
 
7
 
 
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.
 
12
 
 
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
 
16
 
 
17
"""Tree classes, representing directory at point in time.
 
18
"""
 
19
 
 
20
from osutils import pumpfile, appendpath, fingerprint_file
 
21
 
 
22
from bzrlib.trace import mutter, note
 
23
from bzrlib.errors import BzrError
 
24
 
 
25
import bzrlib
 
26
 
 
27
exporters = {}
 
28
 
 
29
class Tree(object):
 
30
    """Abstract file tree.
 
31
 
 
32
    There are several subclasses:
 
33
    
 
34
    * `WorkingTree` exists as files on disk editable by the user.
 
35
 
 
36
    * `RevisionTree` is a tree as recorded at some point in the past.
 
37
 
 
38
    * `EmptyTree`
 
39
 
 
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.
 
43
 
 
44
    It is possible for trees to contain files that are not described
 
45
    in their inventory or vice versa; for this use `filenames()`.
 
46
 
 
47
    Trees can be compared, etc, regardless of whether they are working
 
48
    trees or versioned trees.
 
49
    """
 
50
    
 
51
    def has_filename(self, filename):
 
52
        """True if the tree has given filename."""
 
53
        raise NotImplementedError()
 
54
 
 
55
    def has_id(self, file_id):
 
56
        return self.inventory.has_id(file_id)
 
57
 
 
58
    __contains__ = has_id
 
59
 
 
60
    def __iter__(self):
 
61
        return iter(self.inventory)
 
62
 
 
63
    def id2path(self, file_id):
 
64
        return self.inventory.id2path(file_id)
 
65
 
 
66
    def _get_inventory(self):
 
67
        return self._inventory
 
68
 
 
69
    inventory = property(_get_inventory,
 
70
                         doc="Inventory of this Tree")
 
71
 
 
72
    def _check_retrieved(self, ie, f):
 
73
        fp = fingerprint_file(f)
 
74
        f.seek(0)
 
75
        
 
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"])
 
82
 
 
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"])
 
88
 
 
89
 
 
90
    def print_file(self, fileid):
 
91
        """Print file with id `fileid` to stdout."""
 
92
        import sys
 
93
        pumpfile(self.get_file(fileid), sys.stdout)
 
94
        
 
95
        
 
96
    def export(self, dest, format='dir'):
 
97
        """Export this tree."""
 
98
        try:
 
99
            exporter = exporters[format]
 
100
        except KeyError:
 
101
            raise BzrCommandError("export format %r not supported" % format)
 
102
        exporter(self, dest)
 
103
 
 
104
 
 
105
 
 
106
class RevisionTree(Tree):
 
107
    """Tree viewing a previous revision.
 
108
 
 
109
    File text can be retrieved from the text store.
 
110
 
 
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.
 
114
    """
 
115
    
 
116
    def __init__(self, store, inv):
 
117
        self._store = store
 
118
        self._inventory = inv
 
119
 
 
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)
 
125
        return f
 
126
 
 
127
    def get_file_size(self, file_id):
 
128
        return self._inventory[file_id].text_size
 
129
 
 
130
    def get_file_sha1(self, file_id):
 
131
        ie = self._inventory[file_id]
 
132
        return ie.text_sha1
 
133
 
 
134
    def has_filename(self, filename):
 
135
        return bool(self.inventory.path2id(filename))
 
136
 
 
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
 
141
 
 
142
 
 
143
class EmptyTree(Tree):
 
144
    def __init__(self):
 
145
        from bzrlib.inventory import Inventory
 
146
        self._inventory = Inventory()
 
147
 
 
148
    def has_filename(self, filename):
 
149
        return False
 
150
 
 
151
    def list_files(self):
 
152
        if False:  # just to make it a generator
 
153
            yield None
 
154
    
 
155
 
 
156
 
 
157
######################################################################
 
158
# diff
 
159
 
 
160
# TODO: Merge these two functions into a single one that can operate
 
161
# on either a whole tree or a set of files.
 
162
 
 
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.
 
166
 
 
167
 
 
168
def file_status(filename, old_tree, new_tree):
 
169
    """Return single-letter status, old and new names for a file.
 
170
 
 
171
    The complexity here is in deciding how to represent renames;
 
172
    many complex cases are possible.
 
173
    """
 
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)
 
178
 
 
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
 
183
        else:
 
184
            return '?', None, None
 
185
    elif new_id:
 
186
        # There is now a file of this name, great.
 
187
        pass
 
188
    else:
 
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.
 
193
        assert old_id
 
194
        if new_inv.has_id(old_id):
 
195
            return 'X', old_inv.id2path(old_id), new_inv.id2path(old_id)
 
196
        else:
 
197
            return 'D', old_inv.id2path(old_id), None
 
198
 
 
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):
 
201
        return 'A'
 
202
 
 
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):
 
206
        return 'D'
 
207
 
 
208
    return 'wtf?'
 
209
 
 
210
    
 
211
 
 
212
def find_renames(old_inv, new_inv):
 
213
    for file_id in old_inv:
 
214
        if file_id not in new_inv:
 
215
            continue
 
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)
 
220
            
 
221
 
 
222
 
 
223
######################################################################
 
224
# export
 
225
 
 
226
def dir_exporter(tree, dest):
 
227
    """Export this tree to a new directory.
 
228
 
 
229
    `dest` should not exist, and will be created holding the
 
230
    contents of this tree.
 
231
 
 
232
    TODO: To handle subdirectories we need to create the
 
233
           directories first.
 
234
 
 
235
    :note: If the export fails, the destination directory will be
 
236
           left in a half-assed state.
 
237
    """
 
238
    import os
 
239
    os.mkdir(dest)
 
240
    mutter('export version %r' % tree)
 
241
    inv = tree.inventory
 
242
    for dp, ie in inv.iter_entries():
 
243
        kind = ie.kind
 
244
        fullpath = appendpath(dest, dp)
 
245
        if kind == 'directory':
 
246
            os.mkdir(fullpath)
 
247
        elif kind == 'file':
 
248
            pumpfile(tree.get_file(ie.file_id), file(fullpath, 'wb'))
 
249
        else:
 
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
 
253
 
 
254
try:
 
255
    import tarfile
 
256
except ImportError:
 
257
    pass
 
258
else:
 
259
    def tar_exporter(tree, dest, compression=None):
 
260
        """Export this tree to a new tar file.
 
261
 
 
262
        `dest` will be created holding the contents of this tree; if it
 
263
        already exists, it will be clobbered, like with "tar -c".
 
264
        """
 
265
        from time import time
 
266
        now = time()
 
267
        compression = str(compression or '')
 
268
        try:
 
269
            ball = tarfile.open(dest, 'w:' + compression)
 
270
        except tarfile.CompressionError, e:
 
271
            raise BzrError(str(e))
 
272
        mutter('export version %r' % tree)
 
273
        inv = tree.inventory
 
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
 
279
            item.mtime = now
 
280
            if ie.kind == 'directory':
 
281
                item.type = tarfile.DIRTYPE
 
282
                fileobj = None
 
283
                item.name += '/'
 
284
                item.size = 0
 
285
                item.mode = 0755
 
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)
 
290
                item.mode = 0644
 
291
            else:
 
292
                raise BzrError("don't know how to export {%s} of kind %r" %
 
293
                        (ie.file_id, ie.kind))
 
294
 
 
295
            ball.addfile(item, fileobj)
 
296
        ball.close()
 
297
    exporters['tar'] = tar_exporter
 
298
 
 
299
    def tgz_exporter(tree, dest):
 
300
        tar_exporter(tree, dest, compression='gz')
 
301
    exporters['tgz'] = tgz_exporter
 
302
 
 
303
    def tbz_exporter(tree, dest):
 
304
        tar_exporter(tree, dest, compression='bz2')
 
305
    exporters['tbz2'] = tbz_exporter
 
306
 
 
307
 
 
308
def _find_file_size(fileobj):
 
309
    offset = fileobj.tell()
 
310
    try:
 
311
        fileobj.seek(0, 2)
 
312
        size = fileobj.tell()
 
313
    except TypeError:
 
314
        # gzip doesn't accept second argument to seek()
 
315
        fileobj.seek(0)
 
316
        size = 0
 
317
        while True:
 
318
            nread = len(fileobj.read())
 
319
            if nread == 0:
 
320
                break
 
321
            size += nread
 
322
    fileobj.seek(offset)
 
323
    return size