/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-11-05 22:18:12 UTC
  • mto: This revision was merged to the branch mainline in revision 1503.
  • Revision ID: robertc@robertcollins.net-20051105221812-a2a774e6f8d993be
Update comment to reflect author.

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,
 
52
                            file_kind,
 
53
                            isdir,
 
54
                            pumpfile,
 
55
                            splitpath,
 
56
                            relpath)
 
57
from bzrlib.errors import BzrCheckError, DivergedBranches, NotVersionedError
 
58
from bzrlib.trace import mutter
 
59
import bzrlib.xml5
 
60
 
 
61
 
 
62
class TreeEntry(object):
 
63
    """An entry that implements the minium interface used by commands.
 
64
 
 
65
    This needs further inspection, it may be better to have 
 
66
    InventoryEntries without ids - though that seems wrong. For now,
 
67
    this is a parallel hierarchy to InventoryEntry, and needs to become
 
68
    one of several things: decorates to that hierarchy, children of, or
 
69
    parents of it.
 
70
    Another note is that these objects are currently only used when there is
 
71
    no InventoryEntry available - i.e. for unversioned objects.
 
72
    Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
 
73
    """
 
74
 
 
75
    def __eq__(self, other):
 
76
        # yes, this us ugly, TODO: best practice __eq__ style.
 
77
        return (isinstance(other, TreeEntry)
 
78
                and other.__class__ == self.__class__)
 
79
 
 
80
    def kind_character(self):
 
81
        return "???"
 
82
 
 
83
 
 
84
class TreeDirectory(TreeEntry):
 
85
    """See TreeEntry. This is a directory in a working tree."""
 
86
 
 
87
    def __eq__(self, other):
 
88
        return (isinstance(other, TreeDirectory)
 
89
                and other.__class__ == self.__class__)
 
90
 
 
91
    def kind_character(self):
 
92
        return "/"
 
93
 
 
94
 
 
95
class TreeFile(TreeEntry):
 
96
    """See TreeEntry. This is a regular file in a working tree."""
 
97
 
 
98
    def __eq__(self, other):
 
99
        return (isinstance(other, TreeFile)
 
100
                and other.__class__ == self.__class__)
 
101
 
 
102
    def kind_character(self):
 
103
        return ''
 
104
 
 
105
 
 
106
class TreeLink(TreeEntry):
 
107
    """See TreeEntry. This is a symlink in a working tree."""
 
108
 
 
109
    def __eq__(self, other):
 
110
        return (isinstance(other, TreeLink)
 
111
                and other.__class__ == self.__class__)
 
112
 
 
113
    def kind_character(self):
 
114
        return ''
 
115
 
 
116
 
 
117
class WorkingTree(bzrlib.tree.Tree):
 
118
    """Working copy tree.
 
119
 
 
120
    The inventory is held in the `Branch` working-inventory, and the
 
121
    files are in a directory on disk.
 
122
 
 
123
    It is possible for a `WorkingTree` to have a filename which is
 
124
    not listed in the Inventory and vice versa.
 
125
    """
 
126
 
 
127
    def __init__(self, basedir, branch=None):
 
128
        """Construct a WorkingTree for basedir.
 
129
 
 
130
        If the branch is not supplied, it is opened automatically.
 
131
        If the branch is supplied, it must be the branch for this basedir.
 
132
        (branch.base is not cross checked, because for remote branches that
 
133
        would be meaningless).
 
134
        """
 
135
        from bzrlib.hashcache import HashCache
 
136
        from bzrlib.trace import note, mutter
 
137
        assert isinstance(basedir, basestring), \
 
138
            "base directory %r is not a string" % basedir
 
139
        if branch is None:
 
140
            branch = Branch.open(basedir)
 
141
        assert isinstance(branch, Branch), \
 
142
            "branch %r is not a Branch" % branch
 
143
        self.branch = branch
 
144
        self.basedir = basedir
 
145
        self._inventory = self.read_working_inventory()
 
146
        self.path2id = self._inventory.path2id
 
147
 
 
148
        # update the whole cache up front and write to disk if anything changed;
 
149
        # in the future we might want to do this more selectively
 
150
        # two possible ways offer themselves : in self._unlock, write the cache
 
151
        # if needed, or, when the cache sees a change, append it to the hash
 
152
        # cache file, and have the parser take the most recent entry for a
 
153
        # given path only.
 
154
        hc = self._hashcache = HashCache(basedir)
 
155
        hc.read()
 
156
        hc.scan()
 
157
 
 
158
        if hc.needs_write:
 
159
            mutter("write hc")
 
160
            hc.write()
 
161
 
 
162
    def __iter__(self):
 
163
        """Iterate through file_ids for this tree.
 
164
 
 
165
        file_ids are in a WorkingTree if they are in the working inventory
 
166
        and the working file exists.
 
167
        """
 
168
        inv = self._inventory
 
169
        for path, ie in inv.iter_entries():
 
170
            if bzrlib.osutils.lexists(self.abspath(path)):
 
171
                yield ie.file_id
 
172
 
 
173
 
 
174
    def __repr__(self):
 
175
        return "<%s of %s>" % (self.__class__.__name__,
 
176
                               getattr(self, 'basedir', None))
 
177
 
 
178
 
 
179
 
 
180
    def abspath(self, filename):
 
181
        return os.path.join(self.basedir, filename)
 
182
 
 
183
    def relpath(self, abspath):
 
184
        """Return the local path portion from a given absolute path."""
 
185
        return relpath(self.basedir, abspath)
 
186
 
 
187
    def has_filename(self, filename):
 
188
        return bzrlib.osutils.lexists(self.abspath(filename))
 
189
 
 
190
    def get_file(self, file_id):
 
191
        return self.get_file_byname(self.id2path(file_id))
 
192
 
 
193
    def get_file_byname(self, filename):
 
194
        return file(self.abspath(filename), 'rb')
 
195
 
 
196
    def get_root_id(self):
 
197
        """Return the id of this trees root"""
 
198
        inv = self.read_working_inventory()
 
199
        return inv.root.file_id
 
200
        
 
201
    def _get_store_filename(self, file_id):
 
202
        ## XXX: badly named; this isn't in the store at all
 
203
        return self.abspath(self.id2path(file_id))
 
204
 
 
205
 
 
206
    def id2abspath(self, file_id):
 
207
        return self.abspath(self.id2path(file_id))
 
208
 
 
209
                
 
210
    def has_id(self, file_id):
 
211
        # files that have been deleted are excluded
 
212
        inv = self._inventory
 
213
        if not inv.has_id(file_id):
 
214
            return False
 
215
        path = inv.id2path(file_id)
 
216
        return bzrlib.osutils.lexists(self.abspath(path))
 
217
 
 
218
    def has_or_had_id(self, file_id):
 
219
        if file_id == self.inventory.root.file_id:
 
220
            return True
 
221
        return self.inventory.has_id(file_id)
 
222
 
 
223
    __contains__ = has_id
 
224
    
 
225
 
 
226
    def get_file_size(self, file_id):
 
227
        return os.path.getsize(self.id2abspath(file_id))
 
228
 
 
229
    def get_file_sha1(self, file_id):
 
230
        path = self._inventory.id2path(file_id)
 
231
        return self._hashcache.get_sha1(path)
 
232
 
 
233
 
 
234
    def is_executable(self, file_id):
 
235
        if os.name == "nt":
 
236
            return self._inventory[file_id].executable
 
237
        else:
 
238
            path = self._inventory.id2path(file_id)
 
239
            mode = os.lstat(self.abspath(path)).st_mode
 
240
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC&mode)
 
241
 
 
242
    def get_symlink_target(self, file_id):
 
243
        return os.readlink(self.id2abspath(file_id))
 
244
 
 
245
    def file_class(self, filename):
 
246
        if self.path2id(filename):
 
247
            return 'V'
 
248
        elif self.is_ignored(filename):
 
249
            return 'I'
 
250
        else:
 
251
            return '?'
 
252
 
 
253
 
 
254
    def list_files(self):
 
255
        """Recursively list all files as (path, class, kind, id).
 
256
 
 
257
        Lists, but does not descend into unversioned directories.
 
258
 
 
259
        This does not include files that have been deleted in this
 
260
        tree.
 
261
 
 
262
        Skips the control directory.
 
263
        """
 
264
        inv = self._inventory
 
265
 
 
266
        def descend(from_dir_relpath, from_dir_id, dp):
 
267
            ls = os.listdir(dp)
 
268
            ls.sort()
 
269
            for f in ls:
 
270
                ## TODO: If we find a subdirectory with its own .bzr
 
271
                ## directory, then that is a separate tree and we
 
272
                ## should exclude it.
 
273
                if bzrlib.BZRDIR == f:
 
274
                    continue
 
275
 
 
276
                # path within tree
 
277
                fp = appendpath(from_dir_relpath, f)
 
278
 
 
279
                # absolute path
 
280
                fap = appendpath(dp, f)
 
281
                
 
282
                f_ie = inv.get_child(from_dir_id, f)
 
283
                if f_ie:
 
284
                    c = 'V'
 
285
                elif self.is_ignored(fp):
 
286
                    c = 'I'
 
287
                else:
 
288
                    c = '?'
 
289
 
 
290
                fk = file_kind(fap)
 
291
 
 
292
                if f_ie:
 
293
                    if f_ie.kind != fk:
 
294
                        raise BzrCheckError("file %r entered as kind %r id %r, "
 
295
                                            "now of kind %r"
 
296
                                            % (fap, f_ie.kind, f_ie.file_id, fk))
 
297
 
 
298
                # make a last minute entry
 
299
                if f_ie:
 
300
                    entry = f_ie
 
301
                else:
 
302
                    if fk == 'directory':
 
303
                        entry = TreeDirectory()
 
304
                    elif fk == 'file':
 
305
                        entry = TreeFile()
 
306
                    elif fk == 'symlink':
 
307
                        entry = TreeLink()
 
308
                    else:
 
309
                        entry = TreeEntry()
 
310
                
 
311
                yield fp, c, fk, (f_ie and f_ie.file_id), entry
 
312
 
 
313
                if fk != 'directory':
 
314
                    continue
 
315
 
 
316
                if c != 'V':
 
317
                    # don't descend unversioned directories
 
318
                    continue
 
319
                
 
320
                for ff in descend(fp, f_ie.file_id, fap):
 
321
                    yield ff
 
322
 
 
323
        for f in descend('', inv.root.file_id, self.basedir):
 
324
            yield f
 
325
            
 
326
 
 
327
 
 
328
    def unknowns(self):
 
329
        for subp in self.extras():
 
330
            if not self.is_ignored(subp):
 
331
                yield subp
 
332
 
 
333
    def iter_conflicts(self):
 
334
        conflicted = set()
 
335
        for path in (s[0] for s in self.list_files()):
 
336
            stem = get_conflicted_stem(path)
 
337
            if stem is None:
 
338
                continue
 
339
            if stem not in conflicted:
 
340
                conflicted.add(stem)
 
341
                yield stem
 
342
 
 
343
    @needs_write_lock
 
344
    def pull(self, source, overwrite=False):
 
345
        from bzrlib.merge import merge_inner
 
346
        source.lock_read()
 
347
        try:
 
348
            old_revision_history = self.branch.revision_history()
 
349
            self.branch.pull(source, overwrite)
 
350
            new_revision_history = self.branch.revision_history()
 
351
            if new_revision_history != old_revision_history:
 
352
                if len(old_revision_history):
 
353
                    other_revision = old_revision_history[-1]
 
354
                else:
 
355
                    other_revision = None
 
356
                merge_inner(self.branch,
 
357
                            self.branch.basis_tree(), 
 
358
                            self.branch.revision_tree(other_revision))
 
359
        finally:
 
360
            source.unlock()
 
361
 
 
362
    def extras(self):
 
363
        """Yield all unknown files in this WorkingTree.
 
364
 
 
365
        If there are any unknown directories then only the directory is
 
366
        returned, not all its children.  But if there are unknown files
 
367
        under a versioned subdirectory, they are returned.
 
368
 
 
369
        Currently returned depth-first, sorted by name within directories.
 
370
        """
 
371
        ## TODO: Work from given directory downwards
 
372
        for path, dir_entry in self.inventory.directories():
 
373
            mutter("search for unknowns in %r" % path)
 
374
            dirabs = self.abspath(path)
 
375
            if not isdir(dirabs):
 
376
                # e.g. directory deleted
 
377
                continue
 
378
 
 
379
            fl = []
 
380
            for subf in os.listdir(dirabs):
 
381
                if (subf != '.bzr'
 
382
                    and (subf not in dir_entry.children)):
 
383
                    fl.append(subf)
 
384
            
 
385
            fl.sort()
 
386
            for subf in fl:
 
387
                subp = appendpath(path, subf)
 
388
                yield subp
 
389
 
 
390
 
 
391
    def ignored_files(self):
 
392
        """Yield list of PATH, IGNORE_PATTERN"""
 
393
        for subp in self.extras():
 
394
            pat = self.is_ignored(subp)
 
395
            if pat != None:
 
396
                yield subp, pat
 
397
 
 
398
 
 
399
    def get_ignore_list(self):
 
400
        """Return list of ignore patterns.
 
401
 
 
402
        Cached in the Tree object after the first call.
 
403
        """
 
404
        if hasattr(self, '_ignorelist'):
 
405
            return self._ignorelist
 
406
 
 
407
        l = bzrlib.DEFAULT_IGNORE[:]
 
408
        if self.has_filename(bzrlib.IGNORE_FILENAME):
 
409
            f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
 
410
            l.extend([line.rstrip("\n\r") for line in f.readlines()])
 
411
        self._ignorelist = l
 
412
        return l
 
413
 
 
414
 
 
415
    def is_ignored(self, filename):
 
416
        r"""Check whether the filename matches an ignore pattern.
 
417
 
 
418
        Patterns containing '/' or '\' need to match the whole path;
 
419
        others match against only the last component.
 
420
 
 
421
        If the file is ignored, returns the pattern which caused it to
 
422
        be ignored, otherwise None.  So this can simply be used as a
 
423
        boolean if desired."""
 
424
 
 
425
        # TODO: Use '**' to match directories, and other extended
 
426
        # globbing stuff from cvs/rsync.
 
427
 
 
428
        # XXX: fnmatch is actually not quite what we want: it's only
 
429
        # approximately the same as real Unix fnmatch, and doesn't
 
430
        # treat dotfiles correctly and allows * to match /.
 
431
        # Eventually it should be replaced with something more
 
432
        # accurate.
 
433
        
 
434
        for pat in self.get_ignore_list():
 
435
            if '/' in pat or '\\' in pat:
 
436
                
 
437
                # as a special case, you can put ./ at the start of a
 
438
                # pattern; this is good to match in the top-level
 
439
                # only;
 
440
                
 
441
                if (pat[:2] == './') or (pat[:2] == '.\\'):
 
442
                    newpat = pat[2:]
 
443
                else:
 
444
                    newpat = pat
 
445
                if fnmatch.fnmatchcase(filename, newpat):
 
446
                    return pat
 
447
            else:
 
448
                if fnmatch.fnmatchcase(splitpath(filename)[-1], pat):
 
449
                    return pat
 
450
        else:
 
451
            return None
 
452
 
 
453
    def kind(self, file_id):
 
454
        return file_kind(self.id2abspath(file_id))
 
455
 
 
456
    def lock_read(self):
 
457
        """See Branch.lock_read, and WorkingTree.unlock."""
 
458
        return self.branch.lock_read()
 
459
 
 
460
    def lock_write(self):
 
461
        """See Branch.lock_write, and WorkingTree.unlock."""
 
462
        return self.branch.lock_write()
 
463
 
 
464
    @needs_read_lock
 
465
    def read_working_inventory(self):
 
466
        """Read the working inventory."""
 
467
        # ElementTree does its own conversion from UTF-8, so open in
 
468
        # binary.
 
469
        f = self.branch.controlfile('inventory', 'rb')
 
470
        return bzrlib.xml5.serializer_v5.read_inventory(f)
 
471
 
 
472
    @needs_write_lock
 
473
    def remove(self, files, verbose=False):
 
474
        """Remove nominated files from the working inventory..
 
475
 
 
476
        This does not remove their text.  This does not run on XXX on what? RBC
 
477
 
 
478
        TODO: Refuse to remove modified files unless --force is given?
 
479
 
 
480
        TODO: Do something useful with directories.
 
481
 
 
482
        TODO: Should this remove the text or not?  Tough call; not
 
483
        removing may be useful and the user can just use use rm, and
 
484
        is the opposite of add.  Removing it is consistent with most
 
485
        other tools.  Maybe an option.
 
486
        """
 
487
        ## TODO: Normalize names
 
488
        ## TODO: Remove nested loops; better scalability
 
489
        if isinstance(files, basestring):
 
490
            files = [files]
 
491
 
 
492
        inv = self.inventory
 
493
 
 
494
        # do this before any modifications
 
495
        for f in files:
 
496
            fid = inv.path2id(f)
 
497
            if not fid:
 
498
                # TODO: Perhaps make this just a warning, and continue?
 
499
                # This tends to happen when 
 
500
                raise NotVersionedError(path=f)
 
501
            mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
 
502
            if verbose:
 
503
                # having remove it, it must be either ignored or unknown
 
504
                if self.is_ignored(f):
 
505
                    new_status = 'I'
 
506
                else:
 
507
                    new_status = '?'
 
508
                show_status(new_status, inv[fid].kind, quotefn(f))
 
509
            del inv[fid]
 
510
 
 
511
        self._write_inventory(inv)
 
512
 
 
513
    @needs_write_lock
 
514
    def revert(self, filenames, old_tree=None, backups=True):
 
515
        from bzrlib.merge import merge_inner
 
516
        if old_tree is None:
 
517
            old_tree = self.branch.basis_tree()
 
518
        merge_inner(self.branch, old_tree,
 
519
                    self, ignore_zero=True,
 
520
                    backup_files=backups, 
 
521
                    interesting_files=filenames)
 
522
        if not len(filenames):
 
523
            self.branch.set_pending_merges([])
 
524
 
 
525
    @needs_write_lock
 
526
    def set_inventory(self, new_inventory_list):
 
527
        from bzrlib.inventory import (Inventory,
 
528
                                      InventoryDirectory,
 
529
                                      InventoryEntry,
 
530
                                      InventoryFile,
 
531
                                      InventoryLink)
 
532
        inv = Inventory(self.get_root_id())
 
533
        for path, file_id, parent, kind in new_inventory_list:
 
534
            name = os.path.basename(path)
 
535
            if name == "":
 
536
                continue
 
537
            # fixme, there should be a factory function inv,add_?? 
 
538
            if kind == 'directory':
 
539
                inv.add(InventoryDirectory(file_id, name, parent))
 
540
            elif kind == 'file':
 
541
                inv.add(InventoryFile(file_id, name, parent))
 
542
            elif kind == 'symlink':
 
543
                inv.add(InventoryLink(file_id, name, parent))
 
544
            else:
 
545
                raise BzrError("unknown kind %r" % kind)
 
546
        self._write_inventory(inv)
 
547
 
 
548
    @needs_write_lock
 
549
    def set_root_id(self, file_id):
 
550
        """Set the root id for this tree."""
 
551
        inv = self.read_working_inventory()
 
552
        orig_root_id = inv.root.file_id
 
553
        del inv._byid[inv.root.file_id]
 
554
        inv.root.file_id = file_id
 
555
        inv._byid[inv.root.file_id] = inv.root
 
556
        for fid in inv:
 
557
            entry = inv[fid]
 
558
            if entry.parent_id in (None, orig_root_id):
 
559
                entry.parent_id = inv.root.file_id
 
560
        self._write_inventory(inv)
 
561
 
 
562
    def unlock(self):
 
563
        """See Branch.unlock.
 
564
        
 
565
        WorkingTree locking just uses the Branch locking facilities.
 
566
        This is current because all working trees have an embedded branch
 
567
        within them. IF in the future, we were to make branch data shareable
 
568
        between multiple working trees, i.e. via shared storage, then we 
 
569
        would probably want to lock both the local tree, and the branch.
 
570
        """
 
571
        return self.branch.unlock()
 
572
 
 
573
    @needs_write_lock
 
574
    def _write_inventory(self, inv):
 
575
        """Write inventory as the current inventory."""
 
576
        from cStringIO import StringIO
 
577
        from bzrlib.atomicfile import AtomicFile
 
578
        sio = StringIO()
 
579
        bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
 
580
        sio.seek(0)
 
581
        f = AtomicFile(self.branch.controlfilename('inventory'))
 
582
        try:
 
583
            pumpfile(sio, f)
 
584
            f.commit()
 
585
        finally:
 
586
            f.close()
 
587
        mutter('wrote working inventory')
 
588
            
 
589
 
 
590
CONFLICT_SUFFIXES = ('.THIS', '.BASE', '.OTHER')
 
591
def get_conflicted_stem(path):
 
592
    for suffix in CONFLICT_SUFFIXES:
 
593
        if path.endswith(suffix):
 
594
            return path[:-len(suffix)]