~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tree.py

  • Committer: mbp at sourcefrog
  • Date: 2005-03-09 04:08:15 UTC
  • Revision ID: mbp@sourcefrog.net-20050309040815-13242001617e4a06
import from baz patch-364

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 Canonical Ltd
 
1
#! /usr/bin/env python
 
2
# -*- coding: UTF-8 -*-
2
3
 
3
4
# This program is free software; you can redistribute it and/or modify
4
5
# it under the terms of the GNU General Public License as published by
17
18
"""Tree classes, representing directory at point in time.
18
19
"""
19
20
 
20
 
import os
21
 
from cStringIO import StringIO
 
21
from sets import Set
 
22
import os.path, os, fnmatch
 
23
 
 
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
 
29
import branch
 
30
from stat import S_ISREG, S_ISDIR, ST_MODE, ST_SIZE
22
31
 
23
32
import bzrlib
24
 
from bzrlib.trace import mutter, note
25
 
from bzrlib.errors import BzrError, BzrCheckError
26
 
from bzrlib.inventory import Inventory
27
 
from bzrlib.osutils import appendpath, fingerprint_file
28
 
 
29
 
 
30
 
exporters = {}
31
 
 
32
 
class Tree(object):
 
33
 
 
34
class Tree:
33
35
    """Abstract file tree.
34
36
 
35
37
    There are several subclasses:
51
53
    trees or versioned trees.
52
54
    """
53
55
    
 
56
    def get_file(self, file_id):
 
57
        """Return an open file-like object for given file id."""
 
58
        raise NotImplementedError()
 
59
 
54
60
    def has_filename(self, filename):
55
61
        """True if the tree has given filename."""
56
62
        raise NotImplementedError()
58
64
    def has_id(self, file_id):
59
65
        return self.inventory.has_id(file_id)
60
66
 
61
 
    def has_or_had_id(self, file_id):
62
 
        if file_id == self.inventory.root.file_id:
63
 
            return True
64
 
        return self.inventory.has_id(file_id)
65
 
 
66
 
    __contains__ = has_id
67
 
 
68
 
    def __iter__(self):
69
 
        return iter(self.inventory)
 
67
    def id_set(self):
 
68
        """Return set of all ids in this tree."""
 
69
        return self.inventory.id_set()
70
70
 
71
71
    def id2path(self, file_id):
72
72
        return self.inventory.id2path(file_id)
73
73
 
74
74
    def _get_inventory(self):
75
75
        return self._inventory
76
 
    
77
 
    def get_file_by_path(self, path):
78
 
        return self.get_file(self._inventory.path2id(path))
79
76
 
80
77
    inventory = property(_get_inventory,
81
78
                         doc="Inventory of this Tree")
82
79
 
83
80
    def _check_retrieved(self, ie, f):
84
 
        if not __debug__:
85
 
            return  
86
 
        fp = fingerprint_file(f)
87
 
        f.seek(0)
88
 
        
89
 
        if ie.text_size != None:
90
 
            if ie.text_size != fp['size']:
91
 
                raise BzrError("mismatched size for file %r in %r" % (ie.file_id, self._store),
 
81
        # TODO: Test this check by damaging the store?
 
82
        if ie.text_size is not None:
 
83
            fs = filesize(f)
 
84
            if fs != ie.text_size:
 
85
                bailout("mismatched size for file %r in %r" % (ie.file_id, self._store),
92
86
                        ["inventory expects %d bytes" % ie.text_size,
93
 
                         "file is actually %d bytes" % fp['size'],
 
87
                         "file is actually %d bytes" % fs,
94
88
                         "store is probably damaged/corrupt"])
95
89
 
96
 
        if ie.text_sha1 != fp['sha1']:
97
 
            raise BzrError("wrong SHA-1 for file %r in %r" % (ie.file_id, self._store),
 
90
        f_hash = sha_file(f)
 
91
        f.seek(0)
 
92
        if ie.text_sha1 != f_hash:
 
93
            bailout("wrong SHA-1 for file %r in %r" % (ie.file_id, self._store),
98
94
                    ["inventory expects %s" % ie.text_sha1,
99
 
                     "file is actually %s" % fp['sha1'],
 
95
                     "file is actually %s" % f_hash,
100
96
                     "store is probably damaged/corrupt"])
101
97
 
102
98
 
103
 
    def print_file(self, file_id):
104
 
        """Print file with id `file_id` to stdout."""
105
 
        import sys
106
 
        sys.stdout.write(self.get_file_text(file_id))
107
 
        
108
 
        
109
 
    def export(self, dest, format='dir', root=None):
110
 
        """Export this tree."""
111
 
        try:
112
 
            exporter = exporters[format]
113
 
        except KeyError:
114
 
            from bzrlib.errors import BzrCommandError
115
 
            raise BzrCommandError("export format %r not supported" % format)
116
 
        exporter(self, dest, root)
117
 
 
118
 
 
 
99
    def export(self, dest):
 
100
        """Export this tree to a new directory.
 
101
 
 
102
        `dest` should not exist, and will be created holding the
 
103
        contents of this tree.
 
104
 
 
105
        :todo: To handle subdirectories we need to create the
 
106
               directories first.
 
107
 
 
108
        :note: If the export fails, the destination directory will be
 
109
               left in a half-assed state.
 
110
        """
 
111
        os.mkdir(dest)
 
112
        mutter('export version %r' % self)
 
113
        inv = self.inventory
 
114
        for dp, ie in inv.iter_entries():
 
115
            kind = ie.kind
 
116
            fullpath = appendpath(dest, dp)
 
117
            if kind == 'directory':
 
118
                os.mkdir(fullpath)
 
119
            elif kind == 'file':
 
120
                pumpfile(self.get_file(ie.file_id), file(fullpath, 'wb'))
 
121
            else:
 
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))
 
124
 
 
125
 
 
126
 
 
127
class WorkingTree(Tree):
 
128
    """Working copy tree.
 
129
 
 
130
    The inventory is held in the `Branch` working-inventory, and the
 
131
    files are in a directory on disk.
 
132
 
 
133
    It is possible for a `WorkingTree` to have a filename which is
 
134
    not listed in the Inventory and vice versa.
 
135
    """
 
136
    def __init__(self, basedir, inv):
 
137
        self._inventory = inv
 
138
        self.basedir = basedir
 
139
        self.path2id = inv.path2id
 
140
 
 
141
    def __repr__(self):
 
142
        return "<%s of %s>" % (self.__class__.__name__,
 
143
                               self.basedir)
 
144
 
 
145
    def _rel(self, filename):
 
146
        return os.path.join(self.basedir, filename)
 
147
 
 
148
    def has_filename(self, filename):
 
149
        return os.path.exists(self._rel(filename))
 
150
 
 
151
    def get_file(self, file_id):
 
152
        return file(self._get_store_filename(file_id), 'rb')
 
153
 
 
154
    def _get_store_filename(self, file_id):
 
155
        return self._rel(self.id2path(file_id))
 
156
 
 
157
    def get_file_size(self, file_id):
 
158
        return os.stat(self._get_store_filename(file_id))[ST_SIZE]
 
159
 
 
160
    def get_file_sha1(self, file_id):
 
161
        f = self.get_file(file_id)
 
162
        return sha_file(f)
 
163
 
 
164
 
 
165
    def file_class(self, filename):
 
166
        if self.path2id(filename):
 
167
            return 'V'
 
168
        elif self.is_ignored(filename):
 
169
            return 'I'
 
170
        else:
 
171
            return '?'
 
172
 
 
173
 
 
174
    def file_kind(self, filename):
 
175
        if isfile(self._rel(filename)):
 
176
            return 'file'
 
177
        elif isdir(self._rel(filename)):
 
178
            return 'directory'
 
179
        else:
 
180
            return 'unknown'
 
181
 
 
182
 
 
183
    def list_files(self):
 
184
        """Recursively list all files as (path, class, kind, id).
 
185
 
 
186
        Lists, but does not descend into unversioned directories.
 
187
 
 
188
        This does not include files that have been deleted in this
 
189
        tree.
 
190
 
 
191
        Skips the control directory.
 
192
        """
 
193
        inv = self.inventory
 
194
 
 
195
        def descend(from_dir, from_dir_id, dp):
 
196
            ls = os.listdir(dp)
 
197
            ls.sort()
 
198
            for f in ls:
 
199
                if bzrlib.BZRDIR == f:
 
200
                    continue
 
201
 
 
202
                # path within tree
 
203
                fp = appendpath(from_dir, f)
 
204
 
 
205
                # absolute path
 
206
                fap = appendpath(dp, f)
 
207
                
 
208
                f_ie = inv.get_child(from_dir_id, f)
 
209
                if f_ie:
 
210
                    c = 'V'
 
211
                elif self.is_ignored(fp):
 
212
                    c = 'I'
 
213
                else:
 
214
                    c = '?'
 
215
 
 
216
                fk = file_kind(fap)
 
217
 
 
218
                if f_ie:
 
219
                    if f_ie.kind != fk:
 
220
                        bailout("file %r entered as kind %r id %r, now of kind %r"
 
221
                                % (fap, f_ie.kind, f_ie.file_id, fk))
 
222
 
 
223
                yield fp, c, fk, (f_ie and f_ie.file_id)
 
224
 
 
225
                if fk != 'directory':
 
226
                    continue
 
227
 
 
228
                if c != 'V':
 
229
                    # don't descend unversioned directories
 
230
                    continue
 
231
                
 
232
                for ff in descend(fp, f_ie.file_id, fap):
 
233
                    yield ff
 
234
 
 
235
        for f in descend('', None, self.basedir):
 
236
            yield f
 
237
            
 
238
 
 
239
 
 
240
    def unknowns(self, path='', dir_id=None):
 
241
        """Yield names of unknown files in this WorkingTree.
 
242
 
 
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.
 
246
 
 
247
        Currently returned depth-first, sorted by name within directories.
 
248
        """
 
249
        for fpath, fclass, fkind, fid in self.list_files():
 
250
            if fclass == '?':
 
251
                yield fpath
 
252
                
 
253
 
 
254
    def ignored_files(self):
 
255
        for fpath, fclass, fkind, fid in self.list_files():
 
256
            if fclass == 'I':
 
257
                yield fpath
 
258
 
 
259
 
 
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):
 
268
                return True
 
269
        return False
 
270
        
 
271
 
 
272
        
 
273
        
119
274
 
120
275
class RevisionTree(Tree):
121
276
    """Tree viewing a previous revision.
122
277
 
123
278
    File text can be retrieved from the text store.
124
279
 
125
 
    TODO: Some kind of `__repr__` method, but a good one
 
280
    :todo: Some kind of `__repr__` method, but a good one
126
281
           probably means knowing the branch and revision number,
127
282
           or at least passing a description to the constructor.
128
283
    """
129
284
    
130
 
    def __init__(self, weave_store, inv, revision_id):
131
 
        self._weave_store = weave_store
 
285
    def __init__(self, store, inv):
 
286
        self._store = store
132
287
        self._inventory = inv
133
 
        self._revision_id = revision_id
134
 
 
135
 
    def get_weave(self, file_id):
136
 
        # FIXME: RevisionTree should be given a branch
137
 
        # not a store, or the store should know the branch.
138
 
        import bzrlib.transactions as transactions
139
 
        return self._weave_store.get_weave(file_id,
140
 
            transactions.PassThroughTransaction())
141
 
 
142
 
 
143
 
    def get_file_lines(self, file_id):
 
288
 
 
289
    def get_file(self, file_id):
144
290
        ie = self._inventory[file_id]
145
 
        weave = self.get_weave(file_id)
146
 
        return weave.get(ie.revision)
147
 
        
148
 
 
149
 
    def get_file_text(self, file_id):
150
 
        return ''.join(self.get_file_lines(file_id))
151
 
 
152
 
 
153
 
    def get_file(self, file_id):
154
 
        return StringIO(self.get_file_text(file_id))
 
291
        f = self._store[ie.text_id]
 
292
        mutter("  get fileid{%s} from %r" % (file_id, self))
 
293
        fs = filesize(f)
 
294
        if ie.text_size is None:
 
295
            note("warning: no text size recorded on %r" % ie)
 
296
        self._check_retrieved(ie, f)
 
297
        return f
155
298
 
156
299
    def get_file_size(self, file_id):
157
300
        return self._inventory[file_id].text_size
158
301
 
159
302
    def get_file_sha1(self, file_id):
160
303
        ie = self._inventory[file_id]
161
 
        if ie.kind == "file":
162
 
            return ie.text_sha1
163
 
 
164
 
    def is_executable(self, file_id):
165
 
        ie = self._inventory[file_id]
166
 
        if ie.kind != "file":
167
 
            return None 
168
 
        return self._inventory[file_id].executable
 
304
        return ie.text_sha1
169
305
 
170
306
    def has_filename(self, filename):
171
307
        return bool(self.inventory.path2id(filename))
173
309
    def list_files(self):
174
310
        # The only files returned by this are those from the version
175
311
        for path, entry in self.inventory.iter_entries():
176
 
            yield path, 'V', entry.kind, entry.file_id, entry
177
 
 
178
 
    def get_symlink_target(self, file_id):
179
 
        ie = self._inventory[file_id]
180
 
        return ie.symlink_target;
181
 
 
182
 
    def kind(self, file_id):
183
 
        return self._inventory[file_id].kind
 
312
            yield path, 'V', entry.kind, entry.file_id
 
313
 
184
314
 
185
315
class EmptyTree(Tree):
186
316
    def __init__(self):
187
317
        self._inventory = Inventory()
188
318
 
189
 
    def get_symlink_target(self, file_id):
190
 
        return None
191
 
 
192
319
    def has_filename(self, filename):
193
320
        return False
194
321
 
195
322
    def list_files(self):
196
 
        return iter([])
 
323
        if False:  # just to make it a generator
 
324
            yield None
197
325
    
198
 
    def __contains__(self, file_id):
199
 
        return file_id in self._inventory
200
 
 
201
 
    def get_file_sha1(self, file_id):
202
 
        assert self._inventory[file_id].kind == "root_directory"
203
 
        return None
204
326
 
205
327
 
206
328
######################################################################
258
380
 
259
381
    
260
382
 
261
 
def find_renames(old_inv, new_inv):
262
 
    for file_id in old_inv:
263
 
        if file_id not in new_inv:
264
 
            continue
265
 
        old_name = old_inv.id2path(file_id)
266
 
        new_name = new_inv.id2path(file_id)
267
 
        if old_name != new_name:
268
 
            yield (old_name, new_name)
269
 
            
270
 
 
271
 
 
272
 
######################################################################
273
 
# export
274
 
 
275
 
def dir_exporter(tree, dest, root):
276
 
    """Export this tree to a new directory.
277
 
 
278
 
    `dest` should not exist, and will be created holding the
279
 
    contents of this tree.
280
 
 
281
 
    TODO: To handle subdirectories we need to create the
282
 
           directories first.
283
 
 
284
 
    :note: If the export fails, the destination directory will be
285
 
           left in a half-assed state.
286
 
    """
287
 
    import os
288
 
    os.mkdir(dest)
289
 
    mutter('export version %r' % tree)
290
 
    inv = tree.inventory
291
 
    for dp, ie in inv.iter_entries():
292
 
        ie.put_on_disk(dest, dp, tree)
293
 
 
294
 
exporters['dir'] = dir_exporter
295
 
 
296
 
try:
297
 
    import tarfile
298
 
except ImportError:
299
 
    pass
300
 
else:
301
 
    def get_root_name(dest):
302
 
        """Get just the root name for a tarball.
303
 
 
304
 
        >>> get_root_name('mytar.tar')
305
 
        'mytar'
306
 
        >>> get_root_name('mytar.tar.bz2')
307
 
        'mytar'
308
 
        >>> get_root_name('tar.tar.tar.tgz')
309
 
        'tar.tar.tar'
310
 
        >>> get_root_name('bzr-0.0.5.tar.gz')
311
 
        'bzr-0.0.5'
312
 
        >>> get_root_name('a/long/path/mytar.tgz')
313
 
        'mytar'
314
 
        >>> get_root_name('../parent/../dir/other.tbz2')
315
 
        'other'
316
 
        """
317
 
        endings = ['.tar', '.tar.gz', '.tgz', '.tar.bz2', '.tbz2']
318
 
        dest = os.path.basename(dest)
319
 
        for end in endings:
320
 
            if dest.endswith(end):
321
 
                return dest[:-len(end)]
322
 
 
323
 
    def tar_exporter(tree, dest, root, compression=None):
324
 
        """Export this tree to a new tar file.
325
 
 
326
 
        `dest` will be created holding the contents of this tree; if it
327
 
        already exists, it will be clobbered, like with "tar -c".
328
 
        """
329
 
        from time import time
330
 
        now = time()
331
 
        compression = str(compression or '')
332
 
        if root is None:
333
 
            root = get_root_name(dest)
334
 
        try:
335
 
            ball = tarfile.open(dest, 'w:' + compression)
336
 
        except tarfile.CompressionError, e:
337
 
            raise BzrError(str(e))
338
 
        mutter('export version %r' % tree)
339
 
        inv = tree.inventory
340
 
        for dp, ie in inv.iter_entries():
341
 
            mutter("  export {%s} kind %s to %s" % (ie.file_id, ie.kind, dest))
342
 
            item, fileobj = ie.get_tar_item(root, dp, now, tree)
343
 
            ball.addfile(item, fileobj)
344
 
        ball.close()
345
 
 
346
 
    exporters['tar'] = tar_exporter
347
 
 
348
 
    def tgz_exporter(tree, dest, root):
349
 
        tar_exporter(tree, dest, root, compression='gz')
350
 
    exporters['tgz'] = tgz_exporter
351
 
 
352
 
    def tbz_exporter(tree, dest, root):
353
 
        tar_exporter(tree, dest, root, compression='bz2')
354
 
    exporters['tbz2'] = tbz_exporter