/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 23:47:12 UTC
  • mfrom: (0.2.1)
  • Revision ID: robertc@robertcollins.net-20051018234712-45a83974f691c860
Bugfix the new pull --clobber to not generate spurious conflicts.

When --clobber clobbered the history, a bad merge base was used.

Supporting this:
* merge.merge_inner now has tempdir as an optional parameter. (Robert Collins)

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