/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-02-16 07:02:19 UTC
  • mfrom: (2292 +trunk)
  • mto: (2255.6.1 dirstate)
  • mto: This revision was merged to the branch mainline in revision 2322.
  • Revision ID: aaron.bentley@utoronto.ca-20070216070219-b22k0gwnisnxawnk
Merged bzr.dev (17 tests failing)

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