/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: Michael Ellerman
  • Date: 2006-03-09 00:24:48 UTC
  • mto: (1610.1.8 bzr.mbp.integration)
  • mto: This revision was merged to the branch mainline in revision 1616.
  • Revision ID: michael@ellerman.id.au-20060309002448-70cce15e3d605130
Make the "ignore line" in the commit message editor the "right" width, so
that if you make your message that wide it won't wrap in bzr log output.
Just as a visual aid.

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 bzrdir.open_workingtree() or
 
29
WorkingTree.open(dir).
 
30
"""
 
31
 
 
32
 
 
33
# FIXME: I don't know if writing out the cache from the destructor is really a
 
34
# good idea, because destructors are considered poor taste in Python, and it's
 
35
# not predictable when it will be written out.
 
36
 
 
37
# TODO: Give the workingtree sole responsibility for the working inventory;
 
38
# remove the variable and references to it from the branch.  This may require
 
39
# updating the commit code so as to update the inventory within the working
 
40
# copy, and making sure there's only one WorkingTree for any directory on disk.
 
41
# At the momenthey may alias the inventory and have old copies of it in memory.
 
42
 
 
43
from copy import deepcopy
 
44
from cStringIO import StringIO
 
45
import errno
 
46
import fnmatch
 
47
import os
 
48
import stat
 
49
 
 
50
 
 
51
from bzrlib.atomicfile import AtomicFile
 
52
from bzrlib.branch import (Branch,
 
53
                           quotefn)
 
54
import bzrlib.bzrdir as bzrdir
 
55
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
56
import bzrlib.errors as errors
 
57
from bzrlib.errors import (BzrCheckError,
 
58
                           BzrError,
 
59
                           DivergedBranches,
 
60
                           WeaveRevisionNotPresent,
 
61
                           NotBranchError,
 
62
                           NoSuchFile,
 
63
                           NotVersionedError)
 
64
from bzrlib.inventory import InventoryEntry, Inventory
 
65
from bzrlib.lockable_files import LockableFiles, TransportLock
 
66
from bzrlib.merge import merge_inner, transform_tree
 
67
from bzrlib.osutils import (
 
68
                            abspath,
 
69
                            appendpath,
 
70
                            compact_date,
 
71
                            file_kind,
 
72
                            isdir,
 
73
                            getcwd,
 
74
                            pathjoin,
 
75
                            pumpfile,
 
76
                            safe_unicode,
 
77
                            splitpath,
 
78
                            rand_bytes,
 
79
                            normpath,
 
80
                            realpath,
 
81
                            relpath,
 
82
                            rename,
 
83
                            supports_executable,
 
84
                            )
 
85
from bzrlib.progress import DummyProgress
 
86
from bzrlib.revision import NULL_REVISION
 
87
from bzrlib.symbol_versioning import *
 
88
from bzrlib.textui import show_status
 
89
import bzrlib.tree
 
90
from bzrlib.trace import mutter
 
91
from bzrlib.transform import build_tree
 
92
from bzrlib.transport import get_transport
 
93
from bzrlib.transport.local import LocalTransport
 
94
import bzrlib.ui
 
95
import bzrlib.xml5
 
96
 
 
97
 
 
98
def gen_file_id(name):
 
99
    """Return new file id.
 
100
 
 
101
    This should probably generate proper UUIDs, but for the moment we
 
102
    cope with just randomness because running uuidgen every time is
 
103
    slow."""
 
104
    import re
 
105
    from binascii import hexlify
 
106
    from time import time
 
107
 
 
108
    # get last component
 
109
    idx = name.rfind('/')
 
110
    if idx != -1:
 
111
        name = name[idx+1 : ]
 
112
    idx = name.rfind('\\')
 
113
    if idx != -1:
 
114
        name = name[idx+1 : ]
 
115
 
 
116
    # make it not a hidden file
 
117
    name = name.lstrip('.')
 
118
 
 
119
    # remove any wierd characters; we don't escape them but rather
 
120
    # just pull them out
 
121
    name = re.sub(r'[^\w.]', '', name)
 
122
 
 
123
    s = hexlify(rand_bytes(8))
 
124
    return '-'.join((name, compact_date(time()), s))
 
125
 
 
126
 
 
127
def gen_root_id():
 
128
    """Return a new tree-root file id."""
 
129
    return gen_file_id('TREE_ROOT')
 
130
 
 
131
 
 
132
class TreeEntry(object):
 
133
    """An entry that implements the minium interface used by commands.
 
134
 
 
135
    This needs further inspection, it may be better to have 
 
136
    InventoryEntries without ids - though that seems wrong. For now,
 
137
    this is a parallel hierarchy to InventoryEntry, and needs to become
 
138
    one of several things: decorates to that hierarchy, children of, or
 
139
    parents of it.
 
140
    Another note is that these objects are currently only used when there is
 
141
    no InventoryEntry available - i.e. for unversioned objects.
 
142
    Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
 
143
    """
 
144
 
 
145
    def __eq__(self, other):
 
146
        # yes, this us ugly, TODO: best practice __eq__ style.
 
147
        return (isinstance(other, TreeEntry)
 
148
                and other.__class__ == self.__class__)
 
149
 
 
150
    def kind_character(self):
 
151
        return "???"
 
152
 
 
153
 
 
154
class TreeDirectory(TreeEntry):
 
155
    """See TreeEntry. This is a directory in a working tree."""
 
156
 
 
157
    def __eq__(self, other):
 
158
        return (isinstance(other, TreeDirectory)
 
159
                and other.__class__ == self.__class__)
 
160
 
 
161
    def kind_character(self):
 
162
        return "/"
 
163
 
 
164
 
 
165
class TreeFile(TreeEntry):
 
166
    """See TreeEntry. This is a regular file in a working tree."""
 
167
 
 
168
    def __eq__(self, other):
 
169
        return (isinstance(other, TreeFile)
 
170
                and other.__class__ == self.__class__)
 
171
 
 
172
    def kind_character(self):
 
173
        return ''
 
174
 
 
175
 
 
176
class TreeLink(TreeEntry):
 
177
    """See TreeEntry. This is a symlink in a working tree."""
 
178
 
 
179
    def __eq__(self, other):
 
180
        return (isinstance(other, TreeLink)
 
181
                and other.__class__ == self.__class__)
 
182
 
 
183
    def kind_character(self):
 
184
        return ''
 
185
 
 
186
 
 
187
class WorkingTree(bzrlib.tree.Tree):
 
188
    """Working copy tree.
 
189
 
 
190
    The inventory is held in the `Branch` working-inventory, and the
 
191
    files are in a directory on disk.
 
192
 
 
193
    It is possible for a `WorkingTree` to have a filename which is
 
194
    not listed in the Inventory and vice versa.
 
195
    """
 
196
 
 
197
    def __init__(self, basedir='.',
 
198
                 branch=DEPRECATED_PARAMETER,
 
199
                 _inventory=None,
 
200
                 _control_files=None,
 
201
                 _internal=False,
 
202
                 _format=None,
 
203
                 _bzrdir=None):
 
204
        """Construct a WorkingTree for basedir.
 
205
 
 
206
        If the branch is not supplied, it is opened automatically.
 
207
        If the branch is supplied, it must be the branch for this basedir.
 
208
        (branch.base is not cross checked, because for remote branches that
 
209
        would be meaningless).
 
210
        """
 
211
        self._format = _format
 
212
        self.bzrdir = _bzrdir
 
213
        if not _internal:
 
214
            # not created via open etc.
 
215
            warn("WorkingTree() is deprecated as of bzr version 0.8. "
 
216
                 "Please use bzrdir.open_workingtree or WorkingTree.open().",
 
217
                 DeprecationWarning,
 
218
                 stacklevel=2)
 
219
            wt = WorkingTree.open(basedir)
 
220
            self.branch = wt.branch
 
221
            self.basedir = wt.basedir
 
222
            self._control_files = wt._control_files
 
223
            self._hashcache = wt._hashcache
 
224
            self._set_inventory(wt._inventory)
 
225
            self._format = wt._format
 
226
            self.bzrdir = wt.bzrdir
 
227
        from bzrlib.hashcache import HashCache
 
228
        from bzrlib.trace import note, mutter
 
229
        assert isinstance(basedir, basestring), \
 
230
            "base directory %r is not a string" % basedir
 
231
        basedir = safe_unicode(basedir)
 
232
        mutter("opening working tree %r", basedir)
 
233
        if deprecated_passed(branch):
 
234
            if not _internal:
 
235
                warn("WorkingTree(..., branch=XXX) is deprecated as of bzr 0.8."
 
236
                     " Please use bzrdir.open_workingtree() or WorkingTree.open().",
 
237
                     DeprecationWarning,
 
238
                     stacklevel=2
 
239
                     )
 
240
            self.branch = branch
 
241
        else:
 
242
            self.branch = self.bzrdir.open_branch()
 
243
        assert isinstance(self.branch, Branch), \
 
244
            "branch %r is not a Branch" % self.branch
 
245
        self.basedir = realpath(basedir)
 
246
        # if branch is at our basedir and is a format 6 or less
 
247
        if isinstance(self._format, WorkingTreeFormat2):
 
248
            # share control object
 
249
            self._control_files = self.branch.control_files
 
250
        elif _control_files is not None:
 
251
            assert False, "not done yet"
 
252
#            self._control_files = _control_files
 
253
        else:
 
254
            # only ready for format 3
 
255
            assert isinstance(self._format, WorkingTreeFormat3)
 
256
            self._control_files = LockableFiles(
 
257
                self.bzrdir.get_workingtree_transport(None),
 
258
                'lock', TransportLock)
 
259
 
 
260
        # update the whole cache up front and write to disk if anything changed;
 
261
        # in the future we might want to do this more selectively
 
262
        # two possible ways offer themselves : in self._unlock, write the cache
 
263
        # if needed, or, when the cache sees a change, append it to the hash
 
264
        # cache file, and have the parser take the most recent entry for a
 
265
        # given path only.
 
266
        cache_filename = self.bzrdir.get_workingtree_transport(None).abspath('stat-cache')
 
267
        hc = self._hashcache = HashCache(basedir, cache_filename, self._control_files._file_mode)
 
268
        hc.read()
 
269
        # is this scan needed ? it makes things kinda slow.
 
270
        hc.scan()
 
271
 
 
272
        if hc.needs_write:
 
273
            mutter("write hc")
 
274
            hc.write()
 
275
 
 
276
        if _inventory is None:
 
277
            self._set_inventory(self.read_working_inventory())
 
278
        else:
 
279
            self._set_inventory(_inventory)
 
280
 
 
281
    def _set_inventory(self, inv):
 
282
        self._inventory = inv
 
283
        self.path2id = self._inventory.path2id
 
284
 
 
285
    def is_control_filename(self, filename):
 
286
        """True if filename is the name of a control file in this tree.
 
287
        
 
288
        This is true IF and ONLY IF the filename is part of the meta data
 
289
        that bzr controls in this tree. I.E. a random .bzr directory placed
 
290
        on disk will not be a control file for this tree.
 
291
        """
 
292
        try:
 
293
            self.bzrdir.transport.relpath(self.abspath(filename))
 
294
            return True
 
295
        except errors.PathNotChild:
 
296
            return False
 
297
 
 
298
    @staticmethod
 
299
    def open(path=None, _unsupported=False):
 
300
        """Open an existing working tree at path.
 
301
 
 
302
        """
 
303
        if path is None:
 
304
            path = os.path.getcwdu()
 
305
        control = bzrdir.BzrDir.open(path, _unsupported)
 
306
        return control.open_workingtree(_unsupported)
 
307
        
 
308
    @staticmethod
 
309
    def open_containing(path=None):
 
310
        """Open an existing working tree which has its root about path.
 
311
        
 
312
        This probes for a working tree at path and searches upwards from there.
 
313
 
 
314
        Basically we keep looking up until we find the control directory or
 
315
        run into /.  If there isn't one, raises NotBranchError.
 
316
        TODO: give this a new exception.
 
317
        If there is one, it is returned, along with the unused portion of path.
 
318
        """
 
319
        if path is None:
 
320
            path = os.getcwdu()
 
321
        control, relpath = bzrdir.BzrDir.open_containing(path)
 
322
        return control.open_workingtree(), relpath
 
323
 
 
324
    @staticmethod
 
325
    def open_downlevel(path=None):
 
326
        """Open an unsupported working tree.
 
327
 
 
328
        Only intended for advanced situations like upgrading part of a bzrdir.
 
329
        """
 
330
        return WorkingTree.open(path, _unsupported=True)
 
331
 
 
332
    def __iter__(self):
 
333
        """Iterate through file_ids for this tree.
 
334
 
 
335
        file_ids are in a WorkingTree if they are in the working inventory
 
336
        and the working file exists.
 
337
        """
 
338
        inv = self._inventory
 
339
        for path, ie in inv.iter_entries():
 
340
            if bzrlib.osutils.lexists(self.abspath(path)):
 
341
                yield ie.file_id
 
342
 
 
343
    def __repr__(self):
 
344
        return "<%s of %s>" % (self.__class__.__name__,
 
345
                               getattr(self, 'basedir', None))
 
346
 
 
347
    def abspath(self, filename):
 
348
        return pathjoin(self.basedir, filename)
 
349
    
 
350
    def basis_tree(self):
 
351
        """Return RevisionTree for the current last revision."""
 
352
        revision_id = self.last_revision()
 
353
        if revision_id is not None:
 
354
            try:
 
355
                xml = self.read_basis_inventory(revision_id)
 
356
                inv = bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
 
357
                return bzrlib.tree.RevisionTree(self.branch.repository, inv,
 
358
                                                revision_id)
 
359
            except NoSuchFile:
 
360
                pass
 
361
        return self.branch.repository.revision_tree(revision_id)
 
362
 
 
363
    @staticmethod
 
364
    @deprecated_method(zero_eight)
 
365
    def create(branch, directory):
 
366
        """Create a workingtree for branch at directory.
 
367
 
 
368
        If existing_directory already exists it must have a .bzr directory.
 
369
        If it does not exist, it will be created.
 
370
 
 
371
        This returns a new WorkingTree object for the new checkout.
 
372
 
 
373
        TODO FIXME RBC 20060124 when we have checkout formats in place this
 
374
        should accept an optional revisionid to checkout [and reject this if
 
375
        checking out into the same dir as a pre-checkout-aware branch format.]
 
376
 
 
377
        XXX: When BzrDir is present, these should be created through that 
 
378
        interface instead.
 
379
        """
 
380
        warn('delete WorkingTree.create', stacklevel=3)
 
381
        transport = get_transport(directory)
 
382
        if branch.bzrdir.root_transport.base == transport.base:
 
383
            # same dir 
 
384
            return branch.bzrdir.create_workingtree()
 
385
        # different directory, 
 
386
        # create a branch reference
 
387
        # and now a working tree.
 
388
        raise NotImplementedError
 
389
 
 
390
    @staticmethod
 
391
    @deprecated_method(zero_eight)
 
392
    def create_standalone(directory):
 
393
        """Create a checkout and a branch and a repo at directory.
 
394
 
 
395
        Directory must exist and be empty.
 
396
 
 
397
        please use BzrDir.create_standalone_workingtree
 
398
        """
 
399
        return bzrdir.BzrDir.create_standalone_workingtree(directory)
 
400
 
 
401
    def relpath(self, abs):
 
402
        """Return the local path portion from a given absolute path."""
 
403
        return relpath(self.basedir, abs)
 
404
 
 
405
    def has_filename(self, filename):
 
406
        return bzrlib.osutils.lexists(self.abspath(filename))
 
407
 
 
408
    def get_file(self, file_id):
 
409
        return self.get_file_byname(self.id2path(file_id))
 
410
 
 
411
    def get_file_byname(self, filename):
 
412
        return file(self.abspath(filename), 'rb')
 
413
 
 
414
    def get_root_id(self):
 
415
        """Return the id of this trees root"""
 
416
        inv = self.read_working_inventory()
 
417
        return inv.root.file_id
 
418
        
 
419
    def _get_store_filename(self, file_id):
 
420
        ## XXX: badly named; this is not in the store at all
 
421
        return self.abspath(self.id2path(file_id))
 
422
 
 
423
    @needs_read_lock
 
424
    def clone(self, to_bzrdir, revision_id=None, basis=None):
 
425
        """Duplicate this working tree into to_bzr, including all state.
 
426
        
 
427
        Specifically modified files are kept as modified, but
 
428
        ignored and unknown files are discarded.
 
429
 
 
430
        If you want to make a new line of development, see bzrdir.sprout()
 
431
 
 
432
        revision
 
433
            If not None, the cloned tree will have its last revision set to 
 
434
            revision, and and difference between the source trees last revision
 
435
            and this one merged in.
 
436
 
 
437
        basis
 
438
            If not None, a closer copy of a tree which may have some files in
 
439
            common, and which file content should be preferentially copied from.
 
440
        """
 
441
        # assumes the target bzr dir format is compatible.
 
442
        result = self._format.initialize(to_bzrdir)
 
443
        self.copy_content_into(result, revision_id)
 
444
        return result
 
445
 
 
446
    @needs_read_lock
 
447
    def copy_content_into(self, tree, revision_id=None):
 
448
        """Copy the current content and user files of this tree into tree."""
 
449
        if revision_id is None:
 
450
            transform_tree(tree, self)
 
451
        else:
 
452
            # TODO now merge from tree.last_revision to revision
 
453
            transform_tree(tree, self)
 
454
            tree.set_last_revision(revision_id)
 
455
 
 
456
    @needs_write_lock
 
457
    def commit(self, message=None, revprops=None, *args, **kwargs):
 
458
        # avoid circular imports
 
459
        from bzrlib.commit import Commit
 
460
        if revprops is None:
 
461
            revprops = {}
 
462
        if not 'branch-nick' in revprops:
 
463
            revprops['branch-nick'] = self.branch.nick
 
464
        # args for wt.commit start at message from the Commit.commit method,
 
465
        # but with branch a kwarg now, passing in args as is results in the
 
466
        #message being used for the branch
 
467
        args = (DEPRECATED_PARAMETER, message, ) + args
 
468
        Commit().commit(working_tree=self, revprops=revprops, *args, **kwargs)
 
469
        self._set_inventory(self.read_working_inventory())
 
470
 
 
471
    def id2abspath(self, file_id):
 
472
        return self.abspath(self.id2path(file_id))
 
473
 
 
474
    def has_id(self, file_id):
 
475
        # files that have been deleted are excluded
 
476
        inv = self._inventory
 
477
        if not inv.has_id(file_id):
 
478
            return False
 
479
        path = inv.id2path(file_id)
 
480
        return bzrlib.osutils.lexists(self.abspath(path))
 
481
 
 
482
    def has_or_had_id(self, file_id):
 
483
        if file_id == self.inventory.root.file_id:
 
484
            return True
 
485
        return self.inventory.has_id(file_id)
 
486
 
 
487
    __contains__ = has_id
 
488
 
 
489
    def get_file_size(self, file_id):
 
490
        return os.path.getsize(self.id2abspath(file_id))
 
491
 
 
492
    @needs_read_lock
 
493
    def get_file_sha1(self, file_id):
 
494
        path = self._inventory.id2path(file_id)
 
495
        return self._hashcache.get_sha1(path)
 
496
 
 
497
    def is_executable(self, file_id):
 
498
        if not supports_executable():
 
499
            return self._inventory[file_id].executable
 
500
        else:
 
501
            path = self._inventory.id2path(file_id)
 
502
            mode = os.lstat(self.abspath(path)).st_mode
 
503
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC&mode)
 
504
 
 
505
    @needs_write_lock
 
506
    def add(self, files, ids=None):
 
507
        """Make files versioned.
 
508
 
 
509
        Note that the command line normally calls smart_add instead,
 
510
        which can automatically recurse.
 
511
 
 
512
        This adds the files to the inventory, so that they will be
 
513
        recorded by the next commit.
 
514
 
 
515
        files
 
516
            List of paths to add, relative to the base of the tree.
 
517
 
 
518
        ids
 
519
            If set, use these instead of automatically generated ids.
 
520
            Must be the same length as the list of files, but may
 
521
            contain None for ids that are to be autogenerated.
 
522
 
 
523
        TODO: Perhaps have an option to add the ids even if the files do
 
524
              not (yet) exist.
 
525
 
 
526
        TODO: Perhaps callback with the ids and paths as they're added.
 
527
        """
 
528
        # TODO: Re-adding a file that is removed in the working copy
 
529
        # should probably put it back with the previous ID.
 
530
        if isinstance(files, basestring):
 
531
            assert(ids is None or isinstance(ids, basestring))
 
532
            files = [files]
 
533
            if ids is not None:
 
534
                ids = [ids]
 
535
 
 
536
        if ids is None:
 
537
            ids = [None] * len(files)
 
538
        else:
 
539
            assert(len(ids) == len(files))
 
540
 
 
541
        inv = self.read_working_inventory()
 
542
        for f,file_id in zip(files, ids):
 
543
            if self.is_control_filename(f):
 
544
                raise BzrError("cannot add control file %s" % quotefn(f))
 
545
 
 
546
            fp = splitpath(f)
 
547
 
 
548
            if len(fp) == 0:
 
549
                raise BzrError("cannot add top-level %r" % f)
 
550
 
 
551
            fullpath = normpath(self.abspath(f))
 
552
 
 
553
            try:
 
554
                kind = file_kind(fullpath)
 
555
            except OSError, e:
 
556
                if e.errno == errno.ENOENT:
 
557
                    raise NoSuchFile(fullpath)
 
558
                # maybe something better?
 
559
                raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
 
560
 
 
561
            if not InventoryEntry.versionable_kind(kind):
 
562
                raise BzrError('cannot add: not a versionable file ('
 
563
                               'i.e. regular file, symlink or directory): %s' % quotefn(f))
 
564
 
 
565
            if file_id is None:
 
566
                file_id = gen_file_id(f)
 
567
            inv.add_path(f, kind=kind, file_id=file_id)
 
568
 
 
569
            mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
 
570
        self._write_inventory(inv)
 
571
 
 
572
    @needs_write_lock
 
573
    def add_pending_merge(self, *revision_ids):
 
574
        # TODO: Perhaps should check at this point that the
 
575
        # history of the revision is actually present?
 
576
        p = self.pending_merges()
 
577
        updated = False
 
578
        for rev_id in revision_ids:
 
579
            if rev_id in p:
 
580
                continue
 
581
            p.append(rev_id)
 
582
            updated = True
 
583
        if updated:
 
584
            self.set_pending_merges(p)
 
585
 
 
586
    @needs_read_lock
 
587
    def pending_merges(self):
 
588
        """Return a list of pending merges.
 
589
 
 
590
        These are revisions that have been merged into the working
 
591
        directory but not yet committed.
 
592
        """
 
593
        try:
 
594
            merges_file = self._control_files.get_utf8('pending-merges')
 
595
        except OSError, e:
 
596
            if e.errno != errno.ENOENT:
 
597
                raise
 
598
            return []
 
599
        p = []
 
600
        for l in merges_file.readlines():
 
601
            p.append(l.rstrip('\n'))
 
602
        return p
 
603
 
 
604
    @needs_write_lock
 
605
    def set_pending_merges(self, rev_list):
 
606
        self._control_files.put_utf8('pending-merges', '\n'.join(rev_list))
 
607
 
 
608
    def get_symlink_target(self, file_id):
 
609
        return os.readlink(self.id2abspath(file_id))
 
610
 
 
611
    def file_class(self, filename):
 
612
        if self.path2id(filename):
 
613
            return 'V'
 
614
        elif self.is_ignored(filename):
 
615
            return 'I'
 
616
        else:
 
617
            return '?'
 
618
 
 
619
    def list_files(self):
 
620
        """Recursively list all files as (path, class, kind, id).
 
621
 
 
622
        Lists, but does not descend into unversioned directories.
 
623
 
 
624
        This does not include files that have been deleted in this
 
625
        tree.
 
626
 
 
627
        Skips the control directory.
 
628
        """
 
629
        inv = self._inventory
 
630
 
 
631
        def descend(from_dir_relpath, from_dir_id, dp):
 
632
            ls = os.listdir(dp)
 
633
            ls.sort()
 
634
            for f in ls:
 
635
                ## TODO: If we find a subdirectory with its own .bzr
 
636
                ## directory, then that is a separate tree and we
 
637
                ## should exclude it.
 
638
 
 
639
                # the bzrdir for this tree
 
640
                if self.bzrdir.transport.base.endswith(f + '/'):
 
641
                    continue
 
642
 
 
643
                # path within tree
 
644
                fp = appendpath(from_dir_relpath, f)
 
645
 
 
646
                # absolute path
 
647
                fap = appendpath(dp, f)
 
648
                
 
649
                f_ie = inv.get_child(from_dir_id, f)
 
650
                if f_ie:
 
651
                    c = 'V'
 
652
                elif self.is_ignored(fp):
 
653
                    c = 'I'
 
654
                else:
 
655
                    c = '?'
 
656
 
 
657
                fk = file_kind(fap)
 
658
 
 
659
                if f_ie:
 
660
                    if f_ie.kind != fk:
 
661
                        raise BzrCheckError("file %r entered as kind %r id %r, "
 
662
                                            "now of kind %r"
 
663
                                            % (fap, f_ie.kind, f_ie.file_id, fk))
 
664
 
 
665
                # make a last minute entry
 
666
                if f_ie:
 
667
                    entry = f_ie
 
668
                else:
 
669
                    if fk == 'directory':
 
670
                        entry = TreeDirectory()
 
671
                    elif fk == 'file':
 
672
                        entry = TreeFile()
 
673
                    elif fk == 'symlink':
 
674
                        entry = TreeLink()
 
675
                    else:
 
676
                        entry = TreeEntry()
 
677
                
 
678
                yield fp, c, fk, (f_ie and f_ie.file_id), entry
 
679
 
 
680
                if fk != 'directory':
 
681
                    continue
 
682
 
 
683
                if c != 'V':
 
684
                    # don't descend unversioned directories
 
685
                    continue
 
686
                
 
687
                for ff in descend(fp, f_ie.file_id, fap):
 
688
                    yield ff
 
689
 
 
690
        for f in descend(u'', inv.root.file_id, self.basedir):
 
691
            yield f
 
692
 
 
693
    @needs_write_lock
 
694
    def move(self, from_paths, to_name):
 
695
        """Rename files.
 
696
 
 
697
        to_name must exist in the inventory.
 
698
 
 
699
        If to_name exists and is a directory, the files are moved into
 
700
        it, keeping their old names.  
 
701
 
 
702
        Note that to_name is only the last component of the new name;
 
703
        this doesn't change the directory.
 
704
 
 
705
        This returns a list of (from_path, to_path) pairs for each
 
706
        entry that is moved.
 
707
        """
 
708
        result = []
 
709
        ## TODO: Option to move IDs only
 
710
        assert not isinstance(from_paths, basestring)
 
711
        inv = self.inventory
 
712
        to_abs = self.abspath(to_name)
 
713
        if not isdir(to_abs):
 
714
            raise BzrError("destination %r is not a directory" % to_abs)
 
715
        if not self.has_filename(to_name):
 
716
            raise BzrError("destination %r not in working directory" % to_abs)
 
717
        to_dir_id = inv.path2id(to_name)
 
718
        if to_dir_id == None and to_name != '':
 
719
            raise BzrError("destination %r is not a versioned directory" % to_name)
 
720
        to_dir_ie = inv[to_dir_id]
 
721
        if to_dir_ie.kind not in ('directory', 'root_directory'):
 
722
            raise BzrError("destination %r is not a directory" % to_abs)
 
723
 
 
724
        to_idpath = inv.get_idpath(to_dir_id)
 
725
 
 
726
        for f in from_paths:
 
727
            if not self.has_filename(f):
 
728
                raise BzrError("%r does not exist in working tree" % f)
 
729
            f_id = inv.path2id(f)
 
730
            if f_id == None:
 
731
                raise BzrError("%r is not versioned" % f)
 
732
            name_tail = splitpath(f)[-1]
 
733
            dest_path = appendpath(to_name, name_tail)
 
734
            if self.has_filename(dest_path):
 
735
                raise BzrError("destination %r already exists" % dest_path)
 
736
            if f_id in to_idpath:
 
737
                raise BzrError("can't move %r to a subdirectory of itself" % f)
 
738
 
 
739
        # OK, so there's a race here, it's possible that someone will
 
740
        # create a file in this interval and then the rename might be
 
741
        # left half-done.  But we should have caught most problems.
 
742
        orig_inv = deepcopy(self.inventory)
 
743
        try:
 
744
            for f in from_paths:
 
745
                name_tail = splitpath(f)[-1]
 
746
                dest_path = appendpath(to_name, name_tail)
 
747
                result.append((f, dest_path))
 
748
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
 
749
                try:
 
750
                    rename(self.abspath(f), self.abspath(dest_path))
 
751
                except OSError, e:
 
752
                    raise BzrError("failed to rename %r to %r: %s" %
 
753
                                   (f, dest_path, e[1]),
 
754
                            ["rename rolled back"])
 
755
        except:
 
756
            # restore the inventory on error
 
757
            self._set_inventory(orig_inv)
 
758
            raise
 
759
        self._write_inventory(inv)
 
760
        return result
 
761
 
 
762
    @needs_write_lock
 
763
    def rename_one(self, from_rel, to_rel):
 
764
        """Rename one file.
 
765
 
 
766
        This can change the directory or the filename or both.
 
767
        """
 
768
        inv = self.inventory
 
769
        if not self.has_filename(from_rel):
 
770
            raise BzrError("can't rename: old working file %r does not exist" % from_rel)
 
771
        if self.has_filename(to_rel):
 
772
            raise BzrError("can't rename: new working file %r already exists" % to_rel)
 
773
 
 
774
        file_id = inv.path2id(from_rel)
 
775
        if file_id == None:
 
776
            raise BzrError("can't rename: old name %r is not versioned" % from_rel)
 
777
 
 
778
        entry = inv[file_id]
 
779
        from_parent = entry.parent_id
 
780
        from_name = entry.name
 
781
        
 
782
        if inv.path2id(to_rel):
 
783
            raise BzrError("can't rename: new name %r is already versioned" % to_rel)
 
784
 
 
785
        to_dir, to_tail = os.path.split(to_rel)
 
786
        to_dir_id = inv.path2id(to_dir)
 
787
        if to_dir_id == None and to_dir != '':
 
788
            raise BzrError("can't determine destination directory id for %r" % to_dir)
 
789
 
 
790
        mutter("rename_one:")
 
791
        mutter("  file_id    {%s}" % file_id)
 
792
        mutter("  from_rel   %r" % from_rel)
 
793
        mutter("  to_rel     %r" % to_rel)
 
794
        mutter("  to_dir     %r" % to_dir)
 
795
        mutter("  to_dir_id  {%s}" % to_dir_id)
 
796
 
 
797
        inv.rename(file_id, to_dir_id, to_tail)
 
798
 
 
799
        from_abs = self.abspath(from_rel)
 
800
        to_abs = self.abspath(to_rel)
 
801
        try:
 
802
            rename(from_abs, to_abs)
 
803
        except OSError, e:
 
804
            inv.rename(file_id, from_parent, from_name)
 
805
            raise BzrError("failed to rename %r to %r: %s"
 
806
                    % (from_abs, to_abs, e[1]),
 
807
                    ["rename rolled back"])
 
808
        self._write_inventory(inv)
 
809
 
 
810
    @needs_read_lock
 
811
    def unknowns(self):
 
812
        """Return all unknown files.
 
813
 
 
814
        These are files in the working directory that are not versioned or
 
815
        control files or ignored.
 
816
        
 
817
        >>> from bzrlib.bzrdir import ScratchDir
 
818
        >>> d = ScratchDir(files=['foo', 'foo~'])
 
819
        >>> b = d.open_branch()
 
820
        >>> tree = d.open_workingtree()
 
821
        >>> map(str, tree.unknowns())
 
822
        ['foo']
 
823
        >>> tree.add('foo')
 
824
        >>> list(b.unknowns())
 
825
        []
 
826
        >>> tree.remove('foo')
 
827
        >>> list(b.unknowns())
 
828
        [u'foo']
 
829
        """
 
830
        for subp in self.extras():
 
831
            if not self.is_ignored(subp):
 
832
                yield subp
 
833
 
 
834
    def iter_conflicts(self):
 
835
        conflicted = set()
 
836
        for path in (s[0] for s in self.list_files()):
 
837
            stem = get_conflicted_stem(path)
 
838
            if stem is None:
 
839
                continue
 
840
            if stem not in conflicted:
 
841
                conflicted.add(stem)
 
842
                yield stem
 
843
 
 
844
    @needs_write_lock
 
845
    def pull(self, source, overwrite=False, stop_revision=None):
 
846
        source.lock_read()
 
847
        try:
 
848
            old_revision_history = self.branch.revision_history()
 
849
            basis_tree = self.basis_tree()
 
850
            count = self.branch.pull(source, overwrite, stop_revision)
 
851
            new_revision_history = self.branch.revision_history()
 
852
            if new_revision_history != old_revision_history:
 
853
                if len(old_revision_history):
 
854
                    other_revision = old_revision_history[-1]
 
855
                else:
 
856
                    other_revision = None
 
857
                repository = self.branch.repository
 
858
                merge_inner(self.branch,
 
859
                            self.branch.basis_tree(),
 
860
                            basis_tree, 
 
861
                            this_tree=self, 
 
862
                            pb=bzrlib.ui.ui_factory.progress_bar())
 
863
                self.set_last_revision(self.branch.last_revision())
 
864
            return count
 
865
        finally:
 
866
            source.unlock()
 
867
 
 
868
    def extras(self):
 
869
        """Yield all unknown files in this WorkingTree.
 
870
 
 
871
        If there are any unknown directories then only the directory is
 
872
        returned, not all its children.  But if there are unknown files
 
873
        under a versioned subdirectory, they are returned.
 
874
 
 
875
        Currently returned depth-first, sorted by name within directories.
 
876
        """
 
877
        ## TODO: Work from given directory downwards
 
878
        for path, dir_entry in self.inventory.directories():
 
879
            mutter("search for unknowns in %r", path)
 
880
            dirabs = self.abspath(path)
 
881
            if not isdir(dirabs):
 
882
                # e.g. directory deleted
 
883
                continue
 
884
 
 
885
            fl = []
 
886
            for subf in os.listdir(dirabs):
 
887
                if (subf != '.bzr'
 
888
                    and (subf not in dir_entry.children)):
 
889
                    fl.append(subf)
 
890
            
 
891
            fl.sort()
 
892
            for subf in fl:
 
893
                subp = appendpath(path, subf)
 
894
                yield subp
 
895
 
 
896
 
 
897
    def ignored_files(self):
 
898
        """Yield list of PATH, IGNORE_PATTERN"""
 
899
        for subp in self.extras():
 
900
            pat = self.is_ignored(subp)
 
901
            if pat != None:
 
902
                yield subp, pat
 
903
 
 
904
 
 
905
    def get_ignore_list(self):
 
906
        """Return list of ignore patterns.
 
907
 
 
908
        Cached in the Tree object after the first call.
 
909
        """
 
910
        if hasattr(self, '_ignorelist'):
 
911
            return self._ignorelist
 
912
 
 
913
        l = bzrlib.DEFAULT_IGNORE[:]
 
914
        if self.has_filename(bzrlib.IGNORE_FILENAME):
 
915
            f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
 
916
            l.extend([line.rstrip("\n\r") for line in f.readlines()])
 
917
        self._ignorelist = l
 
918
        return l
 
919
 
 
920
 
 
921
    def is_ignored(self, filename):
 
922
        r"""Check whether the filename matches an ignore pattern.
 
923
 
 
924
        Patterns containing '/' or '\' need to match the whole path;
 
925
        others match against only the last component.
 
926
 
 
927
        If the file is ignored, returns the pattern which caused it to
 
928
        be ignored, otherwise None.  So this can simply be used as a
 
929
        boolean if desired."""
 
930
 
 
931
        # TODO: Use '**' to match directories, and other extended
 
932
        # globbing stuff from cvs/rsync.
 
933
 
 
934
        # XXX: fnmatch is actually not quite what we want: it's only
 
935
        # approximately the same as real Unix fnmatch, and doesn't
 
936
        # treat dotfiles correctly and allows * to match /.
 
937
        # Eventually it should be replaced with something more
 
938
        # accurate.
 
939
        
 
940
        for pat in self.get_ignore_list():
 
941
            if '/' in pat or '\\' in pat:
 
942
                
 
943
                # as a special case, you can put ./ at the start of a
 
944
                # pattern; this is good to match in the top-level
 
945
                # only;
 
946
                
 
947
                if (pat[:2] == './') or (pat[:2] == '.\\'):
 
948
                    newpat = pat[2:]
 
949
                else:
 
950
                    newpat = pat
 
951
                if fnmatch.fnmatchcase(filename, newpat):
 
952
                    return pat
 
953
            else:
 
954
                if fnmatch.fnmatchcase(splitpath(filename)[-1], pat):
 
955
                    return pat
 
956
        else:
 
957
            return None
 
958
 
 
959
    def kind(self, file_id):
 
960
        return file_kind(self.id2abspath(file_id))
 
961
 
 
962
    @needs_read_lock
 
963
    def last_revision(self):
 
964
        """Return the last revision id of this working tree.
 
965
 
 
966
        In early branch formats this was == the branch last_revision,
 
967
        but that cannot be relied upon - for working tree operations,
 
968
        always use tree.last_revision().
 
969
        """
 
970
        return self.branch.last_revision()
 
971
 
 
972
    def lock_read(self):
 
973
        """See Branch.lock_read, and WorkingTree.unlock."""
 
974
        self.branch.lock_read()
 
975
        try:
 
976
            return self._control_files.lock_read()
 
977
        except:
 
978
            self.branch.unlock()
 
979
            raise
 
980
 
 
981
    def lock_write(self):
 
982
        """See Branch.lock_write, and WorkingTree.unlock."""
 
983
        self.branch.lock_write()
 
984
        try:
 
985
            return self._control_files.lock_write()
 
986
        except:
 
987
            self.branch.unlock()
 
988
            raise
 
989
 
 
990
    def _basis_inventory_name(self, revision_id):
 
991
        return 'basis-inventory.%s' % revision_id
 
992
 
 
993
    @needs_write_lock
 
994
    def set_last_revision(self, new_revision, old_revision=None):
 
995
        """Change the last revision in the working tree."""
 
996
        self._remove_old_basis(old_revision)
 
997
        if self._change_last_revision(new_revision):
 
998
            self._cache_basis_inventory(new_revision)
 
999
 
 
1000
    def _change_last_revision(self, new_revision):
 
1001
        """Template method part of set_last_revision to perform the change."""
 
1002
        if new_revision is None:
 
1003
            self.branch.set_revision_history([])
 
1004
            return False
 
1005
        # current format is locked in with the branch
 
1006
        revision_history = self.branch.revision_history()
 
1007
        try:
 
1008
            position = revision_history.index(new_revision)
 
1009
        except ValueError:
 
1010
            raise errors.NoSuchRevision(self.branch, new_revision)
 
1011
        self.branch.set_revision_history(revision_history[:position + 1])
 
1012
        return True
 
1013
 
 
1014
    def _cache_basis_inventory(self, new_revision):
 
1015
        """Cache new_revision as the basis inventory."""
 
1016
        try:
 
1017
            xml = self.branch.repository.get_inventory_xml(new_revision)
 
1018
            path = self._basis_inventory_name(new_revision)
 
1019
            self._control_files.put_utf8(path, xml)
 
1020
        except WeaveRevisionNotPresent:
 
1021
            pass
 
1022
 
 
1023
    def _remove_old_basis(self, old_revision):
 
1024
        """Remove the old basis inventory 'old_revision'."""
 
1025
        if old_revision is not None:
 
1026
            try:
 
1027
                path = self._basis_inventory_name(old_revision)
 
1028
                path = self._control_files._escape(path)
 
1029
                self._control_files._transport.delete(path)
 
1030
            except NoSuchFile:
 
1031
                pass
 
1032
 
 
1033
    def read_basis_inventory(self, revision_id):
 
1034
        """Read the cached basis inventory."""
 
1035
        path = self._basis_inventory_name(revision_id)
 
1036
        return self._control_files.get_utf8(path).read()
 
1037
        
 
1038
    @needs_read_lock
 
1039
    def read_working_inventory(self):
 
1040
        """Read the working inventory."""
 
1041
        # ElementTree does its own conversion from UTF-8, so open in
 
1042
        # binary.
 
1043
        result = bzrlib.xml5.serializer_v5.read_inventory(
 
1044
            self._control_files.get('inventory'))
 
1045
        self._set_inventory(result)
 
1046
        return result
 
1047
 
 
1048
    @needs_write_lock
 
1049
    def remove(self, files, verbose=False):
 
1050
        """Remove nominated files from the working inventory..
 
1051
 
 
1052
        This does not remove their text.  This does not run on XXX on what? RBC
 
1053
 
 
1054
        TODO: Refuse to remove modified files unless --force is given?
 
1055
 
 
1056
        TODO: Do something useful with directories.
 
1057
 
 
1058
        TODO: Should this remove the text or not?  Tough call; not
 
1059
        removing may be useful and the user can just use use rm, and
 
1060
        is the opposite of add.  Removing it is consistent with most
 
1061
        other tools.  Maybe an option.
 
1062
        """
 
1063
        ## TODO: Normalize names
 
1064
        ## TODO: Remove nested loops; better scalability
 
1065
        if isinstance(files, basestring):
 
1066
            files = [files]
 
1067
 
 
1068
        inv = self.inventory
 
1069
 
 
1070
        # do this before any modifications
 
1071
        for f in files:
 
1072
            fid = inv.path2id(f)
 
1073
            if not fid:
 
1074
                # TODO: Perhaps make this just a warning, and continue?
 
1075
                # This tends to happen when 
 
1076
                raise NotVersionedError(path=f)
 
1077
            mutter("remove inventory entry %s {%s}", quotefn(f), fid)
 
1078
            if verbose:
 
1079
                # having remove it, it must be either ignored or unknown
 
1080
                if self.is_ignored(f):
 
1081
                    new_status = 'I'
 
1082
                else:
 
1083
                    new_status = '?'
 
1084
                show_status(new_status, inv[fid].kind, quotefn(f))
 
1085
            del inv[fid]
 
1086
 
 
1087
        self._write_inventory(inv)
 
1088
 
 
1089
    @needs_write_lock
 
1090
    def revert(self, filenames, old_tree=None, backups=True, 
 
1091
               pb=DummyProgress()):
 
1092
        from transform import revert
 
1093
        if old_tree is None:
 
1094
            old_tree = self.basis_tree()
 
1095
        revert(self, old_tree, filenames, backups, pb)
 
1096
        if not len(filenames):
 
1097
            self.set_pending_merges([])
 
1098
 
 
1099
    @needs_write_lock
 
1100
    def set_inventory(self, new_inventory_list):
 
1101
        from bzrlib.inventory import (Inventory,
 
1102
                                      InventoryDirectory,
 
1103
                                      InventoryEntry,
 
1104
                                      InventoryFile,
 
1105
                                      InventoryLink)
 
1106
        inv = Inventory(self.get_root_id())
 
1107
        for path, file_id, parent, kind in new_inventory_list:
 
1108
            name = os.path.basename(path)
 
1109
            if name == "":
 
1110
                continue
 
1111
            # fixme, there should be a factory function inv,add_?? 
 
1112
            if kind == 'directory':
 
1113
                inv.add(InventoryDirectory(file_id, name, parent))
 
1114
            elif kind == 'file':
 
1115
                inv.add(InventoryFile(file_id, name, parent))
 
1116
            elif kind == 'symlink':
 
1117
                inv.add(InventoryLink(file_id, name, parent))
 
1118
            else:
 
1119
                raise BzrError("unknown kind %r" % kind)
 
1120
        self._write_inventory(inv)
 
1121
 
 
1122
    @needs_write_lock
 
1123
    def set_root_id(self, file_id):
 
1124
        """Set the root id for this tree."""
 
1125
        inv = self.read_working_inventory()
 
1126
        orig_root_id = inv.root.file_id
 
1127
        del inv._byid[inv.root.file_id]
 
1128
        inv.root.file_id = file_id
 
1129
        inv._byid[inv.root.file_id] = inv.root
 
1130
        for fid in inv:
 
1131
            entry = inv[fid]
 
1132
            if entry.parent_id == orig_root_id:
 
1133
                entry.parent_id = inv.root.file_id
 
1134
        self._write_inventory(inv)
 
1135
 
 
1136
    def unlock(self):
 
1137
        """See Branch.unlock.
 
1138
        
 
1139
        WorkingTree locking just uses the Branch locking facilities.
 
1140
        This is current because all working trees have an embedded branch
 
1141
        within them. IF in the future, we were to make branch data shareable
 
1142
        between multiple working trees, i.e. via shared storage, then we 
 
1143
        would probably want to lock both the local tree, and the branch.
 
1144
        """
 
1145
        # FIXME: We want to write out the hashcache only when the last lock on
 
1146
        # this working copy is released.  Peeking at the lock count is a bit
 
1147
        # of a nasty hack; probably it's better to have a transaction object,
 
1148
        # which can do some finalization when it's either successfully or
 
1149
        # unsuccessfully completed.  (Denys's original patch did that.)
 
1150
        # RBC 20060206 hookinhg into transaction will couple lock and transaction
 
1151
        # wrongly. Hookinh into unllock on the control files object is fine though.
 
1152
        
 
1153
        # TODO: split this per format so there is no ugly if block
 
1154
        if self._hashcache.needs_write and (
 
1155
            # dedicated lock files
 
1156
            self._control_files._lock_count==1 or 
 
1157
            # shared lock files
 
1158
            (self._control_files is self.branch.control_files and 
 
1159
             self._control_files._lock_count==3)):
 
1160
            self._hashcache.write()
 
1161
        # reverse order of locking.
 
1162
        result = self._control_files.unlock()
 
1163
        try:
 
1164
            self.branch.unlock()
 
1165
        finally:
 
1166
            return result
 
1167
 
 
1168
    @needs_write_lock
 
1169
    def update(self):
 
1170
        """Update a working tree along its branch.
 
1171
 
 
1172
        This will update the branch if its bound too, which means we have multiple trees involved:
 
1173
        The new basis tree of the master.
 
1174
        The old basis tree of the branch.
 
1175
        The old basis tree of the working tree.
 
1176
        The current working tree state.
 
1177
        pathologically all three may be different, and non ancestors of each other.
 
1178
        Conceptually we want to:
 
1179
        Preserve the wt.basis->wt.state changes
 
1180
        Transform the wt.basis to the new master basis.
 
1181
        Apply a merge of the old branch basis to get any 'local' changes from it into the tree.
 
1182
        Restore the wt.basis->wt.state changes.
 
1183
 
 
1184
        There isn't a single operation at the moment to do that, so we:
 
1185
        Merge current state -> basis tree of the master w.r.t. the old tree basis.
 
1186
        Do a 'normal' merge of the old branch basis if it is relevant.
 
1187
        """
 
1188
        old_tip = self.branch.update()
 
1189
        if old_tip is not None:
 
1190
            self.add_pending_merge(old_tip)
 
1191
        self.branch.lock_read()
 
1192
        try:
 
1193
            result = 0
 
1194
            if self.last_revision() != self.branch.last_revision():
 
1195
                # merge tree state up to new branch tip.
 
1196
                basis = self.basis_tree()
 
1197
                to_tree = self.branch.basis_tree()
 
1198
                result += merge_inner(self.branch,
 
1199
                                      to_tree,
 
1200
                                      basis,
 
1201
                                      this_tree=self)
 
1202
                self.set_last_revision(self.branch.last_revision())
 
1203
            if old_tip and old_tip != self.last_revision():
 
1204
                # our last revision was not the prior branch last reivison
 
1205
                # and we have converted that last revision to a pending merge.
 
1206
                # base is somewhere between the branch tip now
 
1207
                # and the now pending merge
 
1208
                from bzrlib.revision import common_ancestor
 
1209
                try:
 
1210
                    base_rev_id = common_ancestor(self.branch.last_revision(),
 
1211
                                                  old_tip,
 
1212
                                                  self.branch.repository)
 
1213
                except errors.NoCommonAncestor:
 
1214
                    base_rev_id = None
 
1215
                base_tree = self.branch.repository.revision_tree(base_rev_id)
 
1216
                other_tree = self.branch.repository.revision_tree(old_tip)
 
1217
                result += merge_inner(self.branch,
 
1218
                                      other_tree,
 
1219
                                      base_tree,
 
1220
                                      this_tree=self)
 
1221
            return result
 
1222
        finally:
 
1223
            self.branch.unlock()
 
1224
 
 
1225
    @needs_write_lock
 
1226
    def _write_inventory(self, inv):
 
1227
        """Write inventory as the current inventory."""
 
1228
        sio = StringIO()
 
1229
        bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
 
1230
        sio.seek(0)
 
1231
        self._control_files.put('inventory', sio)
 
1232
        self._set_inventory(inv)
 
1233
        mutter('wrote working inventory')
 
1234
 
 
1235
 
 
1236
class WorkingTree3(WorkingTree):
 
1237
    """This is the Format 3 working tree.
 
1238
 
 
1239
    This differs from the base WorkingTree by:
 
1240
     - having its own file lock
 
1241
     - having its own last-revision property.
 
1242
    """
 
1243
 
 
1244
    @needs_read_lock
 
1245
    def last_revision(self):
 
1246
        """See WorkingTree.last_revision."""
 
1247
        try:
 
1248
            return self._control_files.get_utf8('last-revision').read()
 
1249
        except NoSuchFile:
 
1250
            return None
 
1251
 
 
1252
    def _change_last_revision(self, revision_id):
 
1253
        """See WorkingTree._change_last_revision."""
 
1254
        if revision_id is None or revision_id == NULL_REVISION:
 
1255
            try:
 
1256
                self._control_files._transport.delete('last-revision')
 
1257
            except errors.NoSuchFile:
 
1258
                pass
 
1259
            return False
 
1260
        else:
 
1261
            try:
 
1262
                self.branch.revision_history().index(revision_id)
 
1263
            except ValueError:
 
1264
                raise errors.NoSuchRevision(self.branch, revision_id)
 
1265
            self._control_files.put_utf8('last-revision', revision_id)
 
1266
            return True
 
1267
 
 
1268
 
 
1269
CONFLICT_SUFFIXES = ('.THIS', '.BASE', '.OTHER')
 
1270
def get_conflicted_stem(path):
 
1271
    for suffix in CONFLICT_SUFFIXES:
 
1272
        if path.endswith(suffix):
 
1273
            return path[:-len(suffix)]
 
1274
 
 
1275
@deprecated_function(zero_eight)
 
1276
def is_control_file(filename):
 
1277
    """See WorkingTree.is_control_filename(filename)."""
 
1278
    ## FIXME: better check
 
1279
    filename = normpath(filename)
 
1280
    while filename != '':
 
1281
        head, tail = os.path.split(filename)
 
1282
        ## mutter('check %r for control file' % ((head, tail),))
 
1283
        if tail == '.bzr':
 
1284
            return True
 
1285
        if filename == head:
 
1286
            break
 
1287
        filename = head
 
1288
    return False
 
1289
 
 
1290
 
 
1291
class WorkingTreeFormat(object):
 
1292
    """An encapsulation of the initialization and open routines for a format.
 
1293
 
 
1294
    Formats provide three things:
 
1295
     * An initialization routine,
 
1296
     * a format string,
 
1297
     * an open routine.
 
1298
 
 
1299
    Formats are placed in an dict by their format string for reference 
 
1300
    during workingtree opening. Its not required that these be instances, they
 
1301
    can be classes themselves with class methods - it simply depends on 
 
1302
    whether state is needed for a given format or not.
 
1303
 
 
1304
    Once a format is deprecated, just deprecate the initialize and open
 
1305
    methods on the format class. Do not deprecate the object, as the 
 
1306
    object will be created every time regardless.
 
1307
    """
 
1308
 
 
1309
    _default_format = None
 
1310
    """The default format used for new trees."""
 
1311
 
 
1312
    _formats = {}
 
1313
    """The known formats."""
 
1314
 
 
1315
    @classmethod
 
1316
    def find_format(klass, a_bzrdir):
 
1317
        """Return the format for the working tree object in a_bzrdir."""
 
1318
        try:
 
1319
            transport = a_bzrdir.get_workingtree_transport(None)
 
1320
            format_string = transport.get("format").read()
 
1321
            return klass._formats[format_string]
 
1322
        except NoSuchFile:
 
1323
            raise errors.NoWorkingTree(base=transport.base)
 
1324
        except KeyError:
 
1325
            raise errors.UnknownFormatError(format_string)
 
1326
 
 
1327
    @classmethod
 
1328
    def get_default_format(klass):
 
1329
        """Return the current default format."""
 
1330
        return klass._default_format
 
1331
 
 
1332
    def get_format_string(self):
 
1333
        """Return the ASCII format string that identifies this format."""
 
1334
        raise NotImplementedError(self.get_format_string)
 
1335
 
 
1336
    def is_supported(self):
 
1337
        """Is this format supported?
 
1338
 
 
1339
        Supported formats can be initialized and opened.
 
1340
        Unsupported formats may not support initialization or committing or 
 
1341
        some other features depending on the reason for not being supported.
 
1342
        """
 
1343
        return True
 
1344
 
 
1345
    @classmethod
 
1346
    def register_format(klass, format):
 
1347
        klass._formats[format.get_format_string()] = format
 
1348
 
 
1349
    @classmethod
 
1350
    def set_default_format(klass, format):
 
1351
        klass._default_format = format
 
1352
 
 
1353
    @classmethod
 
1354
    def unregister_format(klass, format):
 
1355
        assert klass._formats[format.get_format_string()] is format
 
1356
        del klass._formats[format.get_format_string()]
 
1357
 
 
1358
 
 
1359
 
 
1360
class WorkingTreeFormat2(WorkingTreeFormat):
 
1361
    """The second working tree format. 
 
1362
 
 
1363
    This format modified the hash cache from the format 1 hash cache.
 
1364
    """
 
1365
 
 
1366
    def initialize(self, a_bzrdir, revision_id=None):
 
1367
        """See WorkingTreeFormat.initialize()."""
 
1368
        if not isinstance(a_bzrdir.transport, LocalTransport):
 
1369
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
 
1370
        branch = a_bzrdir.open_branch()
 
1371
        if revision_id is not None:
 
1372
            branch.lock_write()
 
1373
            try:
 
1374
                revision_history = branch.revision_history()
 
1375
                try:
 
1376
                    position = revision_history.index(revision_id)
 
1377
                except ValueError:
 
1378
                    raise errors.NoSuchRevision(branch, revision_id)
 
1379
                branch.set_revision_history(revision_history[:position + 1])
 
1380
            finally:
 
1381
                branch.unlock()
 
1382
        revision = branch.last_revision()
 
1383
        inv = Inventory() 
 
1384
        wt = WorkingTree(a_bzrdir.root_transport.base,
 
1385
                         branch,
 
1386
                         inv,
 
1387
                         _internal=True,
 
1388
                         _format=self,
 
1389
                         _bzrdir=a_bzrdir)
 
1390
        wt._write_inventory(inv)
 
1391
        wt.set_root_id(inv.root.file_id)
 
1392
        wt.set_last_revision(revision)
 
1393
        wt.set_pending_merges([])
 
1394
        build_tree(wt.basis_tree(), wt)
 
1395
        return wt
 
1396
 
 
1397
    def __init__(self):
 
1398
        super(WorkingTreeFormat2, self).__init__()
 
1399
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
 
1400
 
 
1401
    def open(self, a_bzrdir, _found=False):
 
1402
        """Return the WorkingTree object for a_bzrdir
 
1403
 
 
1404
        _found is a private parameter, do not use it. It is used to indicate
 
1405
               if format probing has already been done.
 
1406
        """
 
1407
        if not _found:
 
1408
            # we are being called directly and must probe.
 
1409
            raise NotImplementedError
 
1410
        if not isinstance(a_bzrdir.transport, LocalTransport):
 
1411
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
 
1412
        return WorkingTree(a_bzrdir.root_transport.base,
 
1413
                           _internal=True,
 
1414
                           _format=self,
 
1415
                           _bzrdir=a_bzrdir)
 
1416
 
 
1417
 
 
1418
class WorkingTreeFormat3(WorkingTreeFormat):
 
1419
    """The second working tree format updated to record a format marker.
 
1420
 
 
1421
    This format modified the hash cache from the format 1 hash cache.
 
1422
    """
 
1423
 
 
1424
    def get_format_string(self):
 
1425
        """See WorkingTreeFormat.get_format_string()."""
 
1426
        return "Bazaar-NG Working Tree format 3"
 
1427
 
 
1428
    def initialize(self, a_bzrdir, revision_id=None):
 
1429
        """See WorkingTreeFormat.initialize().
 
1430
        
 
1431
        revision_id allows creating a working tree at a differnet
 
1432
        revision than the branch is at.
 
1433
        """
 
1434
        if not isinstance(a_bzrdir.transport, LocalTransport):
 
1435
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
 
1436
        transport = a_bzrdir.get_workingtree_transport(self)
 
1437
        control_files = LockableFiles(transport, 'lock', TransportLock)
 
1438
        control_files.put_utf8('format', self.get_format_string())
 
1439
        branch = a_bzrdir.open_branch()
 
1440
        if revision_id is None:
 
1441
            revision_id = branch.last_revision()
 
1442
        inv = Inventory() 
 
1443
        wt = WorkingTree3(a_bzrdir.root_transport.base,
 
1444
                         branch,
 
1445
                         inv,
 
1446
                         _internal=True,
 
1447
                         _format=self,
 
1448
                         _bzrdir=a_bzrdir)
 
1449
        wt._write_inventory(inv)
 
1450
        wt.set_root_id(inv.root.file_id)
 
1451
        wt.set_last_revision(revision_id)
 
1452
        wt.set_pending_merges([])
 
1453
        build_tree(wt.basis_tree(), wt)
 
1454
        return wt
 
1455
 
 
1456
    def __init__(self):
 
1457
        super(WorkingTreeFormat3, self).__init__()
 
1458
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
1459
 
 
1460
    def open(self, a_bzrdir, _found=False):
 
1461
        """Return the WorkingTree object for a_bzrdir
 
1462
 
 
1463
        _found is a private parameter, do not use it. It is used to indicate
 
1464
               if format probing has already been done.
 
1465
        """
 
1466
        if not _found:
 
1467
            # we are being called directly and must probe.
 
1468
            raise NotImplementedError
 
1469
        if not isinstance(a_bzrdir.transport, LocalTransport):
 
1470
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
 
1471
        return WorkingTree3(a_bzrdir.root_transport.base,
 
1472
                           _internal=True,
 
1473
                           _format=self,
 
1474
                           _bzrdir=a_bzrdir)
 
1475
 
 
1476
    def __str__(self):
 
1477
        return self.get_format_string()
 
1478
 
 
1479
 
 
1480
# formats which have no format string are not discoverable
 
1481
# and not independently creatable, so are not registered.
 
1482
__default_format = WorkingTreeFormat3()
 
1483
WorkingTreeFormat.register_format(__default_format)
 
1484
WorkingTreeFormat.set_default_format(__default_format)
 
1485
_legacy_formats = [WorkingTreeFormat2(),
 
1486
                   ]
 
1487
 
 
1488
 
 
1489
class WorkingTreeTestProviderAdapter(object):
 
1490
    """A tool to generate a suite testing multiple workingtree formats at once.
 
1491
 
 
1492
    This is done by copying the test once for each transport and injecting
 
1493
    the transport_server, transport_readonly_server, and workingtree_format
 
1494
    classes into each copy. Each copy is also given a new id() to make it
 
1495
    easy to identify.
 
1496
    """
 
1497
 
 
1498
    def __init__(self, transport_server, transport_readonly_server, formats):
 
1499
        self._transport_server = transport_server
 
1500
        self._transport_readonly_server = transport_readonly_server
 
1501
        self._formats = formats
 
1502
    
 
1503
    def adapt(self, test):
 
1504
        from bzrlib.tests import TestSuite
 
1505
        result = TestSuite()
 
1506
        for workingtree_format, bzrdir_format in self._formats:
 
1507
            new_test = deepcopy(test)
 
1508
            new_test.transport_server = self._transport_server
 
1509
            new_test.transport_readonly_server = self._transport_readonly_server
 
1510
            new_test.bzrdir_format = bzrdir_format
 
1511
            new_test.workingtree_format = workingtree_format
 
1512
            def make_new_test_id():
 
1513
                new_id = "%s(%s)" % (new_test.id(), workingtree_format.__class__.__name__)
 
1514
                return lambda: new_id
 
1515
            new_test.id = make_new_test_id()
 
1516
            result.addTest(new_test)
 
1517
        return result