/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/workingtree.py

  • Committer: Robert Collins
  • Date: 2005-10-18 06:42:17 UTC
  • mfrom: (0.2.1)
  • mto: This revision was merged to the branch mainline in revision 1463.
  • Revision ID: robertc@robertcollins.net-20051018064217-e810bd94c74a9ad1
Factor out the guts of 'pull' from the command into WorkingTree.pull().
(Robert Collins)

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
# TODO: Don't allow WorkingTrees to be constructed for remote branches.
 
18
 
 
19
# FIXME: I don't know if writing out the cache from the destructor is really a
 
20
# good idea, because destructors are considered poor taste in Python, and
 
21
# it's not predictable when it will be written out.
 
22
 
 
23
import os
 
24
import stat
 
25
import fnmatch
 
26
 
 
27
from bzrlib.branch import Branch, needs_read_lock, needs_write_lock, quotefn
 
28
import bzrlib.tree
 
29
from bzrlib.osutils import appendpath, file_kind, isdir, splitpath, relpath
 
30
from bzrlib.errors import BzrCheckError, DivergedBranches
 
31
from bzrlib.trace import mutter
 
32
 
 
33
class TreeEntry(object):
 
34
    """An entry that implements the minium interface used by commands.
 
35
 
 
36
    This needs further inspection, it may be better to have 
 
37
    InventoryEntries without ids - though that seems wrong. For now,
 
38
    this is a parallel hierarchy to InventoryEntry, and needs to become
 
39
    one of several things: decorates to that hierarchy, children of, or
 
40
    parents of it.
 
41
    Another note is that these objects are currently only used when there is
 
42
    no InventoryEntry available - i.e. for unversioned objects.
 
43
    Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
 
44
    """
 
45
 
 
46
    def __eq__(self, other):
 
47
        # yes, this us ugly, TODO: best practice __eq__ style.
 
48
        return (isinstance(other, TreeEntry)
 
49
                and other.__class__ == self.__class__)
 
50
 
 
51
    def kind_character(self):
 
52
        return "???"
 
53
 
 
54
 
 
55
class TreeDirectory(TreeEntry):
 
56
    """See TreeEntry. This is a directory in a working tree."""
 
57
 
 
58
    def __eq__(self, other):
 
59
        return (isinstance(other, TreeDirectory)
 
60
                and other.__class__ == self.__class__)
 
61
 
 
62
    def kind_character(self):
 
63
        return "/"
 
64
 
 
65
 
 
66
class TreeFile(TreeEntry):
 
67
    """See TreeEntry. This is a regular file in a working tree."""
 
68
 
 
69
    def __eq__(self, other):
 
70
        return (isinstance(other, TreeFile)
 
71
                and other.__class__ == self.__class__)
 
72
 
 
73
    def kind_character(self):
 
74
        return ''
 
75
 
 
76
 
 
77
class TreeLink(TreeEntry):
 
78
    """See TreeEntry. This is a symlink in a working tree."""
 
79
 
 
80
    def __eq__(self, other):
 
81
        return (isinstance(other, TreeLink)
 
82
                and other.__class__ == self.__class__)
 
83
 
 
84
    def kind_character(self):
 
85
        return ''
 
86
 
 
87
 
 
88
class WorkingTree(bzrlib.tree.Tree):
 
89
    """Working copy tree.
 
90
 
 
91
    The inventory is held in the `Branch` working-inventory, and the
 
92
    files are in a directory on disk.
 
93
 
 
94
    It is possible for a `WorkingTree` to have a filename which is
 
95
    not listed in the Inventory and vice versa.
 
96
    """
 
97
 
 
98
    def __init__(self, basedir, branch=None):
 
99
        """Construct a WorkingTree for basedir.
 
100
 
 
101
        If the branch is not supplied, it is opened automatically.
 
102
        If the branch is supplied, it must be the branch for this basedir.
 
103
        (branch.base is not cross checked, because for remote branches that
 
104
        would be meaningless).
 
105
        """
 
106
        from bzrlib.hashcache import HashCache
 
107
        from bzrlib.trace import note, mutter
 
108
 
 
109
        if branch is None:
 
110
            branch = Branch.open(basedir)
 
111
        self._inventory = branch.inventory
 
112
        self.path2id = self._inventory.path2id
 
113
        self.branch = branch
 
114
        self.basedir = basedir
 
115
 
 
116
        # update the whole cache up front and write to disk if anything changed;
 
117
        # in the future we might want to do this more selectively
 
118
        hc = self._hashcache = HashCache(basedir)
 
119
        hc.read()
 
120
        hc.scan()
 
121
 
 
122
        if hc.needs_write:
 
123
            mutter("write hc")
 
124
            hc.write()
 
125
            
 
126
            
 
127
    def __del__(self):
 
128
        if self._hashcache.needs_write:
 
129
            self._hashcache.write()
 
130
 
 
131
 
 
132
    def __iter__(self):
 
133
        """Iterate through file_ids for this tree.
 
134
 
 
135
        file_ids are in a WorkingTree if they are in the working inventory
 
136
        and the working file exists.
 
137
        """
 
138
        inv = self._inventory
 
139
        for path, ie in inv.iter_entries():
 
140
            if bzrlib.osutils.lexists(self.abspath(path)):
 
141
                yield ie.file_id
 
142
 
 
143
 
 
144
    def __repr__(self):
 
145
        return "<%s of %s>" % (self.__class__.__name__,
 
146
                               getattr(self, 'basedir', None))
 
147
 
 
148
 
 
149
 
 
150
    def abspath(self, filename):
 
151
        return os.path.join(self.basedir, filename)
 
152
 
 
153
    def relpath(self, abspath):
 
154
        """Return the local path portion from a given absolute path."""
 
155
        return relpath(self.basedir, abspath)
 
156
 
 
157
    def has_filename(self, filename):
 
158
        return bzrlib.osutils.lexists(self.abspath(filename))
 
159
 
 
160
    def get_file(self, file_id):
 
161
        return self.get_file_byname(self.id2path(file_id))
 
162
 
 
163
    def get_file_byname(self, filename):
 
164
        return file(self.abspath(filename), 'rb')
 
165
 
 
166
    def _get_store_filename(self, file_id):
 
167
        ## XXX: badly named; this isn't in the store at all
 
168
        return self.abspath(self.id2path(file_id))
 
169
 
 
170
 
 
171
    def id2abspath(self, file_id):
 
172
        return self.abspath(self.id2path(file_id))
 
173
 
 
174
                
 
175
    def has_id(self, file_id):
 
176
        # files that have been deleted are excluded
 
177
        inv = self._inventory
 
178
        if not inv.has_id(file_id):
 
179
            return False
 
180
        path = inv.id2path(file_id)
 
181
        return bzrlib.osutils.lexists(self.abspath(path))
 
182
 
 
183
    def has_or_had_id(self, file_id):
 
184
        if file_id == self.inventory.root.file_id:
 
185
            return True
 
186
        return self.inventory.has_id(file_id)
 
187
 
 
188
    __contains__ = has_id
 
189
    
 
190
 
 
191
    def get_file_size(self, file_id):
 
192
        return os.path.getsize(self.id2abspath(file_id))
 
193
 
 
194
    def get_file_sha1(self, file_id):
 
195
        path = self._inventory.id2path(file_id)
 
196
        return self._hashcache.get_sha1(path)
 
197
 
 
198
 
 
199
    def is_executable(self, file_id):
 
200
        if os.name == "nt":
 
201
            return self._inventory[file_id].executable
 
202
        else:
 
203
            path = self._inventory.id2path(file_id)
 
204
            mode = os.lstat(self.abspath(path)).st_mode
 
205
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC&mode)
 
206
 
 
207
    def get_symlink_target(self, file_id):
 
208
        return os.readlink(self.id2abspath(file_id))
 
209
 
 
210
    def file_class(self, filename):
 
211
        if self.path2id(filename):
 
212
            return 'V'
 
213
        elif self.is_ignored(filename):
 
214
            return 'I'
 
215
        else:
 
216
            return '?'
 
217
 
 
218
 
 
219
    def list_files(self):
 
220
        """Recursively list all files as (path, class, kind, id).
 
221
 
 
222
        Lists, but does not descend into unversioned directories.
 
223
 
 
224
        This does not include files that have been deleted in this
 
225
        tree.
 
226
 
 
227
        Skips the control directory.
 
228
        """
 
229
        inv = self._inventory
 
230
 
 
231
        def descend(from_dir_relpath, from_dir_id, dp):
 
232
            ls = os.listdir(dp)
 
233
            ls.sort()
 
234
            for f in ls:
 
235
                ## TODO: If we find a subdirectory with its own .bzr
 
236
                ## directory, then that is a separate tree and we
 
237
                ## should exclude it.
 
238
                if bzrlib.BZRDIR == f:
 
239
                    continue
 
240
 
 
241
                # path within tree
 
242
                fp = appendpath(from_dir_relpath, f)
 
243
 
 
244
                # absolute path
 
245
                fap = appendpath(dp, f)
 
246
                
 
247
                f_ie = inv.get_child(from_dir_id, f)
 
248
                if f_ie:
 
249
                    c = 'V'
 
250
                elif self.is_ignored(fp):
 
251
                    c = 'I'
 
252
                else:
 
253
                    c = '?'
 
254
 
 
255
                fk = file_kind(fap)
 
256
 
 
257
                if f_ie:
 
258
                    if f_ie.kind != fk:
 
259
                        raise BzrCheckError("file %r entered as kind %r id %r, "
 
260
                                            "now of kind %r"
 
261
                                            % (fap, f_ie.kind, f_ie.file_id, fk))
 
262
 
 
263
                # make a last minute entry
 
264
                if f_ie:
 
265
                    entry = f_ie
 
266
                else:
 
267
                    if fk == 'directory':
 
268
                        entry = TreeDirectory()
 
269
                    elif fk == 'file':
 
270
                        entry = TreeFile()
 
271
                    elif fk == 'symlink':
 
272
                        entry = TreeLink()
 
273
                    else:
 
274
                        entry = TreeEntry()
 
275
                
 
276
                yield fp, c, fk, (f_ie and f_ie.file_id), entry
 
277
 
 
278
                if fk != 'directory':
 
279
                    continue
 
280
 
 
281
                if c != 'V':
 
282
                    # don't descend unversioned directories
 
283
                    continue
 
284
                
 
285
                for ff in descend(fp, f_ie.file_id, fap):
 
286
                    yield ff
 
287
 
 
288
        for f in descend('', inv.root.file_id, self.basedir):
 
289
            yield f
 
290
            
 
291
 
 
292
 
 
293
    def unknowns(self):
 
294
        for subp in self.extras():
 
295
            if not self.is_ignored(subp):
 
296
                yield subp
 
297
 
 
298
    def iter_conflicts(self):
 
299
        conflicted = set()
 
300
        for path in (s[0] for s in self.list_files()):
 
301
            stem = get_conflicted_stem(path)
 
302
            if stem is None:
 
303
                continue
 
304
            if stem not in conflicted:
 
305
                conflicted.add(stem)
 
306
                yield stem
 
307
 
 
308
    @needs_write_lock
 
309
    def pull(self, source, remember=False):
 
310
        from bzrlib.merge import merge
 
311
        source.lock_read()
 
312
        try:
 
313
            old_revno = self.branch.revno()
 
314
            old_revision_history = self.branch.revision_history()
 
315
            try:
 
316
                self.branch.update_revisions(source)
 
317
            except DivergedBranches:
 
318
                if True:
 
319
                    raise
 
320
            new_revision_history = self.branch.revision_history()
 
321
            if new_revision_history != old_revision_history:
 
322
                merge((self.basedir, -1), (self.basedir, old_revno), check_clean=False)
 
323
            if self.branch.get_parent() is None or remember:
 
324
                self.branch.set_parent(source.base)
 
325
        finally:
 
326
            source.unlock()
 
327
 
 
328
    def extras(self):
 
329
        """Yield all unknown files in this WorkingTree.
 
330
 
 
331
        If there are any unknown directories then only the directory is
 
332
        returned, not all its children.  But if there are unknown files
 
333
        under a versioned subdirectory, they are returned.
 
334
 
 
335
        Currently returned depth-first, sorted by name within directories.
 
336
        """
 
337
        ## TODO: Work from given directory downwards
 
338
        for path, dir_entry in self.inventory.directories():
 
339
            mutter("search for unknowns in %r" % path)
 
340
            dirabs = self.abspath(path)
 
341
            if not isdir(dirabs):
 
342
                # e.g. directory deleted
 
343
                continue
 
344
 
 
345
            fl = []
 
346
            for subf in os.listdir(dirabs):
 
347
                if (subf != '.bzr'
 
348
                    and (subf not in dir_entry.children)):
 
349
                    fl.append(subf)
 
350
            
 
351
            fl.sort()
 
352
            for subf in fl:
 
353
                subp = appendpath(path, subf)
 
354
                yield subp
 
355
 
 
356
 
 
357
    def ignored_files(self):
 
358
        """Yield list of PATH, IGNORE_PATTERN"""
 
359
        for subp in self.extras():
 
360
            pat = self.is_ignored(subp)
 
361
            if pat != None:
 
362
                yield subp, pat
 
363
 
 
364
 
 
365
    def get_ignore_list(self):
 
366
        """Return list of ignore patterns.
 
367
 
 
368
        Cached in the Tree object after the first call.
 
369
        """
 
370
        if hasattr(self, '_ignorelist'):
 
371
            return self._ignorelist
 
372
 
 
373
        l = bzrlib.DEFAULT_IGNORE[:]
 
374
        if self.has_filename(bzrlib.IGNORE_FILENAME):
 
375
            f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
 
376
            l.extend([line.rstrip("\n\r") for line in f.readlines()])
 
377
        self._ignorelist = l
 
378
        return l
 
379
 
 
380
 
 
381
    def is_ignored(self, filename):
 
382
        r"""Check whether the filename matches an ignore pattern.
 
383
 
 
384
        Patterns containing '/' or '\' need to match the whole path;
 
385
        others match against only the last component.
 
386
 
 
387
        If the file is ignored, returns the pattern which caused it to
 
388
        be ignored, otherwise None.  So this can simply be used as a
 
389
        boolean if desired."""
 
390
 
 
391
        # TODO: Use '**' to match directories, and other extended
 
392
        # globbing stuff from cvs/rsync.
 
393
 
 
394
        # XXX: fnmatch is actually not quite what we want: it's only
 
395
        # approximately the same as real Unix fnmatch, and doesn't
 
396
        # treat dotfiles correctly and allows * to match /.
 
397
        # Eventually it should be replaced with something more
 
398
        # accurate.
 
399
        
 
400
        for pat in self.get_ignore_list():
 
401
            if '/' in pat or '\\' in pat:
 
402
                
 
403
                # as a special case, you can put ./ at the start of a
 
404
                # pattern; this is good to match in the top-level
 
405
                # only;
 
406
                
 
407
                if (pat[:2] == './') or (pat[:2] == '.\\'):
 
408
                    newpat = pat[2:]
 
409
                else:
 
410
                    newpat = pat
 
411
                if fnmatch.fnmatchcase(filename, newpat):
 
412
                    return pat
 
413
            else:
 
414
                if fnmatch.fnmatchcase(splitpath(filename)[-1], pat):
 
415
                    return pat
 
416
        else:
 
417
            return None
 
418
 
 
419
    def kind(self, file_id):
 
420
        return file_kind(self.id2abspath(file_id))
 
421
 
 
422
    def lock_read(self):
 
423
        """See Branch.lock_read, and WorkingTree.unlock."""
 
424
        return self.branch.lock_read()
 
425
 
 
426
    def lock_write(self):
 
427
        """See Branch.lock_write, and WorkingTree.unlock."""
 
428
        return self.branch.lock_write()
 
429
 
 
430
    @needs_write_lock
 
431
    def remove(self, files, verbose=False):
 
432
        """Remove nominated files from the working inventory..
 
433
 
 
434
        This does not remove their text.  This does not run on XXX on what? RBC
 
435
 
 
436
        TODO: Refuse to remove modified files unless --force is given?
 
437
 
 
438
        TODO: Do something useful with directories.
 
439
 
 
440
        TODO: Should this remove the text or not?  Tough call; not
 
441
        removing may be useful and the user can just use use rm, and
 
442
        is the opposite of add.  Removing it is consistent with most
 
443
        other tools.  Maybe an option.
 
444
        """
 
445
        ## TODO: Normalize names
 
446
        ## TODO: Remove nested loops; better scalability
 
447
        if isinstance(files, basestring):
 
448
            files = [files]
 
449
 
 
450
        inv = self.inventory
 
451
 
 
452
        # do this before any modifications
 
453
        for f in files:
 
454
            fid = inv.path2id(f)
 
455
            if not fid:
 
456
                raise BzrError("cannot remove unversioned file %s" % quotefn(f))
 
457
            mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
 
458
            if verbose:
 
459
                # having remove it, it must be either ignored or unknown
 
460
                if self.is_ignored(f):
 
461
                    new_status = 'I'
 
462
                else:
 
463
                    new_status = '?'
 
464
                show_status(new_status, inv[fid].kind, quotefn(f))
 
465
            del inv[fid]
 
466
 
 
467
        self.branch._write_inventory(inv)
 
468
 
 
469
    def unlock(self):
 
470
        """See Branch.unlock.
 
471
        
 
472
        WorkingTree locking just uses the Branch locking facilities.
 
473
        This is current because all working trees have an embedded branch
 
474
        within them. IF in the future, we were to make branch data shareable
 
475
        between multiple working trees, i.e. via shared storage, then we 
 
476
        would probably want to lock both the local tree, and the branch.
 
477
        """
 
478
        return self.branch.unlock()
 
479
 
 
480
 
 
481
CONFLICT_SUFFIXES = ('.THIS', '.BASE', '.OTHER')
 
482
def get_conflicted_stem(path):
 
483
    for suffix in CONFLICT_SUFFIXES:
 
484
        if path.endswith(suffix):
 
485
            return path[:-len(suffix)]