/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: Aaron Bentley
  • Date: 2007-01-11 03:46:53 UTC
  • mto: (2255.6.1 dirstate)
  • mto: This revision was merged to the branch mainline in revision 2322.
  • Revision ID: aaron.bentley@utoronto.ca-20070111034653-wa1n3uy49wbvom5m
Remove get_format_*, make FormatRegistry.register_metadir vary working tree

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006 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
# TODO: Give the workingtree sole responsibility for the working inventory;
 
33
# remove the variable and references to it from the branch.  This may require
 
34
# updating the commit code so as to update the inventory within the working
 
35
# copy, and making sure there's only one WorkingTree for any directory on disk.
 
36
# At the moment they may alias the inventory and have old copies of it in
 
37
# memory.  (Now done? -- mbp 20060309)
 
38
 
 
39
from cStringIO import StringIO
 
40
import os
 
41
 
 
42
from bzrlib.lazy_import import lazy_import
 
43
lazy_import(globals(), """
 
44
import collections
 
45
from copy import deepcopy
 
46
import errno
 
47
import stat
 
48
from time import time
 
49
import warnings
 
50
 
 
51
import bzrlib
 
52
from bzrlib import (
 
53
    branch,
 
54
    bzrdir,
 
55
    conflicts as _mod_conflicts,
 
56
    errors,
 
57
    generate_ids,
 
58
    globbing,
 
59
    hashcache,
 
60
    ignores,
 
61
    merge,
 
62
    osutils,
 
63
    repository,
 
64
    textui,
 
65
    transform,
 
66
    urlutils,
 
67
    xml5,
 
68
    xml6,
 
69
    xml7,
 
70
    )
 
71
import bzrlib.branch
 
72
from bzrlib.transport import get_transport
 
73
import bzrlib.ui
 
74
""")
 
75
 
 
76
from bzrlib import symbol_versioning
 
77
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
78
from bzrlib.errors import (BzrCheckError,
 
79
                           BzrError,
 
80
                           ConflictFormatError,
 
81
                           WeaveRevisionNotPresent,
 
82
                           NotBranchError,
 
83
                           NoSuchFile,
 
84
                           NotVersionedError,
 
85
                           MergeModifiedFormatError,
 
86
                           UnsupportedOperation,
 
87
                           )
 
88
from bzrlib.inventory import InventoryEntry, Inventory, ROOT_ID, TreeReference
 
89
from bzrlib.lockable_files import LockableFiles, TransportLock
 
90
from bzrlib.lockdir import LockDir
 
91
import bzrlib.mutabletree
 
92
from bzrlib.mutabletree import needs_tree_write_lock
 
93
from bzrlib.osutils import (
 
94
    compact_date,
 
95
    file_kind,
 
96
    isdir,
 
97
    pathjoin,
 
98
    safe_unicode,
 
99
    splitpath,
 
100
    rand_chars,
 
101
    normpath,
 
102
    realpath,
 
103
    supports_executable,
 
104
    )
 
105
from bzrlib.trace import mutter, note
 
106
from bzrlib.transport.local import LocalTransport
 
107
import bzrlib.tree
 
108
from bzrlib.progress import DummyProgress, ProgressPhase
 
109
from bzrlib.revision import NULL_REVISION, CURRENT_REVISION
 
110
import bzrlib.revisiontree
 
111
from bzrlib.rio import RioReader, rio_file, Stanza
 
112
from bzrlib.symbol_versioning import (deprecated_passed,
 
113
        deprecated_method,
 
114
        deprecated_function,
 
115
        DEPRECATED_PARAMETER,
 
116
        zero_eight,
 
117
        zero_eleven,
 
118
        zero_thirteen,
 
119
        )
 
120
 
 
121
 
 
122
MERGE_MODIFIED_HEADER_1 = "BZR merge-modified list format 1"
 
123
CONFLICT_HEADER_1 = "BZR conflict list format 1"
 
124
 
 
125
 
 
126
@deprecated_function(zero_thirteen)
 
127
def gen_file_id(name):
 
128
    """Return new file id for the basename 'name'.
 
129
 
 
130
    Use bzrlib.generate_ids.gen_file_id() instead
 
131
    """
 
132
    return generate_ids.gen_file_id(name)
 
133
 
 
134
 
 
135
@deprecated_function(zero_thirteen)
 
136
def gen_root_id():
 
137
    """Return a new tree-root file id.
 
138
 
 
139
    This has been deprecated in favor of bzrlib.generate_ids.gen_root_id()
 
140
    """
 
141
    return generate_ids.gen_root_id()
 
142
 
 
143
 
 
144
class TreeEntry(object):
 
145
    """An entry that implements the minimum interface used by commands.
 
146
 
 
147
    This needs further inspection, it may be better to have 
 
148
    InventoryEntries without ids - though that seems wrong. For now,
 
149
    this is a parallel hierarchy to InventoryEntry, and needs to become
 
150
    one of several things: decorates to that hierarchy, children of, or
 
151
    parents of it.
 
152
    Another note is that these objects are currently only used when there is
 
153
    no InventoryEntry available - i.e. for unversioned objects.
 
154
    Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
 
155
    """
 
156
 
 
157
    def __eq__(self, other):
 
158
        # yes, this us ugly, TODO: best practice __eq__ style.
 
159
        return (isinstance(other, TreeEntry)
 
160
                and other.__class__ == self.__class__)
 
161
 
 
162
    def kind_character(self):
 
163
        return "???"
 
164
 
 
165
 
 
166
class TreeDirectory(TreeEntry):
 
167
    """See TreeEntry. This is a directory in a working tree."""
 
168
 
 
169
    def __eq__(self, other):
 
170
        return (isinstance(other, TreeDirectory)
 
171
                and other.__class__ == self.__class__)
 
172
 
 
173
    def kind_character(self):
 
174
        return "/"
 
175
 
 
176
 
 
177
class TreeFile(TreeEntry):
 
178
    """See TreeEntry. This is a regular file in a working tree."""
 
179
 
 
180
    def __eq__(self, other):
 
181
        return (isinstance(other, TreeFile)
 
182
                and other.__class__ == self.__class__)
 
183
 
 
184
    def kind_character(self):
 
185
        return ''
 
186
 
 
187
 
 
188
class TreeLink(TreeEntry):
 
189
    """See TreeEntry. This is a symlink in a working tree."""
 
190
 
 
191
    def __eq__(self, other):
 
192
        return (isinstance(other, TreeLink)
 
193
                and other.__class__ == self.__class__)
 
194
 
 
195
    def kind_character(self):
 
196
        return ''
 
197
 
 
198
 
 
199
class WorkingTree(bzrlib.mutabletree.MutableTree):
 
200
    """Working copy tree.
 
201
 
 
202
    The inventory is held in the `Branch` working-inventory, and the
 
203
    files are in a directory on disk.
 
204
 
 
205
    It is possible for a `WorkingTree` to have a filename which is
 
206
    not listed in the Inventory and vice versa.
 
207
    """
 
208
 
 
209
    def __init__(self, basedir='.',
 
210
                 branch=DEPRECATED_PARAMETER,
 
211
                 _inventory=None,
 
212
                 _control_files=None,
 
213
                 _internal=False,
 
214
                 _format=None,
 
215
                 _bzrdir=None):
 
216
        """Construct a WorkingTree for basedir.
 
217
 
 
218
        If the branch is not supplied, it is opened automatically.
 
219
        If the branch is supplied, it must be the branch for this basedir.
 
220
        (branch.base is not cross checked, because for remote branches that
 
221
        would be meaningless).
 
222
        """
 
223
        self._format = _format
 
224
        self.bzrdir = _bzrdir
 
225
        if not _internal:
 
226
            # not created via open etc.
 
227
            warnings.warn("WorkingTree() is deprecated as of bzr version 0.8. "
 
228
                 "Please use bzrdir.open_workingtree or WorkingTree.open().",
 
229
                 DeprecationWarning,
 
230
                 stacklevel=2)
 
231
            wt = WorkingTree.open(basedir)
 
232
            self._branch = wt.branch
 
233
            self.basedir = wt.basedir
 
234
            self._control_files = wt._control_files
 
235
            self._hashcache = wt._hashcache
 
236
            self._set_inventory(wt._inventory, dirty=False)
 
237
            self._format = wt._format
 
238
            self.bzrdir = wt.bzrdir
 
239
        assert isinstance(basedir, basestring), \
 
240
            "base directory %r is not a string" % basedir
 
241
        basedir = safe_unicode(basedir)
 
242
        mutter("opening working tree %r", basedir)
 
243
        if deprecated_passed(branch):
 
244
            if not _internal:
 
245
                warnings.warn("WorkingTree(..., branch=XXX) is deprecated as of bzr 0.8."
 
246
                     " Please use bzrdir.open_workingtree() or"
 
247
                     " WorkingTree.open().",
 
248
                     DeprecationWarning,
 
249
                     stacklevel=2
 
250
                     )
 
251
            self._branch = branch
 
252
        else:
 
253
            self._branch = self.bzrdir.open_branch()
 
254
        self.basedir = realpath(basedir)
 
255
        # if branch is at our basedir and is a format 6 or less
 
256
        if isinstance(self._format, WorkingTreeFormat2):
 
257
            # share control object
 
258
            self._control_files = self.branch.control_files
 
259
        else:
 
260
            # assume all other formats have their own control files.
 
261
            assert isinstance(_control_files, LockableFiles), \
 
262
                    "_control_files must be a LockableFiles, not %r" \
 
263
                    % _control_files
 
264
            self._control_files = _control_files
 
265
        # update the whole cache up front and write to disk if anything changed;
 
266
        # in the future we might want to do this more selectively
 
267
        # two possible ways offer themselves : in self._unlock, write the cache
 
268
        # if needed, or, when the cache sees a change, append it to the hash
 
269
        # cache file, and have the parser take the most recent entry for a
 
270
        # given path only.
 
271
        cache_filename = self.bzrdir.get_workingtree_transport(None).local_abspath('stat-cache')
 
272
        self._hashcache = hashcache.HashCache(basedir, cache_filename,
 
273
                                              self._control_files._file_mode)
 
274
        hc = self._hashcache
 
275
        hc.read()
 
276
        # is this scan needed ? it makes things kinda slow.
 
277
        #hc.scan()
 
278
 
 
279
        if hc.needs_write:
 
280
            mutter("write hc")
 
281
            hc.write()
 
282
 
 
283
        if _inventory is None:
 
284
            self._inventory_is_modified = False
 
285
            self.read_working_inventory()
 
286
        else:
 
287
            # the caller of __init__ has provided an inventory,
 
288
            # we assume they know what they are doing - as its only
 
289
            # the Format factory and creation methods that are
 
290
            # permitted to do this.
 
291
            self._set_inventory(_inventory, dirty=False)
 
292
 
 
293
    branch = property(
 
294
        fget=lambda self: self._branch,
 
295
        doc="""The branch this WorkingTree is connected to.
 
296
 
 
297
            This cannot be set - it is reflective of the actual disk structure
 
298
            the working tree has been constructed from.
 
299
            """)
 
300
 
 
301
    def break_lock(self):
 
302
        """Break a lock if one is present from another instance.
 
303
 
 
304
        Uses the ui factory to ask for confirmation if the lock may be from
 
305
        an active process.
 
306
 
 
307
        This will probe the repository for its lock as well.
 
308
        """
 
309
        self._control_files.break_lock()
 
310
        self.branch.break_lock()
 
311
 
 
312
    def requires_rich_root(self):
 
313
        return self._format.requires_rich_root
 
314
 
 
315
    def _set_inventory(self, inv, dirty):
 
316
        """Set the internal cached inventory.
 
317
 
 
318
        :param inv: The inventory to set.
 
319
        :param dirty: A boolean indicating whether the inventory is the same
 
320
            logical inventory as whats on disk. If True the inventory is not
 
321
            the same and should be written to disk or data will be lost, if
 
322
            False then the inventory is the same as that on disk and any
 
323
            serialisation would be unneeded overhead.
 
324
        """
 
325
        assert inv.root is not None
 
326
        self._inventory = inv
 
327
        self._inventory_is_modified = dirty
 
328
 
 
329
    @staticmethod
 
330
    def open(path=None, _unsupported=False):
 
331
        """Open an existing working tree at path.
 
332
 
 
333
        """
 
334
        if path is None:
 
335
            path = os.path.getcwdu()
 
336
        control = bzrdir.BzrDir.open(path, _unsupported)
 
337
        return control.open_workingtree(_unsupported)
 
338
        
 
339
    @staticmethod
 
340
    def open_containing(path=None):
 
341
        """Open an existing working tree which has its root about path.
 
342
        
 
343
        This probes for a working tree at path and searches upwards from there.
 
344
 
 
345
        Basically we keep looking up until we find the control directory or
 
346
        run into /.  If there isn't one, raises NotBranchError.
 
347
        TODO: give this a new exception.
 
348
        If there is one, it is returned, along with the unused portion of path.
 
349
 
 
350
        :return: The WorkingTree that contains 'path', and the rest of path
 
351
        """
 
352
        if path is None:
 
353
            path = osutils.getcwd()
 
354
        control, relpath = bzrdir.BzrDir.open_containing(path)
 
355
 
 
356
        return control.open_workingtree(), relpath
 
357
 
 
358
    @staticmethod
 
359
    def open_downlevel(path=None):
 
360
        """Open an unsupported working tree.
 
361
 
 
362
        Only intended for advanced situations like upgrading part of a bzrdir.
 
363
        """
 
364
        return WorkingTree.open(path, _unsupported=True)
 
365
 
 
366
    def __iter__(self):
 
367
        """Iterate through file_ids for this tree.
 
368
 
 
369
        file_ids are in a WorkingTree if they are in the working inventory
 
370
        and the working file exists.
 
371
        """
 
372
        inv = self._inventory
 
373
        for path, ie in inv.iter_entries():
 
374
            if osutils.lexists(self.abspath(path)):
 
375
                yield ie.file_id
 
376
 
 
377
    def __repr__(self):
 
378
        return "<%s of %s>" % (self.__class__.__name__,
 
379
                               getattr(self, 'basedir', None))
 
380
 
 
381
    def abspath(self, filename):
 
382
        return pathjoin(self.basedir, filename)
 
383
    
 
384
    def basis_tree(self):
 
385
        """Return RevisionTree for the current last revision.
 
386
        
 
387
        If the left most parent is a ghost then the returned tree will be an
 
388
        empty tree - one obtained by calling repository.revision_tree(None).
 
389
        """
 
390
        try:
 
391
            revision_id = self.get_parent_ids()[0]
 
392
        except IndexError:
 
393
            # no parents, return an empty revision tree.
 
394
            # in the future this should return the tree for
 
395
            # 'empty:' - the implicit root empty tree.
 
396
            return self.branch.repository.revision_tree(None)
 
397
        else:
 
398
            try:
 
399
                xml = self.read_basis_inventory()
 
400
                inv = xml6.serializer_v6.read_inventory_from_string(xml)
 
401
                if inv is not None and inv.revision_id == revision_id:
 
402
                    return bzrlib.revisiontree.RevisionTree(
 
403
                        self.branch.repository, inv, revision_id)
 
404
            except (NoSuchFile, errors.BadInventoryFormat):
 
405
                pass
 
406
        # No cached copy available, retrieve from the repository.
 
407
        # FIXME? RBC 20060403 should we cache the inventory locally
 
408
        # at this point ?
 
409
        try:
 
410
            return self.branch.repository.revision_tree(revision_id)
 
411
        except errors.RevisionNotPresent:
 
412
            # the basis tree *may* be a ghost or a low level error may have
 
413
            # occured. If the revision is present, its a problem, if its not
 
414
            # its a ghost.
 
415
            if self.branch.repository.has_revision(revision_id):
 
416
                raise
 
417
            # the basis tree is a ghost so return an empty tree.
 
418
            return self.branch.repository.revision_tree(None)
 
419
 
 
420
    @staticmethod
 
421
    @deprecated_method(zero_eight)
 
422
    def create(branch, directory):
 
423
        """Create a workingtree for branch at directory.
 
424
 
 
425
        If existing_directory already exists it must have a .bzr directory.
 
426
        If it does not exist, it will be created.
 
427
 
 
428
        This returns a new WorkingTree object for the new checkout.
 
429
 
 
430
        TODO FIXME RBC 20060124 when we have checkout formats in place this
 
431
        should accept an optional revisionid to checkout [and reject this if
 
432
        checking out into the same dir as a pre-checkout-aware branch format.]
 
433
 
 
434
        XXX: When BzrDir is present, these should be created through that 
 
435
        interface instead.
 
436
        """
 
437
        warnings.warn('delete WorkingTree.create', stacklevel=3)
 
438
        transport = get_transport(directory)
 
439
        if branch.bzrdir.root_transport.base == transport.base:
 
440
            # same dir 
 
441
            return branch.bzrdir.create_workingtree()
 
442
        # different directory, 
 
443
        # create a branch reference
 
444
        # and now a working tree.
 
445
        raise NotImplementedError
 
446
 
 
447
    @staticmethod
 
448
    @deprecated_method(zero_eight)
 
449
    def create_standalone(directory):
 
450
        """Create a checkout and a branch and a repo at directory.
 
451
 
 
452
        Directory must exist and be empty.
 
453
 
 
454
        please use BzrDir.create_standalone_workingtree
 
455
        """
 
456
        return bzrdir.BzrDir.create_standalone_workingtree(directory)
 
457
 
 
458
    def relpath(self, path):
 
459
        """Return the local path portion from a given path.
 
460
        
 
461
        The path may be absolute or relative. If its a relative path it is 
 
462
        interpreted relative to the python current working directory.
 
463
        """
 
464
        return osutils.relpath(self.basedir, path)
 
465
 
 
466
    def has_filename(self, filename):
 
467
        return osutils.lexists(self.abspath(filename))
 
468
 
 
469
    def get_file(self, file_id):
 
470
        return self.get_file_byname(self.id2path(file_id))
 
471
 
 
472
    def get_file_text(self, file_id):
 
473
        return self.get_file(file_id).read()
 
474
 
 
475
    def get_file_byname(self, filename):
 
476
        return file(self.abspath(filename), 'rb')
 
477
 
 
478
    def annotate_iter(self, file_id):
 
479
        """See Tree.annotate_iter
 
480
 
 
481
        This implementation will use the basis tree implementation if possible.
 
482
        Lines not in the basis are attributed to CURRENT_REVISION
 
483
 
 
484
        If there are pending merges, lines added by those merges will be
 
485
        incorrectly attributed to CURRENT_REVISION (but after committing, the
 
486
        attribution will be correct).
 
487
        """
 
488
        basis = self.basis_tree()
 
489
        changes = self._iter_changes(basis, True, [file_id]).next()
 
490
        changed_content, kind = changes[2], changes[6]
 
491
        if not changed_content:
 
492
            return basis.annotate_iter(file_id)
 
493
        if kind[1] is None:
 
494
            return None
 
495
        import annotate
 
496
        if kind[0] != 'file':
 
497
            old_lines = []
 
498
        else:
 
499
            old_lines = list(basis.annotate_iter(file_id))
 
500
        old = [old_lines]
 
501
        for tree in self.branch.repository.revision_trees(
 
502
            self.get_parent_ids()[1:]):
 
503
            if file_id not in tree:
 
504
                continue
 
505
            old.append(list(tree.annotate_iter(file_id)))
 
506
        return annotate.reannotate(old, self.get_file(file_id).readlines(),
 
507
                                   CURRENT_REVISION)
 
508
 
 
509
    def get_parent_ids(self):
 
510
        """See Tree.get_parent_ids.
 
511
        
 
512
        This implementation reads the pending merges list and last_revision
 
513
        value and uses that to decide what the parents list should be.
 
514
        """
 
515
        last_rev = self._last_revision()
 
516
        if last_rev is None:
 
517
            parents = []
 
518
        else:
 
519
            parents = [last_rev]
 
520
        try:
 
521
            merges_file = self._control_files.get_utf8('pending-merges')
 
522
        except NoSuchFile:
 
523
            pass
 
524
        else:
 
525
            for l in merges_file.readlines():
 
526
                parents.append(l.rstrip('\n'))
 
527
        return parents
 
528
 
 
529
    @needs_read_lock
 
530
    def get_root_id(self):
 
531
        """Return the id of this trees root"""
 
532
        return self._inventory.root.file_id
 
533
        
 
534
    def _get_store_filename(self, file_id):
 
535
        ## XXX: badly named; this is not in the store at all
 
536
        return self.abspath(self.id2path(file_id))
 
537
 
 
538
    @needs_read_lock
 
539
    def clone(self, to_bzrdir, revision_id=None, basis=None):
 
540
        """Duplicate this working tree into to_bzr, including all state.
 
541
        
 
542
        Specifically modified files are kept as modified, but
 
543
        ignored and unknown files are discarded.
 
544
 
 
545
        If you want to make a new line of development, see bzrdir.sprout()
 
546
 
 
547
        revision
 
548
            If not None, the cloned tree will have its last revision set to 
 
549
            revision, and and difference between the source trees last revision
 
550
            and this one merged in.
 
551
 
 
552
        basis
 
553
            If not None, a closer copy of a tree which may have some files in
 
554
            common, and which file content should be preferentially copied from.
 
555
        """
 
556
        # assumes the target bzr dir format is compatible.
 
557
        result = self._format.initialize(to_bzrdir)
 
558
        self.copy_content_into(result, revision_id)
 
559
        return result
 
560
 
 
561
    @needs_read_lock
 
562
    def copy_content_into(self, tree, revision_id=None):
 
563
        """Copy the current content and user files of this tree into tree."""
 
564
        tree.set_root_id(self.get_root_id())
 
565
        if revision_id is None:
 
566
            merge.transform_tree(tree, self)
 
567
        else:
 
568
            # TODO now merge from tree.last_revision to revision (to preserve
 
569
            # user local changes)
 
570
            merge.transform_tree(tree, self)
 
571
            tree.set_parent_ids([revision_id])
 
572
 
 
573
    def id2abspath(self, file_id):
 
574
        return self.abspath(self.id2path(file_id))
 
575
 
 
576
    def has_id(self, file_id):
 
577
        # files that have been deleted are excluded
 
578
        inv = self._inventory
 
579
        if not inv.has_id(file_id):
 
580
            return False
 
581
        path = inv.id2path(file_id)
 
582
        return osutils.lexists(self.abspath(path))
 
583
 
 
584
    def has_or_had_id(self, file_id):
 
585
        if file_id == self.inventory.root.file_id:
 
586
            return True
 
587
        return self.inventory.has_id(file_id)
 
588
 
 
589
    __contains__ = has_id
 
590
 
 
591
    def get_file_size(self, file_id):
 
592
        return os.path.getsize(self.id2abspath(file_id))
 
593
 
 
594
    @needs_read_lock
 
595
    def get_file_sha1(self, file_id, path=None, stat_value=None):
 
596
        if not path:
 
597
            path = self._inventory.id2path(file_id)
 
598
        return self._hashcache.get_sha1(path, stat_value)
 
599
 
 
600
    def get_file_mtime(self, file_id, path=None):
 
601
        if not path:
 
602
            path = self._inventory.id2path(file_id)
 
603
        return os.lstat(self.abspath(path)).st_mtime
 
604
 
 
605
    if not supports_executable():
 
606
        def is_executable(self, file_id, path=None):
 
607
            return self._inventory[file_id].executable
 
608
    else:
 
609
        def is_executable(self, file_id, path=None):
 
610
            if not path:
 
611
                path = self._inventory.id2path(file_id)
 
612
            mode = os.lstat(self.abspath(path)).st_mode
 
613
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
614
 
 
615
    @needs_write_lock
 
616
    def _add(self, files, ids, kinds):
 
617
        """See MutableTree._add."""
 
618
        # TODO: Re-adding a file that is removed in the working copy
 
619
        # should probably put it back with the previous ID.
 
620
        # the read and write working inventory should not occur in this 
 
621
        # function - they should be part of lock_write and unlock.
 
622
        inv = self.read_working_inventory()
 
623
        for f, file_id, kind in zip(files, ids, kinds):
 
624
            assert kind is not None
 
625
            if file_id is None:
 
626
                inv.add_path(f, kind=kind)
 
627
            else:
 
628
                inv.add_path(f, kind=kind, file_id=file_id)
 
629
        self._write_inventory(inv)
 
630
 
 
631
    def add_reference(self, sub_tree):
 
632
        """Add a TreeReference to the tree, pointing at sub_tree"""
 
633
        raise UnsupportedOperation(self.add_reference, self)
 
634
 
 
635
    @needs_tree_write_lock
 
636
    def _gather_kinds(self, files, kinds):
 
637
        """See MutableTree._gather_kinds."""
 
638
        for pos, f in enumerate(files):
 
639
            if kinds[pos] is None:
 
640
                fullpath = normpath(self.abspath(f))
 
641
                try:
 
642
                    kinds[pos] = file_kind(fullpath)
 
643
                except OSError, e:
 
644
                    if e.errno == errno.ENOENT:
 
645
                        raise NoSuchFile(fullpath)
 
646
 
 
647
    @needs_write_lock
 
648
    def add_parent_tree_id(self, revision_id, allow_leftmost_as_ghost=False):
 
649
        """Add revision_id as a parent.
 
650
 
 
651
        This is equivalent to retrieving the current list of parent ids
 
652
        and setting the list to its value plus revision_id.
 
653
 
 
654
        :param revision_id: The revision id to add to the parent list. It may
 
655
        be a ghost revision as long as its not the first parent to be added,
 
656
        or the allow_leftmost_as_ghost parameter is set True.
 
657
        :param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
 
658
        """
 
659
        parents = self.get_parent_ids() + [revision_id]
 
660
        self.set_parent_ids(parents,
 
661
            allow_leftmost_as_ghost=len(parents) > 1 or allow_leftmost_as_ghost)
 
662
 
 
663
    @needs_tree_write_lock
 
664
    def add_parent_tree(self, parent_tuple, allow_leftmost_as_ghost=False):
 
665
        """Add revision_id, tree tuple as a parent.
 
666
 
 
667
        This is equivalent to retrieving the current list of parent trees
 
668
        and setting the list to its value plus parent_tuple. See also
 
669
        add_parent_tree_id - if you only have a parent id available it will be
 
670
        simpler to use that api. If you have the parent already available, using
 
671
        this api is preferred.
 
672
 
 
673
        :param parent_tuple: The (revision id, tree) to add to the parent list.
 
674
            If the revision_id is a ghost, pass None for the tree.
 
675
        :param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
 
676
        """
 
677
        parent_ids = self.get_parent_ids() + [parent_tuple[0]]
 
678
        if len(parent_ids) > 1:
 
679
            # the leftmost may have already been a ghost, preserve that if it
 
680
            # was.
 
681
            allow_leftmost_as_ghost = True
 
682
        self.set_parent_ids(parent_ids,
 
683
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
 
684
 
 
685
    @needs_tree_write_lock
 
686
    def add_pending_merge(self, *revision_ids):
 
687
        # TODO: Perhaps should check at this point that the
 
688
        # history of the revision is actually present?
 
689
        parents = self.get_parent_ids()
 
690
        updated = False
 
691
        for rev_id in revision_ids:
 
692
            if rev_id in parents:
 
693
                continue
 
694
            parents.append(rev_id)
 
695
            updated = True
 
696
        if updated:
 
697
            self.set_parent_ids(parents, allow_leftmost_as_ghost=True)
 
698
 
 
699
    @deprecated_method(zero_eleven)
 
700
    @needs_read_lock
 
701
    def pending_merges(self):
 
702
        """Return a list of pending merges.
 
703
 
 
704
        These are revisions that have been merged into the working
 
705
        directory but not yet committed.
 
706
 
 
707
        As of 0.11 this is deprecated. Please see WorkingTree.get_parent_ids()
 
708
        instead - which is available on all tree objects.
 
709
        """
 
710
        return self.get_parent_ids()[1:]
 
711
 
 
712
    def _check_parents_for_ghosts(self, revision_ids, allow_leftmost_as_ghost):
 
713
        """Common ghost checking functionality from set_parent_*.
 
714
 
 
715
        This checks that the left hand-parent exists if there are any
 
716
        revisions present.
 
717
        """
 
718
        if len(revision_ids) > 0:
 
719
            leftmost_id = revision_ids[0]
 
720
            if (not allow_leftmost_as_ghost and not
 
721
                self.branch.repository.has_revision(leftmost_id)):
 
722
                raise errors.GhostRevisionUnusableHere(leftmost_id)
 
723
 
 
724
    def _set_merges_from_parent_ids(self, parent_ids):
 
725
        merges = parent_ids[1:]
 
726
        self._control_files.put_utf8('pending-merges', '\n'.join(merges))
 
727
 
 
728
    @needs_tree_write_lock
 
729
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
 
730
        """Set the parent ids to revision_ids.
 
731
        
 
732
        See also set_parent_trees. This api will try to retrieve the tree data
 
733
        for each element of revision_ids from the trees repository. If you have
 
734
        tree data already available, it is more efficient to use
 
735
        set_parent_trees rather than set_parent_ids. set_parent_ids is however
 
736
        an easier API to use.
 
737
 
 
738
        :param revision_ids: The revision_ids to set as the parent ids of this
 
739
            working tree. Any of these may be ghosts.
 
740
        """
 
741
        self._check_parents_for_ghosts(revision_ids,
 
742
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
 
743
 
 
744
        if len(revision_ids) > 0:
 
745
            self.set_last_revision(revision_ids[0])
 
746
        else:
 
747
            self.set_last_revision(None)
 
748
 
 
749
        self._set_merges_from_parent_ids(revision_ids)
 
750
 
 
751
    @needs_tree_write_lock
 
752
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
 
753
        """See MutableTree.set_parent_trees."""
 
754
        parent_ids = [rev for (rev, tree) in parents_list]
 
755
 
 
756
        self._check_parents_for_ghosts(parent_ids,
 
757
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
 
758
 
 
759
        if len(parent_ids) == 0:
 
760
            leftmost_parent_id = None
 
761
            leftmost_parent_tree = None
 
762
        else:
 
763
            leftmost_parent_id, leftmost_parent_tree = parents_list[0]
 
764
 
 
765
        if self._change_last_revision(leftmost_parent_id):
 
766
            if leftmost_parent_tree is None:
 
767
                # If we don't have a tree, fall back to reading the
 
768
                # parent tree from the repository.
 
769
                self._cache_basis_inventory(leftmost_parent_id)
 
770
            else:
 
771
                inv = leftmost_parent_tree.inventory
 
772
                xml = self._create_basis_xml_from_inventory(
 
773
                                        leftmost_parent_id, inv)
 
774
                self._write_basis_inventory(xml)
 
775
        self._set_merges_from_parent_ids(parent_ids)
 
776
 
 
777
    @needs_tree_write_lock
 
778
    def set_pending_merges(self, rev_list):
 
779
        parents = self.get_parent_ids()
 
780
        leftmost = parents[:1]
 
781
        new_parents = leftmost + rev_list
 
782
        self.set_parent_ids(new_parents)
 
783
 
 
784
    @needs_tree_write_lock
 
785
    def set_merge_modified(self, modified_hashes):
 
786
        def iter_stanzas():
 
787
            for file_id, hash in modified_hashes.iteritems():
 
788
                yield Stanza(file_id=file_id, hash=hash)
 
789
        self._put_rio('merge-hashes', iter_stanzas(), MERGE_MODIFIED_HEADER_1)
 
790
 
 
791
    @needs_tree_write_lock
 
792
    def _put_rio(self, filename, stanzas, header):
 
793
        my_file = rio_file(stanzas, header)
 
794
        self._control_files.put(filename, my_file)
 
795
 
 
796
    @needs_write_lock # because merge pulls data into the branch.
 
797
    def merge_from_branch(self, branch, to_revision=None):
 
798
        """Merge from a branch into this working tree.
 
799
 
 
800
        :param branch: The branch to merge from.
 
801
        :param to_revision: If non-None, the merge will merge to to_revision, but 
 
802
            not beyond it. to_revision does not need to be in the history of
 
803
            the branch when it is supplied. If None, to_revision defaults to
 
804
            branch.last_revision().
 
805
        """
 
806
        from bzrlib.merge import Merger, Merge3Merger
 
807
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
808
        try:
 
809
            merger = Merger(self.branch, this_tree=self, pb=pb)
 
810
            merger.pp = ProgressPhase("Merge phase", 5, pb)
 
811
            merger.pp.next_phase()
 
812
            # check that there are no
 
813
            # local alterations
 
814
            merger.check_basis(check_clean=True, require_commits=False)
 
815
            if to_revision is None:
 
816
                to_revision = branch.last_revision()
 
817
            merger.other_rev_id = to_revision
 
818
            if merger.other_rev_id is None:
 
819
                raise error.NoCommits(branch)
 
820
            self.branch.fetch(branch, last_revision=merger.other_rev_id)
 
821
            merger.other_basis = merger.other_rev_id
 
822
            merger.other_tree = self.branch.repository.revision_tree(
 
823
                merger.other_rev_id)
 
824
            merger.pp.next_phase()
 
825
            merger.find_base()
 
826
            if merger.base_rev_id == merger.other_rev_id:
 
827
                raise errors.PointlessMerge
 
828
            merger.backup_files = False
 
829
            merger.merge_type = Merge3Merger
 
830
            merger.set_interesting_files(None)
 
831
            merger.show_base = False
 
832
            merger.reprocess = False
 
833
            conflicts = merger.do_merge()
 
834
            merger.set_pending()
 
835
        finally:
 
836
            pb.finished()
 
837
        return conflicts
 
838
 
 
839
    @needs_write_lock
 
840
    def subsume(self, other_tree):
 
841
        def add_children(inventory, entry):
 
842
            for child_entry in entry.children.values():
 
843
                inventory._byid[child_entry.file_id] = child_entry
 
844
                if child_entry.kind == 'directory':
 
845
                    add_children(inventory, child_entry)
 
846
        if other_tree.get_root_id() == self.get_root_id():
 
847
            raise errors.BadSubsumeSource(self, other_tree, 
 
848
                                          'Trees have the same root')
 
849
        try:
 
850
            other_tree_path = self.relpath(other_tree.basedir)
 
851
        except errors.PathNotChild:
 
852
            raise errors.BadSubsumeSource(self, other_tree, 
 
853
                'Tree is not contained by the other')
 
854
        new_root_parent = self.path2id(osutils.dirname(other_tree_path))
 
855
        if new_root_parent is None:
 
856
            raise errors.BadSubsumeSource(self, other_tree, 
 
857
                'Parent directory is not versioned.')
 
858
        # We need to ensure that the result of a fetch will have a
 
859
        # versionedfile for the other_tree root, and only fetching into
 
860
        # RepositoryKnit2 guarantees that.
 
861
        if not self.branch.repository.supports_rich_root():
 
862
            raise errors.SubsumeTargetNeedsUpgrade(other_tree)
 
863
        other_tree.lock_tree_write()
 
864
        try:
 
865
            for parent_id in other_tree.get_parent_ids():
 
866
                self.branch.fetch(other_tree.branch, parent_id)
 
867
                self.add_parent_tree_id(parent_id)
 
868
            other_root = other_tree.inventory.root
 
869
            other_root.parent_id = new_root_parent
 
870
            other_root.name = osutils.basename(other_tree_path)
 
871
            self.inventory.add(other_root)
 
872
            add_children(self.inventory, other_root)
 
873
            self._write_inventory(self.inventory)
 
874
        finally:
 
875
            other_tree.unlock()
 
876
        other_tree.bzrdir.destroy_workingtree_metadata()
 
877
 
 
878
    @needs_tree_write_lock
 
879
    def extract(self, file_id, format=None):
 
880
        """Extract a subtree from this tree.
 
881
        
 
882
        A new branch will be created, relative to the path for this tree.
 
883
        """
 
884
        def mkdirs(path):
 
885
            segments = osutils.splitpath(path)
 
886
            transport = self.branch.bzrdir.root_transport
 
887
            for name in segments:
 
888
                transport = transport.clone(name)
 
889
                try:
 
890
                    transport.mkdir('.')
 
891
                except errors.FileExists:
 
892
                    pass
 
893
            return transport
 
894
            
 
895
        sub_path = self.id2path(file_id)
 
896
        branch_transport = mkdirs(sub_path)
 
897
        if format is None:
 
898
            format = bzrdir.format_registry.make_bzrdir('experimental-knit2')
 
899
        try:
 
900
            branch_transport.mkdir('.')
 
901
        except errors.FileExists:
 
902
            pass
 
903
        branch_bzrdir = format.initialize_on_transport(branch_transport)
 
904
        try:
 
905
            repo = branch_bzrdir.find_repository()
 
906
        except errors.NoRepositoryPresent:
 
907
            repo = branch_bzrdir.create_repository()
 
908
            assert repo.supports_rich_root()
 
909
        else:
 
910
            if not repo.supports_rich_root():
 
911
                raise errors.RootNotRich()
 
912
        new_branch = branch_bzrdir.create_branch()
 
913
        new_branch.pull(self.branch)
 
914
        for parent_id in self.get_parent_ids():
 
915
            new_branch.fetch(self.branch, parent_id)
 
916
        tree_transport = self.bzrdir.root_transport.clone(sub_path)
 
917
        if tree_transport.base != branch_transport.base:
 
918
            tree_bzrdir = format.initialize_on_transport(tree_transport)
 
919
            branch.BranchReferenceFormat().initialize(tree_bzrdir, new_branch)
 
920
        else:
 
921
            tree_bzrdir = branch_bzrdir
 
922
        wt = tree_bzrdir.create_workingtree(NULL_REVISION)
 
923
        wt.set_parent_ids(self.get_parent_ids())
 
924
        my_inv = self.inventory
 
925
        child_inv = Inventory(root_id=None)
 
926
        new_root = my_inv[file_id]
 
927
        my_inv.remove_recursive_id(file_id)
 
928
        new_root.parent_id = None
 
929
        child_inv.add(new_root)
 
930
        self._write_inventory(my_inv)
 
931
        wt._write_inventory(child_inv)
 
932
        return wt
 
933
 
 
934
    @needs_read_lock
 
935
    def merge_modified(self):
 
936
        try:
 
937
            hashfile = self._control_files.get('merge-hashes')
 
938
        except NoSuchFile:
 
939
            return {}
 
940
        merge_hashes = {}
 
941
        try:
 
942
            if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
 
943
                raise MergeModifiedFormatError()
 
944
        except StopIteration:
 
945
            raise MergeModifiedFormatError()
 
946
        for s in RioReader(hashfile):
 
947
            file_id = s.get("file_id")
 
948
            if file_id not in self.inventory:
 
949
                continue
 
950
            hash = s.get("hash")
 
951
            if hash == self.get_file_sha1(file_id):
 
952
                merge_hashes[file_id] = hash
 
953
        return merge_hashes
 
954
 
 
955
    @needs_write_lock
 
956
    def mkdir(self, path, file_id=None):
 
957
        """See MutableTree.mkdir()."""
 
958
        if file_id is None:
 
959
            file_id = generate_ids.gen_file_id(os.path.basename(path))
 
960
        os.mkdir(self.abspath(path))
 
961
        self.add(path, file_id, 'directory')
 
962
        return file_id
 
963
 
 
964
    def get_symlink_target(self, file_id):
 
965
        return os.readlink(self.id2abspath(file_id))
 
966
 
 
967
    def file_class(self, filename):
 
968
        if self.path2id(filename):
 
969
            return 'V'
 
970
        elif self.is_ignored(filename):
 
971
            return 'I'
 
972
        else:
 
973
            return '?'
 
974
 
 
975
    def flush(self):
 
976
        """Write the in memory inventory to disk."""
 
977
        # TODO: Maybe this should only write on dirty ?
 
978
        if self._control_files._lock_mode != 'w':
 
979
            raise errors.NotWriteLocked(self)
 
980
        sio = StringIO()
 
981
        self._serialize(self._inventory, sio)
 
982
        sio.seek(0)
 
983
        self._control_files.put('inventory', sio)
 
984
        self._inventory_is_modified = False
 
985
 
 
986
    def _serialize(self, inventory, out_file):
 
987
        xml5.serializer_v5.write_inventory(self._inventory, out_file)
 
988
 
 
989
    def _deserialize(selt, in_file):
 
990
        return xml5.serializer_v5.read_inventory(in_file)
 
991
 
 
992
    def list_files(self, include_root=False):
 
993
        """Recursively list all files as (path, class, kind, id, entry).
 
994
 
 
995
        Lists, but does not descend into unversioned directories.
 
996
 
 
997
        This does not include files that have been deleted in this
 
998
        tree.
 
999
 
 
1000
        Skips the control directory.
 
1001
        """
 
1002
        inv = self._inventory
 
1003
        if include_root is True:
 
1004
            yield ('', 'V', 'directory', inv.root.file_id, inv.root)
 
1005
        # Convert these into local objects to save lookup times
 
1006
        pathjoin = osutils.pathjoin
 
1007
        file_kind = osutils.file_kind
 
1008
 
 
1009
        # transport.base ends in a slash, we want the piece
 
1010
        # between the last two slashes
 
1011
        transport_base_dir = self.bzrdir.transport.base.rsplit('/', 2)[1]
 
1012
 
 
1013
        fk_entries = {'directory':TreeDirectory, 'file':TreeFile, 'symlink':TreeLink}
 
1014
 
 
1015
        # directory file_id, relative path, absolute path, reverse sorted children
 
1016
        children = os.listdir(self.basedir)
 
1017
        children.sort()
 
1018
        # jam 20060527 The kernel sized tree seems equivalent whether we 
 
1019
        # use a deque and popleft to keep them sorted, or if we use a plain
 
1020
        # list and just reverse() them.
 
1021
        children = collections.deque(children)
 
1022
        stack = [(inv.root.file_id, u'', self.basedir, children)]
 
1023
        while stack:
 
1024
            from_dir_id, from_dir_relpath, from_dir_abspath, children = stack[-1]
 
1025
 
 
1026
            while children:
 
1027
                f = children.popleft()
 
1028
                ## TODO: If we find a subdirectory with its own .bzr
 
1029
                ## directory, then that is a separate tree and we
 
1030
                ## should exclude it.
 
1031
 
 
1032
                # the bzrdir for this tree
 
1033
                if transport_base_dir == f:
 
1034
                    continue
 
1035
 
 
1036
                # we know that from_dir_relpath and from_dir_abspath never end in a slash
 
1037
                # and 'f' doesn't begin with one, we can do a string op, rather
 
1038
                # than the checks of pathjoin(), all relative paths will have an extra slash
 
1039
                # at the beginning
 
1040
                fp = from_dir_relpath + '/' + f
 
1041
 
 
1042
                # absolute path
 
1043
                fap = from_dir_abspath + '/' + f
 
1044
                
 
1045
                f_ie = inv.get_child(from_dir_id, f)
 
1046
                if f_ie:
 
1047
                    c = 'V'
 
1048
                elif self.is_ignored(fp[1:]):
 
1049
                    c = 'I'
 
1050
                else:
 
1051
                    # we may not have found this file, because of a unicode issue
 
1052
                    f_norm, can_access = osutils.normalized_filename(f)
 
1053
                    if f == f_norm or not can_access:
 
1054
                        # No change, so treat this file normally
 
1055
                        c = '?'
 
1056
                    else:
 
1057
                        # this file can be accessed by a normalized path
 
1058
                        # check again if it is versioned
 
1059
                        # these lines are repeated here for performance
 
1060
                        f = f_norm
 
1061
                        fp = from_dir_relpath + '/' + f
 
1062
                        fap = from_dir_abspath + '/' + f
 
1063
                        f_ie = inv.get_child(from_dir_id, f)
 
1064
                        if f_ie:
 
1065
                            c = 'V'
 
1066
                        elif self.is_ignored(fp[1:]):
 
1067
                            c = 'I'
 
1068
                        else:
 
1069
                            c = '?'
 
1070
 
 
1071
                fk = file_kind(fap)
 
1072
 
 
1073
                if f_ie:
 
1074
                    if f_ie.kind != fk:
 
1075
                        raise BzrCheckError("file %r entered as kind %r id %r, "
 
1076
                                            "now of kind %r"
 
1077
                                            % (fap, f_ie.kind, f_ie.file_id, fk))
 
1078
 
 
1079
                # make a last minute entry
 
1080
                if f_ie:
 
1081
                    yield fp[1:], c, fk, f_ie.file_id, f_ie
 
1082
                else:
 
1083
                    try:
 
1084
                        yield fp[1:], c, fk, None, fk_entries[fk]()
 
1085
                    except KeyError:
 
1086
                        yield fp[1:], c, fk, None, TreeEntry()
 
1087
                    continue
 
1088
                
 
1089
                if fk != 'directory':
 
1090
                    continue
 
1091
 
 
1092
                # But do this child first
 
1093
                new_children = os.listdir(fap)
 
1094
                new_children.sort()
 
1095
                new_children = collections.deque(new_children)
 
1096
                stack.append((f_ie.file_id, fp, fap, new_children))
 
1097
                # Break out of inner loop, so that we start outer loop with child
 
1098
                break
 
1099
            else:
 
1100
                # if we finished all children, pop it off the stack
 
1101
                stack.pop()
 
1102
 
 
1103
    @needs_tree_write_lock
 
1104
    def move(self, from_paths, to_name):
 
1105
        """Rename files.
 
1106
 
 
1107
        to_name must exist in the inventory.
 
1108
 
 
1109
        If to_name exists and is a directory, the files are moved into
 
1110
        it, keeping their old names.  
 
1111
 
 
1112
        Note that to_name is only the last component of the new name;
 
1113
        this doesn't change the directory.
 
1114
 
 
1115
        This returns a list of (from_path, to_path) pairs for each
 
1116
        entry that is moved.
 
1117
        """
 
1118
        result = []
 
1119
        ## TODO: Option to move IDs only
 
1120
        assert not isinstance(from_paths, basestring)
 
1121
        inv = self.inventory
 
1122
        to_abs = self.abspath(to_name)
 
1123
        if not isdir(to_abs):
 
1124
            raise BzrError("destination %r is not a directory" % to_abs)
 
1125
        if not self.has_filename(to_name):
 
1126
            raise BzrError("destination %r not in working directory" % to_abs)
 
1127
        to_dir_id = inv.path2id(to_name)
 
1128
        if to_dir_id is None and to_name != '':
 
1129
            raise BzrError("destination %r is not a versioned directory" % to_name)
 
1130
        to_dir_ie = inv[to_dir_id]
 
1131
        if to_dir_ie.kind != 'directory':
 
1132
            raise BzrError("destination %r is not a directory" % to_abs)
 
1133
 
 
1134
        to_idpath = inv.get_idpath(to_dir_id)
 
1135
 
 
1136
        for f in from_paths:
 
1137
            if not self.has_filename(f):
 
1138
                raise BzrError("%r does not exist in working tree" % f)
 
1139
            f_id = inv.path2id(f)
 
1140
            if f_id is None:
 
1141
                raise BzrError("%r is not versioned" % f)
 
1142
            name_tail = splitpath(f)[-1]
 
1143
            dest_path = pathjoin(to_name, name_tail)
 
1144
            if self.has_filename(dest_path):
 
1145
                raise BzrError("destination %r already exists" % dest_path)
 
1146
            if f_id in to_idpath:
 
1147
                raise BzrError("can't move %r to a subdirectory of itself" % f)
 
1148
 
 
1149
        # OK, so there's a race here, it's possible that someone will
 
1150
        # create a file in this interval and then the rename might be
 
1151
        # left half-done.  But we should have caught most problems.
 
1152
        orig_inv = deepcopy(self.inventory)
 
1153
        original_modified = self._inventory_is_modified
 
1154
        try:
 
1155
            if len(from_paths):
 
1156
                self._inventory_is_modified = True
 
1157
            for f in from_paths:
 
1158
                name_tail = splitpath(f)[-1]
 
1159
                dest_path = pathjoin(to_name, name_tail)
 
1160
                result.append((f, dest_path))
 
1161
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
 
1162
                try:
 
1163
                    osutils.rename(self.abspath(f), self.abspath(dest_path))
 
1164
                except OSError, e:
 
1165
                    raise BzrError("failed to rename %r to %r: %s" %
 
1166
                                   (f, dest_path, e[1]))
 
1167
        except:
 
1168
            # restore the inventory on error
 
1169
            self._set_inventory(orig_inv, dirty=original_modified)
 
1170
            raise
 
1171
        self._write_inventory(inv)
 
1172
        return result
 
1173
 
 
1174
    @needs_tree_write_lock
 
1175
    def rename_one(self, from_rel, to_rel):
 
1176
        """Rename one file.
 
1177
 
 
1178
        This can change the directory or the filename or both.
 
1179
        """
 
1180
        inv = self.inventory
 
1181
        if not self.has_filename(from_rel):
 
1182
            raise BzrError("can't rename: old working file %r does not exist" % from_rel)
 
1183
        if self.has_filename(to_rel):
 
1184
            raise BzrError("can't rename: new working file %r already exists" % to_rel)
 
1185
 
 
1186
        file_id = inv.path2id(from_rel)
 
1187
        if file_id is None:
 
1188
            raise BzrError("can't rename: old name %r is not versioned" % from_rel)
 
1189
 
 
1190
        entry = inv[file_id]
 
1191
        from_parent = entry.parent_id
 
1192
        from_name = entry.name
 
1193
        
 
1194
        if inv.path2id(to_rel):
 
1195
            raise BzrError("can't rename: new name %r is already versioned" % to_rel)
 
1196
 
 
1197
        to_dir, to_tail = os.path.split(to_rel)
 
1198
        to_dir_id = inv.path2id(to_dir)
 
1199
        if to_dir_id is None and to_dir != '':
 
1200
            raise BzrError("can't determine destination directory id for %r" % to_dir)
 
1201
 
 
1202
        mutter("rename_one:")
 
1203
        mutter("  file_id    {%s}" % file_id)
 
1204
        mutter("  from_rel   %r" % from_rel)
 
1205
        mutter("  to_rel     %r" % to_rel)
 
1206
        mutter("  to_dir     %r" % to_dir)
 
1207
        mutter("  to_dir_id  {%s}" % to_dir_id)
 
1208
 
 
1209
        inv.rename(file_id, to_dir_id, to_tail)
 
1210
 
 
1211
        from_abs = self.abspath(from_rel)
 
1212
        to_abs = self.abspath(to_rel)
 
1213
        try:
 
1214
            osutils.rename(from_abs, to_abs)
 
1215
        except OSError, e:
 
1216
            inv.rename(file_id, from_parent, from_name)
 
1217
            raise BzrError("failed to rename %r to %r: %s"
 
1218
                    % (from_abs, to_abs, e[1]))
 
1219
        self._write_inventory(inv)
 
1220
 
 
1221
    @needs_read_lock
 
1222
    def unknowns(self):
 
1223
        """Return all unknown files.
 
1224
 
 
1225
        These are files in the working directory that are not versioned or
 
1226
        control files or ignored.
 
1227
        """
 
1228
        for subp in self.extras():
 
1229
            if not self.is_ignored(subp):
 
1230
                yield subp
 
1231
    
 
1232
    @needs_tree_write_lock
 
1233
    def unversion(self, file_ids):
 
1234
        """Remove the file ids in file_ids from the current versioned set.
 
1235
 
 
1236
        When a file_id is unversioned, all of its children are automatically
 
1237
        unversioned.
 
1238
 
 
1239
        :param file_ids: The file ids to stop versioning.
 
1240
        :raises: NoSuchId if any fileid is not currently versioned.
 
1241
        """
 
1242
        for file_id in file_ids:
 
1243
            if self._inventory.has_id(file_id):
 
1244
                self._inventory.remove_recursive_id(file_id)
 
1245
            else:
 
1246
                raise errors.NoSuchId(self, file_id)
 
1247
        if len(file_ids):
 
1248
            # in the future this should just set a dirty bit to wait for the 
 
1249
            # final unlock. However, until all methods of workingtree start
 
1250
            # with the current in -memory inventory rather than triggering 
 
1251
            # a read, it is more complex - we need to teach read_inventory
 
1252
            # to know when to read, and when to not read first... and possibly
 
1253
            # to save first when the in memory one may be corrupted.
 
1254
            # so for now, we just only write it if it is indeed dirty.
 
1255
            # - RBC 20060907
 
1256
            self._write_inventory(self._inventory)
 
1257
    
 
1258
    @deprecated_method(zero_eight)
 
1259
    def iter_conflicts(self):
 
1260
        """List all files in the tree that have text or content conflicts.
 
1261
        DEPRECATED.  Use conflicts instead."""
 
1262
        return self._iter_conflicts()
 
1263
 
 
1264
    def _iter_conflicts(self):
 
1265
        conflicted = set()
 
1266
        for info in self.list_files():
 
1267
            path = info[0]
 
1268
            stem = get_conflicted_stem(path)
 
1269
            if stem is None:
 
1270
                continue
 
1271
            if stem not in conflicted:
 
1272
                conflicted.add(stem)
 
1273
                yield stem
 
1274
 
 
1275
    @needs_write_lock
 
1276
    def pull(self, source, overwrite=False, stop_revision=None):
 
1277
        top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
1278
        source.lock_read()
 
1279
        try:
 
1280
            pp = ProgressPhase("Pull phase", 2, top_pb)
 
1281
            pp.next_phase()
 
1282
            old_revision_history = self.branch.revision_history()
 
1283
            basis_tree = self.basis_tree()
 
1284
            count = self.branch.pull(source, overwrite, stop_revision)
 
1285
            new_revision_history = self.branch.revision_history()
 
1286
            if new_revision_history != old_revision_history:
 
1287
                pp.next_phase()
 
1288
                if len(old_revision_history):
 
1289
                    other_revision = old_revision_history[-1]
 
1290
                else:
 
1291
                    other_revision = None
 
1292
                repository = self.branch.repository
 
1293
                pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
1294
                try:
 
1295
                    new_basis_tree = self.branch.basis_tree()
 
1296
                    merge.merge_inner(
 
1297
                                self.branch,
 
1298
                                new_basis_tree,
 
1299
                                basis_tree,
 
1300
                                this_tree=self,
 
1301
                                pb=pb)
 
1302
                    if (basis_tree.inventory.root is None and
 
1303
                        new_basis_tree.inventory.root is not None):
 
1304
                        self.set_root_id(new_basis_tree.inventory.root.file_id)
 
1305
                finally:
 
1306
                    pb.finished()
 
1307
                # TODO - dedup parents list with things merged by pull ?
 
1308
                # reuse the revisiontree we merged against to set the new
 
1309
                # tree data.
 
1310
                parent_trees = [(self.branch.last_revision(), new_basis_tree)]
 
1311
                # we have to pull the merge trees out again, because 
 
1312
                # merge_inner has set the ids. - this corner is not yet 
 
1313
                # layered well enough to prevent double handling.
 
1314
                merges = self.get_parent_ids()[1:]
 
1315
                parent_trees.extend([
 
1316
                    (parent, repository.revision_tree(parent)) for
 
1317
                     parent in merges])
 
1318
                self.set_parent_trees(parent_trees)
 
1319
            return count
 
1320
        finally:
 
1321
            source.unlock()
 
1322
            top_pb.finished()
 
1323
 
 
1324
    @needs_write_lock
 
1325
    def put_file_bytes_non_atomic(self, file_id, bytes):
 
1326
        """See MutableTree.put_file_bytes_non_atomic."""
 
1327
        stream = file(self.id2abspath(file_id), 'wb')
 
1328
        try:
 
1329
            stream.write(bytes)
 
1330
        finally:
 
1331
            stream.close()
 
1332
        # TODO: update the hashcache here ?
 
1333
 
 
1334
    def extras(self):
 
1335
        """Yield all unknown files in this WorkingTree.
 
1336
 
 
1337
        If there are any unknown directories then only the directory is
 
1338
        returned, not all its children.  But if there are unknown files
 
1339
        under a versioned subdirectory, they are returned.
 
1340
 
 
1341
        Currently returned depth-first, sorted by name within directories.
 
1342
        """
 
1343
        ## TODO: Work from given directory downwards
 
1344
        for path, dir_entry in self.inventory.directories():
 
1345
            # mutter("search for unknowns in %r", path)
 
1346
            dirabs = self.abspath(path)
 
1347
            if not isdir(dirabs):
 
1348
                # e.g. directory deleted
 
1349
                continue
 
1350
 
 
1351
            fl = []
 
1352
            for subf in os.listdir(dirabs):
 
1353
                if subf == '.bzr':
 
1354
                    continue
 
1355
                if subf not in dir_entry.children:
 
1356
                    subf_norm, can_access = osutils.normalized_filename(subf)
 
1357
                    if subf_norm != subf and can_access:
 
1358
                        if subf_norm not in dir_entry.children:
 
1359
                            fl.append(subf_norm)
 
1360
                    else:
 
1361
                        fl.append(subf)
 
1362
            
 
1363
            fl.sort()
 
1364
            for subf in fl:
 
1365
                subp = pathjoin(path, subf)
 
1366
                yield subp
 
1367
 
 
1368
 
 
1369
    def ignored_files(self):
 
1370
        """Yield list of PATH, IGNORE_PATTERN"""
 
1371
        for subp in self.extras():
 
1372
            pat = self.is_ignored(subp)
 
1373
            if pat is not None:
 
1374
                yield subp, pat
 
1375
 
 
1376
    def get_ignore_list(self):
 
1377
        """Return list of ignore patterns.
 
1378
 
 
1379
        Cached in the Tree object after the first call.
 
1380
        """
 
1381
        ignoreset = getattr(self, '_ignoreset', None)
 
1382
        if ignoreset is not None:
 
1383
            return ignoreset
 
1384
 
 
1385
        ignore_globs = set(bzrlib.DEFAULT_IGNORE)
 
1386
        ignore_globs.update(ignores.get_runtime_ignores())
 
1387
        ignore_globs.update(ignores.get_user_ignores())
 
1388
        if self.has_filename(bzrlib.IGNORE_FILENAME):
 
1389
            f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
 
1390
            try:
 
1391
                ignore_globs.update(ignores.parse_ignore_file(f))
 
1392
            finally:
 
1393
                f.close()
 
1394
        self._ignoreset = ignore_globs
 
1395
        return ignore_globs
 
1396
 
 
1397
    def _flush_ignore_list_cache(self):
 
1398
        """Resets the cached ignore list to force a cache rebuild."""
 
1399
        self._ignoreset = None
 
1400
        self._ignoreglobster = None
 
1401
 
 
1402
    def is_ignored(self, filename):
 
1403
        r"""Check whether the filename matches an ignore pattern.
 
1404
 
 
1405
        Patterns containing '/' or '\' need to match the whole path;
 
1406
        others match against only the last component.
 
1407
 
 
1408
        If the file is ignored, returns the pattern which caused it to
 
1409
        be ignored, otherwise None.  So this can simply be used as a
 
1410
        boolean if desired."""
 
1411
        if getattr(self, '_ignoreglobster', None) is None:
 
1412
            self._ignoreglobster = globbing.Globster(self.get_ignore_list())
 
1413
        return self._ignoreglobster.match(filename)
 
1414
 
 
1415
    def kind(self, file_id):
 
1416
        return file_kind(self.id2abspath(file_id))
 
1417
 
 
1418
    def _comparison_data(self, entry, path):
 
1419
        abspath = self.abspath(path)
 
1420
        try:
 
1421
            stat_value = os.lstat(abspath)
 
1422
        except OSError, e:
 
1423
            if getattr(e, 'errno', None) == errno.ENOENT:
 
1424
                stat_value = None
 
1425
                kind = None
 
1426
                executable = False
 
1427
            else:
 
1428
                raise
 
1429
        else:
 
1430
            mode = stat_value.st_mode
 
1431
            kind = osutils.file_kind_from_stat_mode(mode)
 
1432
            if not supports_executable():
 
1433
                executable = entry.executable
 
1434
            else:
 
1435
                executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
1436
        return kind, executable, stat_value
 
1437
 
 
1438
    def _file_size(self, entry, stat_value):
 
1439
        return stat_value.st_size
 
1440
 
 
1441
    def last_revision(self):
 
1442
        """Return the last revision of the branch for this tree.
 
1443
 
 
1444
        This format tree does not support a separate marker for last-revision
 
1445
        compared to the branch.
 
1446
 
 
1447
        See MutableTree.last_revision
 
1448
        """
 
1449
        return self._last_revision()
 
1450
 
 
1451
    @needs_read_lock
 
1452
    def _last_revision(self):
 
1453
        """helper for get_parent_ids."""
 
1454
        return self.branch.last_revision()
 
1455
 
 
1456
    def is_locked(self):
 
1457
        return self._control_files.is_locked()
 
1458
 
 
1459
    def lock_read(self):
 
1460
        """See Branch.lock_read, and WorkingTree.unlock."""
 
1461
        self.branch.lock_read()
 
1462
        try:
 
1463
            return self._control_files.lock_read()
 
1464
        except:
 
1465
            self.branch.unlock()
 
1466
            raise
 
1467
 
 
1468
    def lock_tree_write(self):
 
1469
        """See MutableTree.lock_tree_write, and WorkingTree.unlock."""
 
1470
        self.branch.lock_read()
 
1471
        try:
 
1472
            return self._control_files.lock_write()
 
1473
        except:
 
1474
            self.branch.unlock()
 
1475
            raise
 
1476
 
 
1477
    def lock_write(self):
 
1478
        """See MutableTree.lock_write, and WorkingTree.unlock."""
 
1479
        self.branch.lock_write()
 
1480
        try:
 
1481
            return self._control_files.lock_write()
 
1482
        except:
 
1483
            self.branch.unlock()
 
1484
            raise
 
1485
 
 
1486
    def get_physical_lock_status(self):
 
1487
        return self._control_files.get_physical_lock_status()
 
1488
 
 
1489
    def _basis_inventory_name(self):
 
1490
        return 'basis-inventory-cache'
 
1491
 
 
1492
    @needs_tree_write_lock
 
1493
    def set_last_revision(self, new_revision):
 
1494
        """Change the last revision in the working tree."""
 
1495
        if self._change_last_revision(new_revision):
 
1496
            self._cache_basis_inventory(new_revision)
 
1497
 
 
1498
    def _change_last_revision(self, new_revision):
 
1499
        """Template method part of set_last_revision to perform the change.
 
1500
        
 
1501
        This is used to allow WorkingTree3 instances to not affect branch
 
1502
        when their last revision is set.
 
1503
        """
 
1504
        if new_revision is None:
 
1505
            self.branch.set_revision_history([])
 
1506
            return False
 
1507
        try:
 
1508
            self.branch.generate_revision_history(new_revision)
 
1509
        except errors.NoSuchRevision:
 
1510
            # not present in the repo - dont try to set it deeper than the tip
 
1511
            self.branch.set_revision_history([new_revision])
 
1512
        return True
 
1513
 
 
1514
    def _write_basis_inventory(self, xml):
 
1515
        """Write the basis inventory XML to the basis-inventory file"""
 
1516
        assert isinstance(xml, str), 'serialised xml must be bytestring.'
 
1517
        path = self._basis_inventory_name()
 
1518
        sio = StringIO(xml)
 
1519
        self._control_files.put(path, sio)
 
1520
 
 
1521
    def _create_basis_xml_from_inventory(self, revision_id, inventory):
 
1522
        """Create the text that will be saved in basis-inventory"""
 
1523
        inventory.revision_id = revision_id
 
1524
        return xml7.serializer_v7.write_inventory_to_string(inventory)
 
1525
 
 
1526
    def _cache_basis_inventory(self, new_revision):
 
1527
        """Cache new_revision as the basis inventory."""
 
1528
        # TODO: this should allow the ready-to-use inventory to be passed in,
 
1529
        # as commit already has that ready-to-use [while the format is the
 
1530
        # same, that is].
 
1531
        try:
 
1532
            # this double handles the inventory - unpack and repack - 
 
1533
            # but is easier to understand. We can/should put a conditional
 
1534
            # in here based on whether the inventory is in the latest format
 
1535
            # - perhaps we should repack all inventories on a repository
 
1536
            # upgrade ?
 
1537
            # the fast path is to copy the raw xml from the repository. If the
 
1538
            # xml contains 'revision_id="', then we assume the right 
 
1539
            # revision_id is set. We must check for this full string, because a
 
1540
            # root node id can legitimately look like 'revision_id' but cannot
 
1541
            # contain a '"'.
 
1542
            xml = self.branch.repository.get_inventory_xml(new_revision)
 
1543
            firstline = xml.split('\n', 1)[0]
 
1544
            if (not 'revision_id="' in firstline or 
 
1545
                'format="7"' not in firstline):
 
1546
                inv = self.branch.repository.deserialise_inventory(
 
1547
                    new_revision, xml)
 
1548
                xml = self._create_basis_xml_from_inventory(new_revision, inv)
 
1549
            self._write_basis_inventory(xml)
 
1550
        except (errors.NoSuchRevision, errors.RevisionNotPresent):
 
1551
            pass
 
1552
 
 
1553
    def read_basis_inventory(self):
 
1554
        """Read the cached basis inventory."""
 
1555
        path = self._basis_inventory_name()
 
1556
        return self._control_files.get(path).read()
 
1557
        
 
1558
    @needs_read_lock
 
1559
    def read_working_inventory(self):
 
1560
        """Read the working inventory.
 
1561
        
 
1562
        :raises errors.InventoryModified: read_working_inventory will fail
 
1563
            when the current in memory inventory has been modified.
 
1564
        """
 
1565
        # conceptually this should be an implementation detail of the tree. 
 
1566
        # XXX: Deprecate this.
 
1567
        # ElementTree does its own conversion from UTF-8, so open in
 
1568
        # binary.
 
1569
        if self._inventory_is_modified:
 
1570
            raise errors.InventoryModified(self)
 
1571
        result = self._deserialize(self._control_files.get('inventory'))
 
1572
        self._set_inventory(result, dirty=False)
 
1573
        return result
 
1574
 
 
1575
    @needs_tree_write_lock
 
1576
    def remove(self, files, verbose=False, to_file=None):
 
1577
        """Remove nominated files from the working inventory..
 
1578
 
 
1579
        This does not remove their text.  This does not run on XXX on what? RBC
 
1580
 
 
1581
        TODO: Refuse to remove modified files unless --force is given?
 
1582
 
 
1583
        TODO: Do something useful with directories.
 
1584
 
 
1585
        TODO: Should this remove the text or not?  Tough call; not
 
1586
        removing may be useful and the user can just use use rm, and
 
1587
        is the opposite of add.  Removing it is consistent with most
 
1588
        other tools.  Maybe an option.
 
1589
        """
 
1590
        ## TODO: Normalize names
 
1591
        ## TODO: Remove nested loops; better scalability
 
1592
        if isinstance(files, basestring):
 
1593
            files = [files]
 
1594
 
 
1595
        inv = self.inventory
 
1596
 
 
1597
        # do this before any modifications
 
1598
        for f in files:
 
1599
            fid = inv.path2id(f)
 
1600
            if not fid:
 
1601
                # TODO: Perhaps make this just a warning, and continue?
 
1602
                # This tends to happen when 
 
1603
                raise NotVersionedError(path=f)
 
1604
            if verbose:
 
1605
                # having remove it, it must be either ignored or unknown
 
1606
                if self.is_ignored(f):
 
1607
                    new_status = 'I'
 
1608
                else:
 
1609
                    new_status = '?'
 
1610
                textui.show_status(new_status, inv[fid].kind, f,
 
1611
                                   to_file=to_file)
 
1612
            del inv[fid]
 
1613
 
 
1614
        self._write_inventory(inv)
 
1615
 
 
1616
    @needs_tree_write_lock
 
1617
    def revert(self, filenames, old_tree=None, backups=True, 
 
1618
               pb=DummyProgress()):
 
1619
        from bzrlib.conflicts import resolve
 
1620
        if old_tree is None:
 
1621
            old_tree = self.basis_tree()
 
1622
        conflicts = transform.revert(self, old_tree, filenames, backups, pb)
 
1623
        if not len(filenames):
 
1624
            self.set_parent_ids(self.get_parent_ids()[:1])
 
1625
            resolve(self)
 
1626
        else:
 
1627
            resolve(self, filenames, ignore_misses=True)
 
1628
        return conflicts
 
1629
 
 
1630
    # XXX: This method should be deprecated in favour of taking in a proper
 
1631
    # new Inventory object.
 
1632
    @needs_tree_write_lock
 
1633
    def set_inventory(self, new_inventory_list):
 
1634
        from bzrlib.inventory import (Inventory,
 
1635
                                      InventoryDirectory,
 
1636
                                      InventoryEntry,
 
1637
                                      InventoryFile,
 
1638
                                      InventoryLink)
 
1639
        inv = Inventory(self.get_root_id())
 
1640
        for path, file_id, parent, kind in new_inventory_list:
 
1641
            name = os.path.basename(path)
 
1642
            if name == "":
 
1643
                continue
 
1644
            # fixme, there should be a factory function inv,add_?? 
 
1645
            if kind == 'directory':
 
1646
                inv.add(InventoryDirectory(file_id, name, parent))
 
1647
            elif kind == 'file':
 
1648
                inv.add(InventoryFile(file_id, name, parent))
 
1649
            elif kind == 'symlink':
 
1650
                inv.add(InventoryLink(file_id, name, parent))
 
1651
            else:
 
1652
                raise BzrError("unknown kind %r" % kind)
 
1653
        self._write_inventory(inv)
 
1654
 
 
1655
    @needs_tree_write_lock
 
1656
    def set_root_id(self, file_id):
 
1657
        """Set the root id for this tree."""
 
1658
        # for compatability 
 
1659
        if file_id is None:
 
1660
            symbol_versioning.warn(symbol_versioning.zero_twelve
 
1661
                % 'WorkingTree.set_root_id with fileid=None',
 
1662
                DeprecationWarning,
 
1663
                stacklevel=3)
 
1664
            file_id = ROOT_ID
 
1665
        inv = self._inventory
 
1666
        orig_root_id = inv.root.file_id
 
1667
        # TODO: it might be nice to exit early if there was nothing
 
1668
        # to do, saving us from trigger a sync on unlock.
 
1669
        self._inventory_is_modified = True
 
1670
        # we preserve the root inventory entry object, but
 
1671
        # unlinkit from the byid index
 
1672
        del inv._byid[inv.root.file_id]
 
1673
        inv.root.file_id = file_id
 
1674
        # and link it into the index with the new changed id.
 
1675
        inv._byid[inv.root.file_id] = inv.root
 
1676
        # and finally update all children to reference the new id.
 
1677
        # XXX: this should be safe to just look at the root.children
 
1678
        # list, not the WHOLE INVENTORY.
 
1679
        for fid in inv:
 
1680
            entry = inv[fid]
 
1681
            if entry.parent_id == orig_root_id:
 
1682
                entry.parent_id = inv.root.file_id
 
1683
 
 
1684
    def unlock(self):
 
1685
        """See Branch.unlock.
 
1686
        
 
1687
        WorkingTree locking just uses the Branch locking facilities.
 
1688
        This is current because all working trees have an embedded branch
 
1689
        within them. IF in the future, we were to make branch data shareable
 
1690
        between multiple working trees, i.e. via shared storage, then we 
 
1691
        would probably want to lock both the local tree, and the branch.
 
1692
        """
 
1693
        raise NotImplementedError(self.unlock)
 
1694
 
 
1695
    def update(self):
 
1696
        """Update a working tree along its branch.
 
1697
 
 
1698
        This will update the branch if its bound too, which means we have
 
1699
        multiple trees involved:
 
1700
 
 
1701
        - The new basis tree of the master.
 
1702
        - The old basis tree of the branch.
 
1703
        - The old basis tree of the working tree.
 
1704
        - The current working tree state.
 
1705
 
 
1706
        Pathologically, all three may be different, and non-ancestors of each
 
1707
        other.  Conceptually we want to:
 
1708
 
 
1709
        - Preserve the wt.basis->wt.state changes
 
1710
        - Transform the wt.basis to the new master basis.
 
1711
        - Apply a merge of the old branch basis to get any 'local' changes from
 
1712
          it into the tree.
 
1713
        - Restore the wt.basis->wt.state changes.
 
1714
 
 
1715
        There isn't a single operation at the moment to do that, so we:
 
1716
        - Merge current state -> basis tree of the master w.r.t. the old tree
 
1717
          basis.
 
1718
        - Do a 'normal' merge of the old branch basis if it is relevant.
 
1719
        """
 
1720
        if self.branch.get_master_branch() is not None:
 
1721
            self.lock_write()
 
1722
            update_branch = True
 
1723
        else:
 
1724
            self.lock_tree_write()
 
1725
            update_branch = False
 
1726
        try:
 
1727
            if update_branch:
 
1728
                old_tip = self.branch.update()
 
1729
            else:
 
1730
                old_tip = None
 
1731
            return self._update_tree(old_tip)
 
1732
        finally:
 
1733
            self.unlock()
 
1734
 
 
1735
    @needs_tree_write_lock
 
1736
    def _update_tree(self, old_tip=None):
 
1737
        """Update a tree to the master branch.
 
1738
 
 
1739
        :param old_tip: if supplied, the previous tip revision the branch,
 
1740
            before it was changed to the master branch's tip.
 
1741
        """
 
1742
        # here if old_tip is not None, it is the old tip of the branch before
 
1743
        # it was updated from the master branch. This should become a pending
 
1744
        # merge in the working tree to preserve the user existing work.  we
 
1745
        # cant set that until we update the working trees last revision to be
 
1746
        # one from the new branch, because it will just get absorbed by the
 
1747
        # parent de-duplication logic.
 
1748
        # 
 
1749
        # We MUST save it even if an error occurs, because otherwise the users
 
1750
        # local work is unreferenced and will appear to have been lost.
 
1751
        # 
 
1752
        result = 0
 
1753
        try:
 
1754
            last_rev = self.get_parent_ids()[0]
 
1755
        except IndexError:
 
1756
            last_rev = None
 
1757
        if last_rev != self.branch.last_revision():
 
1758
            # merge tree state up to new branch tip.
 
1759
            basis = self.basis_tree()
 
1760
            to_tree = self.branch.basis_tree()
 
1761
            if basis.inventory.root is None:
 
1762
                self.set_root_id(to_tree.inventory.root.file_id)
 
1763
            result += merge.merge_inner(
 
1764
                                  self.branch,
 
1765
                                  to_tree,
 
1766
                                  basis,
 
1767
                                  this_tree=self)
 
1768
            # TODO - dedup parents list with things merged by pull ?
 
1769
            # reuse the tree we've updated to to set the basis:
 
1770
            parent_trees = [(self.branch.last_revision(), to_tree)]
 
1771
            merges = self.get_parent_ids()[1:]
 
1772
            # Ideally we ask the tree for the trees here, that way the working
 
1773
            # tree can decide whether to give us teh entire tree or give us a
 
1774
            # lazy initialised tree. dirstate for instance will have the trees
 
1775
            # in ram already, whereas a last-revision + basis-inventory tree
 
1776
            # will not, but also does not need them when setting parents.
 
1777
            for parent in merges:
 
1778
                parent_trees.append(
 
1779
                    (parent, self.branch.repository.revision_tree(parent)))
 
1780
            if old_tip is not None:
 
1781
                parent_trees.append(
 
1782
                    (old_tip, self.branch.repository.revision_tree(old_tip)))
 
1783
            self.set_parent_trees(parent_trees)
 
1784
            last_rev = parent_trees[0][0]
 
1785
        else:
 
1786
            # the working tree had the same last-revision as the master
 
1787
            # branch did. We may still have pivot local work from the local
 
1788
            # branch into old_tip:
 
1789
            if old_tip is not None:
 
1790
                self.add_parent_tree_id(old_tip)
 
1791
        if old_tip and old_tip != last_rev:
 
1792
            # our last revision was not the prior branch last revision
 
1793
            # and we have converted that last revision to a pending merge.
 
1794
            # base is somewhere between the branch tip now
 
1795
            # and the now pending merge
 
1796
            from bzrlib.revision import common_ancestor
 
1797
            try:
 
1798
                base_rev_id = common_ancestor(self.branch.last_revision(),
 
1799
                                              old_tip,
 
1800
                                              self.branch.repository)
 
1801
            except errors.NoCommonAncestor:
 
1802
                base_rev_id = None
 
1803
            base_tree = self.branch.repository.revision_tree(base_rev_id)
 
1804
            other_tree = self.branch.repository.revision_tree(old_tip)
 
1805
            result += merge.merge_inner(
 
1806
                                  self.branch,
 
1807
                                  other_tree,
 
1808
                                  base_tree,
 
1809
                                  this_tree=self)
 
1810
        return result
 
1811
 
 
1812
    def _write_hashcache_if_dirty(self):
 
1813
        """Write out the hashcache if it is dirty."""
 
1814
        if self._hashcache.needs_write:
 
1815
            try:
 
1816
                self._hashcache.write()
 
1817
            except OSError, e:
 
1818
                if e.errno not in (errno.EPERM, errno.EACCES):
 
1819
                    raise
 
1820
                # TODO: jam 20061219 Should this be a warning? A single line
 
1821
                #       warning might be sufficient to let the user know what
 
1822
                #       is going on.
 
1823
                mutter('Could not write hashcache for %s\nError: %s',
 
1824
                       self._hashcache.cache_file_name(), e)
 
1825
 
 
1826
    @needs_tree_write_lock
 
1827
    def _write_inventory(self, inv):
 
1828
        """Write inventory as the current inventory."""
 
1829
        self._set_inventory(inv, dirty=True)
 
1830
        self.flush()
 
1831
 
 
1832
    def set_conflicts(self, arg):
 
1833
        raise UnsupportedOperation(self.set_conflicts, self)
 
1834
 
 
1835
    def add_conflicts(self, arg):
 
1836
        raise UnsupportedOperation(self.add_conflicts, self)
 
1837
 
 
1838
    @needs_read_lock
 
1839
    def conflicts(self):
 
1840
        conflicts = _mod_conflicts.ConflictList()
 
1841
        for conflicted in self._iter_conflicts():
 
1842
            text = True
 
1843
            try:
 
1844
                if file_kind(self.abspath(conflicted)) != "file":
 
1845
                    text = False
 
1846
            except errors.NoSuchFile:
 
1847
                text = False
 
1848
            if text is True:
 
1849
                for suffix in ('.THIS', '.OTHER'):
 
1850
                    try:
 
1851
                        kind = file_kind(self.abspath(conflicted+suffix))
 
1852
                        if kind != "file":
 
1853
                            text = False
 
1854
                    except errors.NoSuchFile:
 
1855
                        text = False
 
1856
                    if text == False:
 
1857
                        break
 
1858
            ctype = {True: 'text conflict', False: 'contents conflict'}[text]
 
1859
            conflicts.append(_mod_conflicts.Conflict.factory(ctype,
 
1860
                             path=conflicted,
 
1861
                             file_id=self.path2id(conflicted)))
 
1862
        return conflicts
 
1863
 
 
1864
 
 
1865
class WorkingTree2(WorkingTree):
 
1866
    """This is the Format 2 working tree.
 
1867
 
 
1868
    This was the first weave based working tree. 
 
1869
     - uses os locks for locking.
 
1870
     - uses the branch last-revision.
 
1871
    """
 
1872
 
 
1873
    def lock_tree_write(self):
 
1874
        """See WorkingTree.lock_tree_write().
 
1875
 
 
1876
        In Format2 WorkingTrees we have a single lock for the branch and tree
 
1877
        so lock_tree_write() degrades to lock_write().
 
1878
        """
 
1879
        self.branch.lock_write()
 
1880
        try:
 
1881
            return self._control_files.lock_write()
 
1882
        except:
 
1883
            self.branch.unlock()
 
1884
            raise
 
1885
 
 
1886
    def unlock(self):
 
1887
        # we share control files:
 
1888
        if self._control_files._lock_count == 3:
 
1889
            # _inventory_is_modified is always False during a read lock.
 
1890
            if self._inventory_is_modified:
 
1891
                self.flush()
 
1892
            self._write_hashcache_if_dirty()
 
1893
                    
 
1894
        # reverse order of locking.
 
1895
        try:
 
1896
            return self._control_files.unlock()
 
1897
        finally:
 
1898
            self.branch.unlock()
 
1899
 
 
1900
 
 
1901
class WorkingTree3(WorkingTree):
 
1902
    """This is the Format 3 working tree.
 
1903
 
 
1904
    This differs from the base WorkingTree by:
 
1905
     - having its own file lock
 
1906
     - having its own last-revision property.
 
1907
 
 
1908
    This is new in bzr 0.8
 
1909
    """
 
1910
 
 
1911
    @needs_read_lock
 
1912
    def _last_revision(self):
 
1913
        """See Mutable.last_revision."""
 
1914
        try:
 
1915
            return self._control_files.get_utf8('last-revision').read()
 
1916
        except NoSuchFile:
 
1917
            return None
 
1918
 
 
1919
    def _change_last_revision(self, revision_id):
 
1920
        """See WorkingTree._change_last_revision."""
 
1921
        if revision_id is None or revision_id == NULL_REVISION:
 
1922
            try:
 
1923
                self._control_files._transport.delete('last-revision')
 
1924
            except errors.NoSuchFile:
 
1925
                pass
 
1926
            return False
 
1927
        else:
 
1928
            self._control_files.put_utf8('last-revision', revision_id)
 
1929
            return True
 
1930
 
 
1931
    @needs_tree_write_lock
 
1932
    def set_conflicts(self, conflicts):
 
1933
        self._put_rio('conflicts', conflicts.to_stanzas(), 
 
1934
                      CONFLICT_HEADER_1)
 
1935
 
 
1936
    @needs_tree_write_lock
 
1937
    def add_conflicts(self, new_conflicts):
 
1938
        conflict_set = set(self.conflicts())
 
1939
        conflict_set.update(set(list(new_conflicts)))
 
1940
        self.set_conflicts(_mod_conflicts.ConflictList(sorted(conflict_set,
 
1941
                                       key=_mod_conflicts.Conflict.sort_key)))
 
1942
 
 
1943
    @needs_read_lock
 
1944
    def conflicts(self):
 
1945
        try:
 
1946
            confile = self._control_files.get('conflicts')
 
1947
        except NoSuchFile:
 
1948
            return _mod_conflicts.ConflictList()
 
1949
        try:
 
1950
            if confile.next() != CONFLICT_HEADER_1 + '\n':
 
1951
                raise ConflictFormatError()
 
1952
        except StopIteration:
 
1953
            raise ConflictFormatError()
 
1954
        return _mod_conflicts.ConflictList.from_stanzas(RioReader(confile))
 
1955
 
 
1956
    def unlock(self):
 
1957
        if self._control_files._lock_count == 1:
 
1958
            # _inventory_is_modified is always False during a read lock.
 
1959
            if self._inventory_is_modified:
 
1960
                self.flush()
 
1961
            self._write_hashcache_if_dirty()
 
1962
        # reverse order of locking.
 
1963
        try:
 
1964
            return self._control_files.unlock()
 
1965
        finally:
 
1966
            self.branch.unlock()
 
1967
 
 
1968
 
 
1969
class WorkingTree4(WorkingTree3):
 
1970
 
 
1971
    def add_reference(self, sub_tree):
 
1972
        try:
 
1973
            sub_tree_path = self.relpath(sub_tree.basedir)
 
1974
        except errors.PathNotChild:
 
1975
            raise errors.BadReferenceTarget(self, sub_tree, 
 
1976
                                            'Target not inside tree.')
 
1977
        parent_id = self.path2id(osutils.dirname(sub_tree_path))
 
1978
        name = osutils.basename(sub_tree_path)
 
1979
        sub_tree_id = sub_tree.get_root_id()
 
1980
        if sub_tree_id == self.get_root_id():
 
1981
            raise errors.BadReferenceTarget(self, sub_tree, 
 
1982
                                     'Trees have the same root id.')
 
1983
        if sub_tree_id in self.inventory:
 
1984
            raise errors.BadReferenceTarget(self, sub_tree, 
 
1985
                                            'Root id already present in tree')
 
1986
        entry = TreeReference(sub_tree_id, name, parent_id, None, 
 
1987
                              None)
 
1988
        self.inventory.add(entry)
 
1989
        self._write_inventory(self.inventory)
 
1990
 
 
1991
    def _serialize(self, inventory, out_file):
 
1992
        xml7.serializer_v7.write_inventory(self._inventory, out_file)
 
1993
 
 
1994
    def _deserialize(selt, in_file):
 
1995
        return xml7.serializer_v7.read_inventory(in_file)
 
1996
 
 
1997
 
 
1998
def get_conflicted_stem(path):
 
1999
    for suffix in _mod_conflicts.CONFLICT_SUFFIXES:
 
2000
        if path.endswith(suffix):
 
2001
            return path[:-len(suffix)]
 
2002
 
 
2003
@deprecated_function(zero_eight)
 
2004
def is_control_file(filename):
 
2005
    """See WorkingTree.is_control_filename(filename)."""
 
2006
    ## FIXME: better check
 
2007
    filename = normpath(filename)
 
2008
    while filename != '':
 
2009
        head, tail = os.path.split(filename)
 
2010
        ## mutter('check %r for control file' % ((head, tail),))
 
2011
        if tail == '.bzr':
 
2012
            return True
 
2013
        if filename == head:
 
2014
            break
 
2015
        filename = head
 
2016
    return False
 
2017
 
 
2018
 
 
2019
class WorkingTreeFormat(object):
 
2020
    """An encapsulation of the initialization and open routines for a format.
 
2021
 
 
2022
    Formats provide three things:
 
2023
     * An initialization routine,
 
2024
     * a format string,
 
2025
     * an open routine.
 
2026
 
 
2027
    Formats are placed in an dict by their format string for reference 
 
2028
    during workingtree opening. Its not required that these be instances, they
 
2029
    can be classes themselves with class methods - it simply depends on 
 
2030
    whether state is needed for a given format or not.
 
2031
 
 
2032
    Once a format is deprecated, just deprecate the initialize and open
 
2033
    methods on the format class. Do not deprecate the object, as the 
 
2034
    object will be created every time regardless.
 
2035
    """
 
2036
 
 
2037
    _default_format = None
 
2038
    """The default format used for new trees."""
 
2039
 
 
2040
    _formats = {}
 
2041
    """The known formats."""
 
2042
 
 
2043
    requires_rich_root = False
 
2044
 
 
2045
    @classmethod
 
2046
    def find_format(klass, a_bzrdir):
 
2047
        """Return the format for the working tree object in a_bzrdir."""
 
2048
        try:
 
2049
            transport = a_bzrdir.get_workingtree_transport(None)
 
2050
            format_string = transport.get("format").read()
 
2051
            return klass._formats[format_string]
 
2052
        except NoSuchFile:
 
2053
            raise errors.NoWorkingTree(base=transport.base)
 
2054
        except KeyError:
 
2055
            raise errors.UnknownFormatError(format=format_string)
 
2056
 
 
2057
    @classmethod
 
2058
    def get_default_format(klass):
 
2059
        """Return the current default format."""
 
2060
        return klass._default_format
 
2061
 
 
2062
    def get_format_string(self):
 
2063
        """Return the ASCII format string that identifies this format."""
 
2064
        raise NotImplementedError(self.get_format_string)
 
2065
 
 
2066
    def get_format_description(self):
 
2067
        """Return the short description for this format."""
 
2068
        raise NotImplementedError(self.get_format_description)
 
2069
 
 
2070
    def is_supported(self):
 
2071
        """Is this format supported?
 
2072
 
 
2073
        Supported formats can be initialized and opened.
 
2074
        Unsupported formats may not support initialization or committing or 
 
2075
        some other features depending on the reason for not being supported.
 
2076
        """
 
2077
        return True
 
2078
 
 
2079
    @classmethod
 
2080
    def register_format(klass, format):
 
2081
        klass._formats[format.get_format_string()] = format
 
2082
 
 
2083
    @classmethod
 
2084
    def set_default_format(klass, format):
 
2085
        klass._default_format = format
 
2086
 
 
2087
    @classmethod
 
2088
    def unregister_format(klass, format):
 
2089
        assert klass._formats[format.get_format_string()] is format
 
2090
        del klass._formats[format.get_format_string()]
 
2091
 
 
2092
 
 
2093
 
 
2094
class WorkingTreeFormat2(WorkingTreeFormat):
 
2095
    """The second working tree format. 
 
2096
 
 
2097
    This format modified the hash cache from the format 1 hash cache.
 
2098
    """
 
2099
 
 
2100
    def get_format_description(self):
 
2101
        """See WorkingTreeFormat.get_format_description()."""
 
2102
        return "Working tree format 2"
 
2103
 
 
2104
    def stub_initialize_remote(self, control_files):
 
2105
        """As a special workaround create critical control files for a remote working tree
 
2106
        
 
2107
        This ensures that it can later be updated and dealt with locally,
 
2108
        since BzrDirFormat6 and BzrDirFormat5 cannot represent dirs with 
 
2109
        no working tree.  (See bug #43064).
 
2110
        """
 
2111
        sio = StringIO()
 
2112
        inv = Inventory()
 
2113
        xml5.serializer_v5.write_inventory(inv, sio)
 
2114
        sio.seek(0)
 
2115
        control_files.put('inventory', sio)
 
2116
 
 
2117
        control_files.put_utf8('pending-merges', '')
 
2118
        
 
2119
 
 
2120
    def initialize(self, a_bzrdir, revision_id=None):
 
2121
        """See WorkingTreeFormat.initialize()."""
 
2122
        if not isinstance(a_bzrdir.transport, LocalTransport):
 
2123
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
 
2124
        branch = a_bzrdir.open_branch()
 
2125
        if revision_id is not None:
 
2126
            branch.lock_write()
 
2127
            try:
 
2128
                revision_history = branch.revision_history()
 
2129
                try:
 
2130
                    position = revision_history.index(revision_id)
 
2131
                except ValueError:
 
2132
                    raise errors.NoSuchRevision(branch, revision_id)
 
2133
                branch.set_revision_history(revision_history[:position + 1])
 
2134
            finally:
 
2135
                branch.unlock()
 
2136
        revision = branch.last_revision()
 
2137
        inv = Inventory()
 
2138
        wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
 
2139
                         branch,
 
2140
                         inv,
 
2141
                         _internal=True,
 
2142
                         _format=self,
 
2143
                         _bzrdir=a_bzrdir)
 
2144
        basis_tree = branch.repository.revision_tree(revision)
 
2145
        if basis_tree.inventory.root is not None:
 
2146
            wt.set_root_id(basis_tree.inventory.root.file_id)
 
2147
        # set the parent list and cache the basis tree.
 
2148
        wt.set_parent_trees([(revision, basis_tree)])
 
2149
        transform.build_tree(basis_tree, wt)
 
2150
        return wt
 
2151
 
 
2152
    def __init__(self):
 
2153
        super(WorkingTreeFormat2, self).__init__()
 
2154
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
 
2155
 
 
2156
    def open(self, a_bzrdir, _found=False):
 
2157
        """Return the WorkingTree object for a_bzrdir
 
2158
 
 
2159
        _found is a private parameter, do not use it. It is used to indicate
 
2160
               if format probing has already been done.
 
2161
        """
 
2162
        if not _found:
 
2163
            # we are being called directly and must probe.
 
2164
            raise NotImplementedError
 
2165
        if not isinstance(a_bzrdir.transport, LocalTransport):
 
2166
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
 
2167
        return WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
 
2168
                           _internal=True,
 
2169
                           _format=self,
 
2170
                           _bzrdir=a_bzrdir)
 
2171
 
 
2172
 
 
2173
class WorkingTreeFormat3(WorkingTreeFormat):
 
2174
    """The second working tree format updated to record a format marker.
 
2175
 
 
2176
    This format:
 
2177
        - exists within a metadir controlling .bzr
 
2178
        - includes an explicit version marker for the workingtree control
 
2179
          files, separate from the BzrDir format
 
2180
        - modifies the hash cache format
 
2181
        - is new in bzr 0.8
 
2182
        - uses a LockDir to guard access for writes.
 
2183
    """
 
2184
 
 
2185
    def get_format_string(self):
 
2186
        """See WorkingTreeFormat.get_format_string()."""
 
2187
        return "Bazaar-NG Working Tree format 3"
 
2188
 
 
2189
    def get_format_description(self):
 
2190
        """See WorkingTreeFormat.get_format_description()."""
 
2191
        return "Working tree format 3"
 
2192
 
 
2193
    _lock_file_name = 'lock'
 
2194
    _lock_class = LockDir
 
2195
    _tree_class = WorkingTree3
 
2196
 
 
2197
    def __get_matchingbzrdir(self):
 
2198
        return bzrdir.BzrDirMetaFormat1()
 
2199
 
 
2200
    _matchingbzrdir = property(__get_matchingbzrdir)
 
2201
 
 
2202
    def _open_control_files(self, a_bzrdir):
 
2203
        transport = a_bzrdir.get_workingtree_transport(None)
 
2204
        return LockableFiles(transport, self._lock_file_name, 
 
2205
                             self._lock_class)
 
2206
 
 
2207
    def initialize(self, a_bzrdir, revision_id=None):
 
2208
        """See WorkingTreeFormat.initialize().
 
2209
        
 
2210
        revision_id allows creating a working tree at a different
 
2211
        revision than the branch is at.
 
2212
        """
 
2213
        if not isinstance(a_bzrdir.transport, LocalTransport):
 
2214
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
 
2215
        transport = a_bzrdir.get_workingtree_transport(self)
 
2216
        control_files = self._open_control_files(a_bzrdir)
 
2217
        control_files.create_lock()
 
2218
        control_files.lock_write()
 
2219
        control_files.put_utf8('format', self.get_format_string())
 
2220
        branch = a_bzrdir.open_branch()
 
2221
        if revision_id is None:
 
2222
            revision_id = branch.last_revision()
 
2223
        inv = self._initial_inventory()
 
2224
        wt = self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
 
2225
                         branch,
 
2226
                         inv,
 
2227
                         _internal=True,
 
2228
                         _format=self,
 
2229
                         _bzrdir=a_bzrdir,
 
2230
                         _control_files=control_files)
 
2231
        wt.lock_tree_write()
 
2232
        try:
 
2233
            basis_tree = branch.repository.revision_tree(revision_id)
 
2234
            # only set an explicit root id if there is one to set.
 
2235
            if basis_tree.inventory.root is not None:
 
2236
                wt.set_root_id(basis_tree.inventory.root.file_id)
 
2237
            if revision_id == NULL_REVISION:
 
2238
                wt.set_parent_trees([])
 
2239
            else:
 
2240
                wt.set_parent_trees([(revision_id, basis_tree)])
 
2241
            transform.build_tree(basis_tree, wt)
 
2242
        finally:
 
2243
            # Unlock in this order so that the unlock-triggers-flush in
 
2244
            # WorkingTree is given a chance to fire.
 
2245
            control_files.unlock()
 
2246
            wt.unlock()
 
2247
        return wt
 
2248
 
 
2249
    def _initial_inventory(self):
 
2250
        return Inventory()
 
2251
 
 
2252
    def __init__(self):
 
2253
        super(WorkingTreeFormat3, self).__init__()
 
2254
 
 
2255
    def open(self, a_bzrdir, _found=False):
 
2256
        """Return the WorkingTree object for a_bzrdir
 
2257
 
 
2258
        _found is a private parameter, do not use it. It is used to indicate
 
2259
               if format probing has already been done.
 
2260
        """
 
2261
        if not _found:
 
2262
            # we are being called directly and must probe.
 
2263
            raise NotImplementedError
 
2264
        if not isinstance(a_bzrdir.transport, LocalTransport):
 
2265
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
 
2266
        return self._open(a_bzrdir, self._open_control_files(a_bzrdir))
 
2267
 
 
2268
    def _open(self, a_bzrdir, control_files):
 
2269
        """Open the tree itself.
 
2270
        
 
2271
        :param a_bzrdir: the dir for the tree.
 
2272
        :param control_files: the control files for the tree.
 
2273
        """
 
2274
        return self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
 
2275
                                _internal=True,
 
2276
                                _format=self,
 
2277
                                _bzrdir=a_bzrdir,
 
2278
                                _control_files=control_files)
 
2279
 
 
2280
    def __str__(self):
 
2281
        return self.get_format_string()
 
2282
 
 
2283
 
 
2284
class WorkingTreeFormat4(WorkingTreeFormat3):
 
2285
    
 
2286
    """Working tree format that supports unique roots and nested trees"""
 
2287
 
 
2288
    _tree_class = WorkingTree4
 
2289
 
 
2290
    requires_rich_root = True
 
2291
 
 
2292
    def __init__(self):
 
2293
        WorkingTreeFormat3.__init__(self)
 
2294
        
 
2295
    def __get_matchingbzrdir(self):
 
2296
        return bzrdir.format_registry.make_bzrdir('experimental-knit3')
 
2297
 
 
2298
    _matchingbzrdir = property(__get_matchingbzrdir)
 
2299
 
 
2300
    def get_format_string(self):
 
2301
        """See WorkingTreeFormat.get_format_string()."""
 
2302
        return "Bazaar-NG Working Tree format 4"
 
2303
 
 
2304
    def get_format_description(self):
 
2305
        """See WorkingTreeFormat.get_format_description()."""
 
2306
        return "Working tree format 4"
 
2307
 
 
2308
    def _initial_inventory(self):
 
2309
        return Inventory(root_id=generate_ids.gen_root_id())
 
2310
 
 
2311
# formats which have no format string are not discoverable
 
2312
# and not independently creatable, so are not registered.
 
2313
__default_format = WorkingTreeFormat3()
 
2314
WorkingTreeFormat.register_format(__default_format)
 
2315
WorkingTreeFormat.register_format(WorkingTreeFormat4())
 
2316
WorkingTreeFormat.set_default_format(__default_format)
 
2317
_legacy_formats = [WorkingTreeFormat2(),
 
2318
                   ]
 
2319
 
 
2320
 
 
2321
class WorkingTreeTestProviderAdapter(object):
 
2322
    """A tool to generate a suite testing multiple workingtree formats at once.
 
2323
 
 
2324
    This is done by copying the test once for each transport and injecting
 
2325
    the transport_server, transport_readonly_server, and workingtree_format
 
2326
    classes into each copy. Each copy is also given a new id() to make it
 
2327
    easy to identify.
 
2328
    """
 
2329
 
 
2330
    def __init__(self, transport_server, transport_readonly_server, formats):
 
2331
        self._transport_server = transport_server
 
2332
        self._transport_readonly_server = transport_readonly_server
 
2333
        self._formats = formats
 
2334
    
 
2335
    def _clone_test(self, test, bzrdir_format, workingtree_format, variation):
 
2336
        """Clone test for adaption."""
 
2337
        new_test = deepcopy(test)
 
2338
        new_test.transport_server = self._transport_server
 
2339
        new_test.transport_readonly_server = self._transport_readonly_server
 
2340
        new_test.bzrdir_format = bzrdir_format
 
2341
        new_test.workingtree_format = workingtree_format
 
2342
        def make_new_test_id():
 
2343
            new_id = "%s(%s)" % (test.id(), variation)
 
2344
            return lambda: new_id
 
2345
        new_test.id = make_new_test_id()
 
2346
        return new_test
 
2347
    
 
2348
    def adapt(self, test):
 
2349
        from bzrlib.tests import TestSuite
 
2350
        result = TestSuite()
 
2351
        for workingtree_format, bzrdir_format in self._formats:
 
2352
            new_test = self._clone_test(
 
2353
                test,
 
2354
                bzrdir_format,
 
2355
                workingtree_format, workingtree_format.__class__.__name__)
 
2356
            result.addTest(new_test)
 
2357
        return result