~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
20
21
from sets import Set
21
22
import os.path, os, fnmatch
22
23
 
23
 
from osutils import pumpfile, filesize, quotefn, sha_file, \
24
 
     joinpath, splitpath, appendpath, isdir, isfile, file_kind, fingerprint_file
25
 
import errno
26
 
from stat import S_ISREG, S_ISDIR, ST_MODE, ST_SIZE
27
 
 
28
24
from inventory import Inventory
29
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
30
28
from errors import bailout
31
29
import branch
 
30
from stat import S_ISREG, S_ISDIR, ST_MODE, ST_SIZE
32
31
 
33
32
import bzrlib
34
33
 
54
53
    trees or versioned trees.
55
54
    """
56
55
    
 
56
    def get_file(self, file_id):
 
57
        """Return an open file-like object for given file id."""
 
58
        raise NotImplementedError()
 
59
 
57
60
    def has_filename(self, filename):
58
61
        """True if the tree has given filename."""
59
62
        raise NotImplementedError()
61
64
    def has_id(self, file_id):
62
65
        return self.inventory.has_id(file_id)
63
66
 
64
 
    __contains__ = has_id
65
 
 
66
67
    def id_set(self):
67
68
        """Return set of all ids in this tree."""
68
69
        return self.inventory.id_set()
69
70
 
70
 
    def __iter__(self):
71
 
        return iter(self.inventory)
72
 
 
73
71
    def id2path(self, file_id):
74
72
        return self.inventory.id2path(file_id)
75
73
 
80
78
                         doc="Inventory of this Tree")
81
79
 
82
80
    def _check_retrieved(self, ie, f):
83
 
        fp = fingerprint_file(f)
84
 
        f.seek(0)
85
 
        
86
 
        if ie.text_size != None:
87
 
            if ie.text_size != fp['size']:
 
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:
88
85
                bailout("mismatched size for file %r in %r" % (ie.file_id, self._store),
89
86
                        ["inventory expects %d bytes" % ie.text_size,
90
 
                         "file is actually %d bytes" % fp['size'],
 
87
                         "file is actually %d bytes" % fs,
91
88
                         "store is probably damaged/corrupt"])
92
89
 
93
 
        if ie.text_sha1 != fp['sha1']:
 
90
        f_hash = sha_file(f)
 
91
        f.seek(0)
 
92
        if ie.text_sha1 != f_hash:
94
93
            bailout("wrong SHA-1 for file %r in %r" % (ie.file_id, self._store),
95
94
                    ["inventory expects %s" % ie.text_sha1,
96
 
                     "file is actually %s" % fp['sha1'],
 
95
                     "file is actually %s" % f_hash,
97
96
                     "store is probably damaged/corrupt"])
98
97
 
99
98
 
100
 
    def print_file(self, fileid):
101
 
        """Print file with id `fileid` to stdout."""
102
 
        import sys
103
 
        pumpfile(self.get_file(fileid), sys.stdout)
104
 
        
105
 
        
106
 
    def export(self, dest):        
 
99
    def export(self, dest):
107
100
        """Export this tree to a new directory.
108
101
 
109
102
        `dest` should not exist, and will be created holding the
110
103
        contents of this tree.
111
104
 
112
 
        TODO: To handle subdirectories we need to create the
 
105
        :todo: To handle subdirectories we need to create the
113
106
               directories first.
114
107
 
115
108
        :note: If the export fails, the destination directory will be
126
119
            elif kind == 'file':
127
120
                pumpfile(self.get_file(ie.file_id), file(fullpath, 'wb'))
128
121
            else:
129
 
                bailout("don't know how to export {%s} of kind %r" % (ie.file_id, kind))
 
122
                bailout("don't know how to export {%s} of kind %r", fid, kind)
130
123
            mutter("  export {%s} kind %s to %s" % (ie.file_id, kind, fullpath))
131
124
 
132
125
 
133
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
        
 
274
 
134
275
class RevisionTree(Tree):
135
276
    """Tree viewing a previous revision.
136
277
 
137
278
    File text can be retrieved from the text store.
138
279
 
139
 
    TODO: Some kind of `__repr__` method, but a good one
 
280
    :todo: Some kind of `__repr__` method, but a good one
140
281
           probably means knowing the branch and revision number,
141
282
           or at least passing a description to the constructor.
142
283
    """
149
290
        ie = self._inventory[file_id]
150
291
        f = self._store[ie.text_id]
151
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)
152
296
        self._check_retrieved(ie, f)
153
297
        return f
154
298
 
236
380
 
237
381
    
238
382
 
239
 
def find_renames(old_inv, new_inv):
240
 
    for file_id in old_inv:
241
 
        if file_id not in new_inv:
242
 
            continue
243
 
        old_name = old_inv.id2path(file_id)
244
 
        new_name = new_inv.id2path(file_id)
245
 
        if old_name != new_name:
246
 
            yield (old_name, new_name)
247