~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tree.py

  • Committer: Martin Pool
  • Date: 2005-05-05 02:43:47 UTC
  • Revision ID: mbp@sourcefrog.net-20050505024347-8cc27a7a75e4d9ea
- add-bzr-to-baz utility script

Show diffs side-by-side

added added

removed removed

Lines of Context:
20
20
from sets import Set
21
21
import os.path, os, fnmatch
22
22
 
 
23
from osutils import pumpfile, compare_files, 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
 
23
28
from inventory import Inventory
24
29
from trace import mutter, note
25
 
from osutils import pumpfile, compare_files, filesize, quotefn, sha_file, \
26
 
     joinpath, splitpath, appendpath, isdir, isfile, file_kind
27
30
from errors import bailout
28
31
import branch
29
 
from stat import S_ISREG, S_ISDIR, ST_MODE, ST_SIZE
30
32
 
31
33
import bzrlib
32
34
 
73
75
                         doc="Inventory of this Tree")
74
76
 
75
77
    def _check_retrieved(self, ie, f):
76
 
        # TODO: Test this check by damaging the store?
77
 
        if ie.text_size is not None:
78
 
            fs = filesize(f)
79
 
            if fs != ie.text_size:
 
78
        fp = fingerprint_file(f)
 
79
        f.seek(0)
 
80
        
 
81
        if ie.text_size != None:
 
82
            if ie.text_size != fp['size']:
80
83
                bailout("mismatched size for file %r in %r" % (ie.file_id, self._store),
81
84
                        ["inventory expects %d bytes" % ie.text_size,
82
 
                         "file is actually %d bytes" % fs,
 
85
                         "file is actually %d bytes" % fp['size'],
83
86
                         "store is probably damaged/corrupt"])
84
87
 
85
 
        f_hash = sha_file(f)
86
 
        f.seek(0)
87
 
        if ie.text_sha1 != f_hash:
 
88
        if ie.text_sha1 != fp['sha1']:
88
89
            bailout("wrong SHA-1 for file %r in %r" % (ie.file_id, self._store),
89
90
                    ["inventory expects %s" % ie.text_sha1,
90
 
                     "file is actually %s" % f_hash,
 
91
                     "file is actually %s" % fp['sha1'],
91
92
                     "store is probably damaged/corrupt"])
92
93
 
93
94
 
94
 
    def export(self, dest):
 
95
    def print_file(self, fileid):
 
96
        """Print file with id `fileid` to stdout."""
 
97
        import sys
 
98
        pumpfile(self.get_file(fileid), sys.stdout)
 
99
        
 
100
        
 
101
    def export(self, dest):        
95
102
        """Export this tree to a new directory.
96
103
 
97
104
        `dest` should not exist, and will be created holding the
98
105
        contents of this tree.
99
106
 
100
 
        :todo: To handle subdirectories we need to create the
 
107
        TODO: To handle subdirectories we need to create the
101
108
               directories first.
102
109
 
103
110
        :note: If the export fails, the destination directory will be
114
121
            elif kind == 'file':
115
122
                pumpfile(self.get_file(ie.file_id), file(fullpath, 'wb'))
116
123
            else:
117
 
                bailout("don't know how to export {%s} of kind %r", fid, kind)
 
124
                bailout("don't know how to export {%s} of kind %r" % (fid, kind))
118
125
            mutter("  export {%s} kind %s to %s" % (ie.file_id, kind, fullpath))
119
126
 
120
127
 
150
157
        return file(self.abspath(filename), 'rb')
151
158
 
152
159
    def _get_store_filename(self, file_id):
 
160
        ## XXX: badly named; this isn't in the store at all
153
161
        return self.abspath(self.id2path(file_id))
154
162
 
155
163
    def has_id(self, file_id):
175
183
            return '?'
176
184
 
177
185
 
178
 
    def file_kind(self, filename):
179
 
        if isfile(self.abspath(filename)):
180
 
            return 'file'
181
 
        elif isdir(self.abspath(filename)):
182
 
            return 'directory'
183
 
        else:
184
 
            return 'unknown'
185
 
 
186
 
 
187
186
    def list_files(self):
188
187
        """Recursively list all files as (path, class, kind, id).
189
188
 
196
195
        """
197
196
        inv = self.inventory
198
197
 
199
 
        def descend(from_dir, from_dir_id, dp):
 
198
        def descend(from_dir_relpath, from_dir_id, dp):
200
199
            ls = os.listdir(dp)
201
200
            ls.sort()
202
201
            for f in ls:
 
202
                ## TODO: If we find a subdirectory with its own .bzr
 
203
                ## directory, then that is a separate tree and we
 
204
                ## should exclude it.
203
205
                if bzrlib.BZRDIR == f:
204
206
                    continue
205
207
 
206
208
                # path within tree
207
 
                fp = appendpath(from_dir, f)
 
209
                fp = appendpath(from_dir_relpath, f)
208
210
 
209
211
                # absolute path
210
212
                fap = appendpath(dp, f)
236
238
                for ff in descend(fp, f_ie.file_id, fap):
237
239
                    yield ff
238
240
 
239
 
        for f in descend('', None, self.basedir):
 
241
        for f in descend('', inv.root.file_id, self.basedir):
240
242
            yield f
241
243
            
242
244
 
243
245
 
244
 
    def unknowns(self, path='', dir_id=None):
245
 
        """Yield names of unknown files in this WorkingTree.
 
246
    def unknowns(self):
 
247
        for subp in self.extras():
 
248
            if not self.is_ignored(subp):
 
249
                yield subp
 
250
 
 
251
 
 
252
    def extras(self):
 
253
        """Yield all unknown files in this WorkingTree.
246
254
 
247
255
        If there are any unknown directories then only the directory is
248
256
        returned, not all its children.  But if there are unknown files
250
258
 
251
259
        Currently returned depth-first, sorted by name within directories.
252
260
        """
253
 
        for fpath, fclass, fkind, fid in self.list_files():
254
 
            if fclass == '?':
255
 
                yield fpath
256
 
                
 
261
        ## TODO: Work from given directory downwards
 
262
        
 
263
        for path, dir_entry in self.inventory.directories():
 
264
            mutter("search for unknowns in %r" % path)
 
265
            dirabs = self.abspath(path)
 
266
            if not isdir(dirabs):
 
267
                # e.g. directory deleted
 
268
                continue
 
269
 
 
270
            fl = []
 
271
            for subf in os.listdir(dirabs):
 
272
                if (subf != '.bzr'
 
273
                    and (subf not in dir_entry.children)):
 
274
                    fl.append(subf)
 
275
            
 
276
            fl.sort()
 
277
            for subf in fl:
 
278
                subp = appendpath(path, subf)
 
279
                yield subp
 
280
 
257
281
 
258
282
    def ignored_files(self):
259
 
        for fpath, fclass, fkind, fid in self.list_files():
260
 
            if fclass == 'I':
261
 
                yield fpath
 
283
        """Yield list of PATH, IGNORE_PATTERN"""
 
284
        for subp in self.extras():
 
285
            pat = self.is_ignored(subp)
 
286
            if pat != None:
 
287
                yield subp, pat
262
288
 
263
289
 
264
290
    def get_ignore_list(self):
278
304
 
279
305
 
280
306
    def is_ignored(self, filename):
281
 
        """Check whether the filename matches an ignore pattern.
282
 
 
283
 
        Patterns containing '/' need to match the whole path; others
284
 
        match against only the last component."""
285
 
        ## TODO: Use extended zsh-style globs maybe?
286
 
        ## TODO: Use '**' to match directories?
 
307
        r"""Check whether the filename matches an ignore pattern.
 
308
 
 
309
        Patterns containing '/' or '\' need to match the whole path;
 
310
        others match against only the last component.
 
311
 
 
312
        If the file is ignored, returns the pattern which caused it to
 
313
        be ignored, otherwise None.  So this can simply be used as a
 
314
        boolean if desired."""
 
315
 
 
316
        # TODO: Use '**' to match directories, and other extended
 
317
        # globbing stuff from cvs/rsync.
 
318
 
 
319
        # XXX: fnmatch is actually not quite what we want: it's only
 
320
        # approximately the same as real Unix fnmatch, and doesn't
 
321
        # treat dotfiles correctly and allows * to match /.
 
322
        # Eventually it should be replaced with something more
 
323
        # accurate.
 
324
        
287
325
        for pat in self.get_ignore_list():
288
 
            if '/' in pat:
289
 
                if fnmatch.fnmatchcase(filename, pat):
290
 
                    return True
 
326
            if '/' in pat or '\\' in pat:
 
327
                
 
328
                # as a special case, you can put ./ at the start of a
 
329
                # pattern; this is good to match in the top-level
 
330
                # only;
 
331
                
 
332
                if (pat[:2] == './') or (pat[:2] == '.\\'):
 
333
                    newpat = pat[2:]
 
334
                else:
 
335
                    newpat = pat
 
336
                if fnmatch.fnmatchcase(filename, newpat):
 
337
                    return pat
291
338
            else:
292
339
                if fnmatch.fnmatchcase(splitpath(filename)[-1], pat):
293
 
                    return True
294
 
        return False
 
340
                    return pat
 
341
        return None
295
342
        
296
343
 
297
344
        
302
349
 
303
350
    File text can be retrieved from the text store.
304
351
 
305
 
    :todo: Some kind of `__repr__` method, but a good one
 
352
    TODO: Some kind of `__repr__` method, but a good one
306
353
           probably means knowing the branch and revision number,
307
354
           or at least passing a description to the constructor.
308
355
    """
315
362
        ie = self._inventory[file_id]
316
363
        f = self._store[ie.text_id]
317
364
        mutter("  get fileid{%s} from %r" % (file_id, self))
318
 
        fs = filesize(f)
319
 
        if ie.text_size is None:
320
 
            note("warning: no text size recorded on %r" % ie)
321
365
        self._check_retrieved(ie, f)
322
366
        return f
323
367
 
405
449
 
406
450
    
407
451
 
 
452
def find_renames(old_inv, new_inv):
 
453
    for file_id in old_inv:
 
454
        if file_id not in new_inv:
 
455
            continue
 
456
        old_name = old_inv.id2path(file_id)
 
457
        new_name = new_inv.id2path(file_id)
 
458
        if old_name != new_name:
 
459
            yield (old_name, new_name)
 
460