/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
1
# Copyright (C) 2005, 2006 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
453 by Martin Pool
- Split WorkingTree into its own file
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
453 by Martin Pool
- Split WorkingTree into its own file
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
453 by Martin Pool
- Split WorkingTree into its own file
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
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
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
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
28
To get a WorkingTree, call bzrdir.open_workingtree() or
29
WorkingTree.open(dir).
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
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.
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
36
# At the moment they may alias the inventory and have old copies of it in
37
# memory.  (Now done? -- mbp 20060309)
956 by Martin Pool
doc
38
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
39
from cStringIO import StringIO
40
import os
41
42
from bzrlib.lazy_import import lazy_import
43
lazy_import(globals(), """
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
44
from bisect import bisect_left
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
45
import collections
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
46
from copy import deepcopy
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
47
import errno
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
48
import itertools
49
import operator
1398 by Robert Collins
integrate in Gustavos x-bit patch
50
import stat
1713.1.6 by Robert Collins
Move file id random data selection out of the inner loop for 'bzr add'.
51
from time import time
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
52
import warnings
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
53
1836.1.21 by John Arbash Meinel
Restore the ability to ignore items by modifying DEFAULT_IGNORE
54
import bzrlib
1731.2.17 by Aaron Bentley
Support extracting with checkouts
55
from bzrlib import (
56
    branch,
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
57
    bzrdir,
58
    conflicts as _mod_conflicts,
1852.13.23 by Robert Collins
Merge up.
59
    dirstate,
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
60
    errors,
2116.4.1 by John Arbash Meinel
Update file and revision id generators.
61
    generate_ids,
2135.2.7 by Kent Gibson
Implement JAM's review suggestions.
62
    globbing,
2201.1.1 by John Arbash Meinel
Fix bug #76299 by ignoring write errors during readonly hashcache write.
63
    hashcache,
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
64
    ignores,
65
    merge,
66
    osutils,
1908.11.5 by John Arbash Meinel
[merge] bzr.dev 2240
67
    revisiontree,
1731.2.17 by Aaron Bentley
Support extracting with checkouts
68
    repository,
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
69
    textui,
70
    transform,
1986.5.2 by Robert Collins
``WorkingTree.set_root_id(None)`` is now deprecated. Please
71
    urlutils,
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
72
    xml5,
1996.3.20 by John Arbash Meinel
[merge] bzr.dev 2063
73
    xml6,
2100.3.10 by Aaron Bentley
Ensure added references are serialized properly, beef up Workingtreee3
74
    xml7,
1731.2.17 by Aaron Bentley
Support extracting with checkouts
75
    )
1852.3.1 by Robert Collins
Trivial cleanups to workingtree.py
76
import bzrlib.branch
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
77
from bzrlib.transport import get_transport
78
import bzrlib.ui
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
79
from bzrlib.workingtree_4 import WorkingTreeFormat4
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
80
""")
81
1986.5.6 by Robert Collins
Merge bzr.dev.
82
from bzrlib import symbol_versioning
1534.4.28 by Robert Collins
first cut at merge from integration.
83
from bzrlib.decorators import needs_read_lock, needs_write_lock
2100.3.8 by Aaron Bentley
Add add_reference
84
from bzrlib.inventory import InventoryEntry, Inventory, ROOT_ID, TreeReference
1553.5.63 by Martin Pool
Lock type is now mandatory for LockableFiles constructor
85
from bzrlib.lockable_files import LockableFiles, TransportLock
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
86
from bzrlib.lockdir import LockDir
1986.1.2 by Robert Collins
Various changes to allow non-workingtree specific tests to run entirely
87
import bzrlib.mutabletree
1986.1.8 by Robert Collins
Update to bzr.dev, which involves adding lock_tree_write to MutableTree and MemoryTree.
88
from bzrlib.mutabletree import needs_tree_write_lock
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
89
from bzrlib.osutils import (
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
90
    compact_date,
91
    file_kind,
92
    isdir,
2206.1.8 by Marius Kruger
Converted move/rename error messages to show source => target.
93
    normpath,
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
94
    pathjoin,
95
    rand_chars,
2206.1.8 by Marius Kruger
Converted move/rename error messages to show source => target.
96
    realpath,
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
97
    safe_unicode,
98
    splitpath,
99
    supports_executable,
100
    )
101
from bzrlib.trace import mutter, note
102
from bzrlib.transport.local import LocalTransport
1551.2.36 by Aaron Bentley
Make pull update the progress bar more nicely
103
from bzrlib.progress import DummyProgress, ProgressPhase
1551.9.16 by Aaron Bentley
Implement Tree.annotate_iter for RevisionTree and WorkingTree
104
from bzrlib.revision import NULL_REVISION, CURRENT_REVISION
1534.10.3 by Aaron Bentley
Simplify set_merge_modified with rio_file
105
from bzrlib.rio import RioReader, rio_file, Stanza
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
106
from bzrlib.symbol_versioning import (deprecated_passed,
107
        deprecated_method,
108
        deprecated_function,
109
        DEPRECATED_PARAMETER,
110
        zero_eight,
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
111
        zero_eleven,
2116.4.1 by John Arbash Meinel
Update file and revision id generators.
112
        zero_thirteen,
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
113
        )
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
114
115
116
MERGE_MODIFIED_HEADER_1 = "BZR merge-modified list format 1"
117
CONFLICT_HEADER_1 = "BZR conflict list format 1"
1685.1.30 by John Arbash Meinel
PEP8 for workingtree.py
118
2116.4.1 by John Arbash Meinel
Update file and revision id generators.
119
120
@deprecated_function(zero_thirteen)
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
121
def gen_file_id(name):
1713.1.6 by Robert Collins
Move file id random data selection out of the inner loop for 'bzr add'.
122
    """Return new file id for the basename 'name'.
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
123
2116.4.1 by John Arbash Meinel
Update file and revision id generators.
124
    Use bzrlib.generate_ids.gen_file_id() instead
1185.85.34 by John Arbash Meinel
Updating 'bzr file-id' exposed that we weren't allowing unicode file ids. Enabling them reveals a lot more bugs.
125
    """
2116.4.1 by John Arbash Meinel
Update file and revision id generators.
126
    return generate_ids.gen_file_id(name)
127
128
129
@deprecated_function(zero_thirteen)
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
130
def gen_root_id():
2116.4.1 by John Arbash Meinel
Update file and revision id generators.
131
    """Return a new tree-root file id.
132
133
    This has been deprecated in favor of bzrlib.generate_ids.gen_root_id()
134
    """
135
    return generate_ids.gen_root_id()
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
136
137
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
138
class TreeEntry(object):
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
139
    """An entry that implements the minimum interface used by commands.
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
140
141
    This needs further inspection, it may be better to have 
142
    InventoryEntries without ids - though that seems wrong. For now,
143
    this is a parallel hierarchy to InventoryEntry, and needs to become
144
    one of several things: decorates to that hierarchy, children of, or
145
    parents of it.
1399.1.3 by Robert Collins
move change detection for text and metadata from delta to entry.detect_changes
146
    Another note is that these objects are currently only used when there is
147
    no InventoryEntry available - i.e. for unversioned objects.
148
    Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
149
    """
150
 
151
    def __eq__(self, other):
152
        # yes, this us ugly, TODO: best practice __eq__ style.
153
        return (isinstance(other, TreeEntry)
154
                and other.__class__ == self.__class__)
155
 
156
    def kind_character(self):
157
        return "???"
158
159
160
class TreeDirectory(TreeEntry):
161
    """See TreeEntry. This is a directory in a working tree."""
162
163
    def __eq__(self, other):
164
        return (isinstance(other, TreeDirectory)
165
                and other.__class__ == self.__class__)
166
167
    def kind_character(self):
168
        return "/"
169
170
171
class TreeFile(TreeEntry):
172
    """See TreeEntry. This is a regular file in a working tree."""
173
174
    def __eq__(self, other):
175
        return (isinstance(other, TreeFile)
176
                and other.__class__ == self.__class__)
177
178
    def kind_character(self):
179
        return ''
180
181
182
class TreeLink(TreeEntry):
183
    """See TreeEntry. This is a symlink in a working tree."""
184
185
    def __eq__(self, other):
186
        return (isinstance(other, TreeLink)
187
                and other.__class__ == self.__class__)
188
189
    def kind_character(self):
190
        return ''
191
192
1986.1.2 by Robert Collins
Various changes to allow non-workingtree specific tests to run entirely
193
class WorkingTree(bzrlib.mutabletree.MutableTree):
453 by Martin Pool
- Split WorkingTree into its own file
194
    """Working copy tree.
195
196
    The inventory is held in the `Branch` working-inventory, and the
197
    files are in a directory on disk.
198
199
    It is possible for a `WorkingTree` to have a filename which is
200
    not listed in the Inventory and vice versa.
201
    """
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
202
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
203
    def __init__(self, basedir='.',
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
204
                 branch=DEPRECATED_PARAMETER,
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
205
                 _inventory=None,
206
                 _control_files=None,
207
                 _internal=False,
208
                 _format=None,
209
                 _bzrdir=None):
1457.1.1 by Robert Collins
rather than getting the branch inventory, WorkingTree can use the whole Branch, or make its own.
210
        """Construct a WorkingTree for basedir.
211
212
        If the branch is not supplied, it is opened automatically.
213
        If the branch is supplied, it must be the branch for this basedir.
214
        (branch.base is not cross checked, because for remote branches that
215
        would be meaningless).
216
        """
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
217
        self._format = _format
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
218
        self.bzrdir = _bzrdir
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
219
        if not _internal:
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
220
            # not created via open etc.
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
221
            warnings.warn("WorkingTree() is deprecated as of bzr version 0.8. "
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
222
                 "Please use bzrdir.open_workingtree or WorkingTree.open().",
223
                 DeprecationWarning,
224
                 stacklevel=2)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
225
            wt = WorkingTree.open(basedir)
1681.1.1 by Robert Collins
Make WorkingTree.branch a read only property. (Robert Collins)
226
            self._branch = wt.branch
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
227
            self.basedir = wt.basedir
228
            self._control_files = wt._control_files
229
            self._hashcache = wt._hashcache
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
230
            self._set_inventory(wt._inventory, dirty=False)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
231
            self._format = wt._format
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
232
            self.bzrdir = wt.bzrdir
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
233
        assert isinstance(basedir, basestring), \
234
            "base directory %r is not a string" % basedir
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
235
        basedir = safe_unicode(basedir)
1534.5.3 by Robert Collins
Make format 4/5/6 branches share a single LockableFiles instance across wt/branch/repository.
236
        mutter("opening working tree %r", basedir)
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
237
        if deprecated_passed(branch):
238
            if not _internal:
2206.1.7 by Marius Kruger
* errors
239
                warnings.warn("WorkingTree(..., branch=XXX) is deprecated"
240
                     " as of bzr 0.8. Please use bzrdir.open_workingtree() or"
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
241
                     " WorkingTree.open().",
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
242
                     DeprecationWarning,
243
                     stacklevel=2
244
                     )
1681.1.1 by Robert Collins
Make WorkingTree.branch a read only property. (Robert Collins)
245
            self._branch = branch
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
246
        else:
1681.1.1 by Robert Collins
Make WorkingTree.branch a read only property. (Robert Collins)
247
            self._branch = self.bzrdir.open_branch()
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
248
        self.basedir = realpath(basedir)
1534.4.28 by Robert Collins
first cut at merge from integration.
249
        # if branch is at our basedir and is a format 6 or less
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
250
        if isinstance(self._format, WorkingTreeFormat2):
251
            # share control object
1534.4.28 by Robert Collins
first cut at merge from integration.
252
            self._control_files = self.branch.control_files
253
        else:
1852.3.1 by Robert Collins
Trivial cleanups to workingtree.py
254
            # assume all other formats have their own control files.
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
255
            assert isinstance(_control_files, LockableFiles), \
256
                    "_control_files must be a LockableFiles, not %r" \
257
                    % _control_files
258
            self._control_files = _control_files
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
259
        # update the whole cache up front and write to disk if anything changed;
260
        # in the future we might want to do this more selectively
1467 by Robert Collins
WorkingTree.__del__ has been removed.
261
        # two possible ways offer themselves : in self._unlock, write the cache
262
        # if needed, or, when the cache sees a change, append it to the hash
263
        # cache file, and have the parser take the most recent entry for a
264
        # given path only.
2220.1.6 by Marius Kruger
* change error message telling user about --after option sightly
265
        wt_trans = self.bzrdir.get_workingtree_transport(None)
266
        cache_filename = wt_trans.local_abspath('stat-cache')
2201.1.1 by John Arbash Meinel
Fix bug #76299 by ignoring write errors during readonly hashcache write.
267
        self._hashcache = hashcache.HashCache(basedir, cache_filename,
268
                                              self._control_files._file_mode)
269
        hc = self._hashcache
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
270
        hc.read()
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
271
        # is this scan needed ? it makes things kinda slow.
1732.1.20 by John Arbash Meinel
hash cache pre-scan cost us ~500ms on a kernel sized tree
272
        #hc.scan()
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
273
274
        if hc.needs_write:
275
            mutter("write hc")
276
            hc.write()
453 by Martin Pool
- Split WorkingTree into its own file
277
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
278
        if _inventory is None:
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
279
            self._inventory_is_modified = False
280
            self.read_working_inventory()
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
281
        else:
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
282
            # the caller of __init__ has provided an inventory,
283
            # we assume they know what they are doing - as its only
284
            # the Format factory and creation methods that are
285
            # permitted to do this.
286
            self._set_inventory(_inventory, dirty=False)
1185.60.6 by Aaron Bentley
Fixed hashcache
287
1681.1.1 by Robert Collins
Make WorkingTree.branch a read only property. (Robert Collins)
288
    branch = property(
289
        fget=lambda self: self._branch,
290
        doc="""The branch this WorkingTree is connected to.
291
292
            This cannot be set - it is reflective of the actual disk structure
293
            the working tree has been constructed from.
294
            """)
295
1687.1.9 by Robert Collins
Teach WorkingTree about break-lock.
296
    def break_lock(self):
297
        """Break a lock if one is present from another instance.
298
299
        Uses the ui factory to ask for confirmation if the lock may be from
300
        an active process.
301
302
        This will probe the repository for its lock as well.
303
        """
304
        self._control_files.break_lock()
305
        self.branch.break_lock()
306
2100.3.14 by Aaron Bentley
Test workingtree4 format, prevent use with old repos
307
    def requires_rich_root(self):
308
        return self._format.requires_rich_root
309
2100.3.20 by Aaron Bentley
Implement tree comparison for tree references
310
    def supports_tree_reference(self):
311
        return getattr(self._format, 'supports_tree_reference', False)
312
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
313
    def _set_inventory(self, inv, dirty):
314
        """Set the internal cached inventory.
315
316
        :param inv: The inventory to set.
317
        :param dirty: A boolean indicating whether the inventory is the same
318
            logical inventory as whats on disk. If True the inventory is not
319
            the same and should be written to disk or data will be lost, if
320
            False then the inventory is the same as that on disk and any
321
            serialisation would be unneeded overhead.
322
        """
1910.2.6 by Aaron Bentley
Update for merge review, handle deprecations
323
        assert inv.root is not None
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
324
        self._inventory = inv
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
325
        self._inventory_is_modified = dirty
1534.5.5 by Robert Collins
Move is_control_file into WorkingTree.is_control_filename and test.
326
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
327
    @staticmethod
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
328
    def open(path=None, _unsupported=False):
329
        """Open an existing working tree at path.
330
331
        """
332
        if path is None:
333
            path = os.path.getcwdu()
334
        control = bzrdir.BzrDir.open(path, _unsupported)
335
        return control.open_workingtree(_unsupported)
336
        
337
    @staticmethod
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
338
    def open_containing(path=None):
339
        """Open an existing working tree which has its root about path.
340
        
341
        This probes for a working tree at path and searches upwards from there.
342
343
        Basically we keep looking up until we find the control directory or
344
        run into /.  If there isn't one, raises NotBranchError.
345
        TODO: give this a new exception.
346
        If there is one, it is returned, along with the unused portion of path.
1685.1.27 by John Arbash Meinel
BzrDir works in URLs, but WorkingTree works in unicode paths
347
348
        :return: The WorkingTree that contains 'path', and the rest of path
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
349
        """
350
        if path is None:
1830.3.14 by John Arbash Meinel
WorkingTree.open_containing() was directly calling os.getcwdu(), which on mac returns the wrong normalization, and on win32 would have the wrong slashes
351
            path = osutils.getcwd()
1685.1.28 by John Arbash Meinel
Changing open_containing to always return a unicode path.
352
        control, relpath = bzrdir.BzrDir.open_containing(path)
1685.1.27 by John Arbash Meinel
BzrDir works in URLs, but WorkingTree works in unicode paths
353
1685.1.28 by John Arbash Meinel
Changing open_containing to always return a unicode path.
354
        return control.open_workingtree(), relpath
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
355
356
    @staticmethod
357
    def open_downlevel(path=None):
358
        """Open an unsupported working tree.
359
360
        Only intended for advanced situations like upgrading part of a bzrdir.
361
        """
362
        return WorkingTree.open(path, _unsupported=True)
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
363
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
364
    def __iter__(self):
365
        """Iterate through file_ids for this tree.
366
367
        file_ids are in a WorkingTree if they are in the working inventory
368
        and the working file exists.
369
        """
370
        inv = self._inventory
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
371
        for path, ie in inv.iter_entries():
1836.1.22 by John Arbash Meinel
[merge] bzr.dev 1861
372
            if osutils.lexists(self.abspath(path)):
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
373
                yield ie.file_id
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
374
453 by Martin Pool
- Split WorkingTree into its own file
375
    def __repr__(self):
376
        return "<%s of %s>" % (self.__class__.__name__,
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
377
                               getattr(self, 'basedir', None))
453 by Martin Pool
- Split WorkingTree into its own file
378
379
    def abspath(self, filename):
1185.31.32 by John Arbash Meinel
Updated the bzr sourcecode to use bzrlib.osutils.pathjoin rather than os.path.join to enforce internal use of / instead of \
380
        return pathjoin(self.basedir, filename)
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
381
    
382
    def basis_tree(self):
1927.2.3 by Robert Collins
review comment application - paired with Martin.
383
        """Return RevisionTree for the current last revision.
384
        
385
        If the left most parent is a ghost then the returned tree will be an
386
        empty tree - one obtained by calling repository.revision_tree(None).
387
        """
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
388
        try:
389
            revision_id = self.get_parent_ids()[0]
390
        except IndexError:
391
            # no parents, return an empty revision tree.
392
            # in the future this should return the tree for
393
            # 'empty:' - the implicit root empty tree.
394
            return self.branch.repository.revision_tree(None)
1908.11.2 by Robert Collins
Implement WorkingTree interface conformance tests for
395
        try:
396
            return self.revision_tree(revision_id)
397
        except errors.NoSuchRevision:
398
            pass
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
399
        # No cached copy available, retrieve from the repository.
400
        # FIXME? RBC 20060403 should we cache the inventory locally
401
        # at this point ?
1927.2.1 by Robert Collins
Alter set_pending_merges to shove the left most merge into the trees last-revision if that is not set. Related bugfixes include basis_tree handling ghosts, de-duping the merges with the last-revision and update changing where and how it adds its pending merge.
402
        try:
403
            return self.branch.repository.revision_tree(revision_id)
404
        except errors.RevisionNotPresent:
405
            # the basis tree *may* be a ghost or a low level error may have
406
            # occured. If the revision is present, its a problem, if its not
407
            # its a ghost.
408
            if self.branch.repository.has_revision(revision_id):
409
                raise
1927.2.3 by Robert Collins
review comment application - paired with Martin.
410
            # the basis tree is a ghost so return an empty tree.
1927.2.1 by Robert Collins
Alter set_pending_merges to shove the left most merge into the trees last-revision if that is not set. Related bugfixes include basis_tree handling ghosts, de-duping the merges with the last-revision and update changing where and how it adds its pending merge.
411
            return self.branch.repository.revision_tree(None)
453 by Martin Pool
- Split WorkingTree into its own file
412
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
413
    @staticmethod
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
414
    @deprecated_method(zero_eight)
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
415
    def create(branch, directory):
416
        """Create a workingtree for branch at directory.
417
418
        If existing_directory already exists it must have a .bzr directory.
419
        If it does not exist, it will be created.
420
421
        This returns a new WorkingTree object for the new checkout.
422
423
        TODO FIXME RBC 20060124 when we have checkout formats in place this
424
        should accept an optional revisionid to checkout [and reject this if
425
        checking out into the same dir as a pre-checkout-aware branch format.]
1551.1.2 by Martin Pool
Deprecation warnings for popular APIs that will change in BzrDir
426
427
        XXX: When BzrDir is present, these should be created through that 
428
        interface instead.
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
429
        """
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
430
        warnings.warn('delete WorkingTree.create', stacklevel=3)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
431
        transport = get_transport(directory)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
432
        if branch.bzrdir.root_transport.base == transport.base:
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
433
            # same dir 
434
            return branch.bzrdir.create_workingtree()
435
        # different directory, 
436
        # create a branch reference
437
        # and now a working tree.
438
        raise NotImplementedError
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
439
 
440
    @staticmethod
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
441
    @deprecated_method(zero_eight)
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
442
    def create_standalone(directory):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
443
        """Create a checkout and a branch and a repo at directory.
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
444
445
        Directory must exist and be empty.
1551.1.2 by Martin Pool
Deprecation warnings for popular APIs that will change in BzrDir
446
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
447
        please use BzrDir.create_standalone_workingtree
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
448
        """
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
449
        return bzrdir.BzrDir.create_standalone_workingtree(directory)
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
450
1713.1.9 by Robert Collins
Paired performance tuning of bzr add. (Robert Collins, Martin Pool).
451
    def relpath(self, path):
452
        """Return the local path portion from a given path.
453
        
454
        The path may be absolute or relative. If its a relative path it is 
455
        interpreted relative to the python current working directory.
456
        """
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
457
        return osutils.relpath(self.basedir, path)
1457.1.3 by Robert Collins
make Branch.relpath delegate to the working tree.
458
453 by Martin Pool
- Split WorkingTree into its own file
459
    def has_filename(self, filename):
1836.1.22 by John Arbash Meinel
[merge] bzr.dev 1861
460
        return osutils.lexists(self.abspath(filename))
453 by Martin Pool
- Split WorkingTree into its own file
461
462
    def get_file(self, file_id):
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
463
        file_id = osutils.safe_file_id(file_id)
453 by Martin Pool
- Split WorkingTree into its own file
464
        return self.get_file_byname(self.id2path(file_id))
465
1852.6.9 by Robert Collins
Add more test trees to the tree-implementations tests.
466
    def get_file_text(self, file_id):
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
467
        file_id = osutils.safe_file_id(file_id)
1852.6.9 by Robert Collins
Add more test trees to the tree-implementations tests.
468
        return self.get_file(file_id).read()
469
453 by Martin Pool
- Split WorkingTree into its own file
470
    def get_file_byname(self, filename):
471
        return file(self.abspath(filename), 'rb')
472
2255.2.18 by Robert Collins
Dirstate: all tree_implementation tests passing.
473
    @needs_read_lock
1551.9.16 by Aaron Bentley
Implement Tree.annotate_iter for RevisionTree and WorkingTree
474
    def annotate_iter(self, file_id):
475
        """See Tree.annotate_iter
476
477
        This implementation will use the basis tree implementation if possible.
478
        Lines not in the basis are attributed to CURRENT_REVISION
479
480
        If there are pending merges, lines added by those merges will be
481
        incorrectly attributed to CURRENT_REVISION (but after committing, the
482
        attribution will be correct).
483
        """
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
484
        file_id = osutils.safe_file_id(file_id)
1551.9.16 by Aaron Bentley
Implement Tree.annotate_iter for RevisionTree and WorkingTree
485
        basis = self.basis_tree()
486
        changes = self._iter_changes(basis, True, [file_id]).next()
487
        changed_content, kind = changes[2], changes[6]
488
        if not changed_content:
489
            return basis.annotate_iter(file_id)
490
        if kind[1] is None:
491
            return None
492
        import annotate
493
        if kind[0] != 'file':
494
            old_lines = []
495
        else:
496
            old_lines = list(basis.annotate_iter(file_id))
1551.9.17 by Aaron Bentley
Annotate for working trees across all parents
497
        old = [old_lines]
498
        for tree in self.branch.repository.revision_trees(
499
            self.get_parent_ids()[1:]):
500
            if file_id not in tree:
501
                continue
502
            old.append(list(tree.annotate_iter(file_id)))
503
        return annotate.reannotate(old, self.get_file(file_id).readlines(),
1551.9.16 by Aaron Bentley
Implement Tree.annotate_iter for RevisionTree and WorkingTree
504
                                   CURRENT_REVISION)
1551.9.18 by Aaron Bentley
Updates from review comments
505
1773.2.1 by Robert Collins
Teach all trees about unknowns, conflicts and get_parent_ids.
506
    def get_parent_ids(self):
507
        """See Tree.get_parent_ids.
508
        
509
        This implementation reads the pending merges list and last_revision
510
        value and uses that to decide what the parents list should be.
511
        """
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
512
        last_rev = self._last_revision()
1773.2.1 by Robert Collins
Teach all trees about unknowns, conflicts and get_parent_ids.
513
        if last_rev is None:
514
            parents = []
515
        else:
516
            parents = [last_rev]
1908.6.10 by Robert Collins
forward to get_parent_ids in pending_merges.
517
        try:
2249.5.7 by John Arbash Meinel
Make sure WorkingTree revision_ids are also returned as utf8 strings
518
            merges_file = self._control_files.get('pending-merges')
2206.1.7 by Marius Kruger
* errors
519
        except errors.NoSuchFile:
1908.6.10 by Robert Collins
forward to get_parent_ids in pending_merges.
520
            pass
521
        else:
522
            for l in merges_file.readlines():
2249.5.9 by John Arbash Meinel
Update WorkingTree to use safe_revision_id when appropriate
523
                revision_id = osutils.safe_revision_id(l.rstrip('\n'))
524
                parents.append(revision_id)
1908.6.10 by Robert Collins
forward to get_parent_ids in pending_merges.
525
        return parents
1773.2.1 by Robert Collins
Teach all trees about unknowns, conflicts and get_parent_ids.
526
1986.5.1 by Robert Collins
(Robert Collins, John Meinel) Change WorkingTree.get_root_id to not trigger read_working_inventory and instead use the one inside the current transaction.
527
    @needs_read_lock
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
528
    def get_root_id(self):
529
        """Return the id of this trees root"""
1986.5.1 by Robert Collins
(Robert Collins, John Meinel) Change WorkingTree.get_root_id to not trigger read_working_inventory and instead use the one inside the current transaction.
530
        return self._inventory.root.file_id
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
531
        
453 by Martin Pool
- Split WorkingTree into its own file
532
    def _get_store_filename(self, file_id):
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
533
        ## XXX: badly named; this is not in the store at all
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
534
        file_id = osutils.safe_file_id(file_id)
453 by Martin Pool
- Split WorkingTree into its own file
535
        return self.abspath(self.id2path(file_id))
536
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
537
    @needs_read_lock
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
538
    def clone(self, to_bzrdir, revision_id=None, basis=None):
539
        """Duplicate this working tree into to_bzr, including all state.
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
540
        
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
541
        Specifically modified files are kept as modified, but
542
        ignored and unknown files are discarded.
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
543
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
544
        If you want to make a new line of development, see bzrdir.sprout()
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
545
546
        revision
547
            If not None, the cloned tree will have its last revision set to 
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
548
            revision, and and difference between the source trees last revision
549
            and this one merged in.
550
551
        basis
552
            If not None, a closer copy of a tree which may have some files in
553
            common, and which file content should be preferentially copied from.
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
554
        """
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
555
        # assumes the target bzr dir format is compatible.
556
        result = self._format.initialize(to_bzrdir)
557
        self.copy_content_into(result, revision_id)
558
        return result
559
560
    @needs_read_lock
561
    def copy_content_into(self, tree, revision_id=None):
562
        """Copy the current content and user files of this tree into tree."""
1731.1.33 by Aaron Bentley
Revert no-special-root changes
563
        tree.set_root_id(self.get_root_id())
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
564
        if revision_id is None:
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
565
            merge.transform_tree(tree, self)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
566
        else:
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
567
            # TODO now merge from tree.last_revision to revision (to preserve
568
            # user local changes)
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
569
            merge.transform_tree(tree, self)
1908.6.3 by Robert Collins
Tidy up the last_revision_id and add_pending_merge conversion to use cleaner apis.
570
            tree.set_parent_ids([revision_id])
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
571
1248 by Martin Pool
- new weave based cleanup [broken]
572
    def id2abspath(self, file_id):
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
573
        file_id = osutils.safe_file_id(file_id)
1248 by Martin Pool
- new weave based cleanup [broken]
574
        return self.abspath(self.id2path(file_id))
575
1185.12.39 by abentley
Propogated has_or_had_id to Tree
576
    def has_id(self, file_id):
453 by Martin Pool
- Split WorkingTree into its own file
577
        # files that have been deleted are excluded
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
578
        file_id = osutils.safe_file_id(file_id)
2255.2.82 by Robert Collins
various notes about find_ids_across_trees
579
        inv = self.inventory
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
580
        if not inv.has_id(file_id):
453 by Martin Pool
- Split WorkingTree into its own file
581
            return False
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
582
        path = inv.id2path(file_id)
1836.1.22 by John Arbash Meinel
[merge] bzr.dev 1861
583
        return osutils.lexists(self.abspath(path))
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
584
1185.12.39 by abentley
Propogated has_or_had_id to Tree
585
    def has_or_had_id(self, file_id):
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
586
        file_id = osutils.safe_file_id(file_id)
1185.12.39 by abentley
Propogated has_or_had_id to Tree
587
        if file_id == self.inventory.root.file_id:
588
            return True
589
        return self.inventory.has_id(file_id)
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
590
591
    __contains__ = has_id
592
453 by Martin Pool
- Split WorkingTree into its own file
593
    def get_file_size(self, file_id):
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
594
        file_id = osutils.safe_file_id(file_id)
1248 by Martin Pool
- new weave based cleanup [broken]
595
        return os.path.getsize(self.id2abspath(file_id))
453 by Martin Pool
- Split WorkingTree into its own file
596
1185.60.6 by Aaron Bentley
Fixed hashcache
597
    @needs_read_lock
2012.1.7 by Aaron Bentley
Get tree._iter_changed down to ~ 1 stat per file
598
    def get_file_sha1(self, file_id, path=None, stat_value=None):
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
599
        file_id = osutils.safe_file_id(file_id)
1732.1.19 by John Arbash Meinel
If you have the path, use it rather than looking it up again
600
        if not path:
601
            path = self._inventory.id2path(file_id)
2012.1.7 by Aaron Bentley
Get tree._iter_changed down to ~ 1 stat per file
602
        return self._hashcache.get_sha1(path, stat_value)
453 by Martin Pool
- Split WorkingTree into its own file
603
1740.2.5 by Aaron Bentley
Merge from bzr.dev
604
    def get_file_mtime(self, file_id, path=None):
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
605
        file_id = osutils.safe_file_id(file_id)
1740.2.5 by Aaron Bentley
Merge from bzr.dev
606
        if not path:
607
            path = self._inventory.id2path(file_id)
608
        return os.lstat(self.abspath(path)).st_mtime
609
1732.1.19 by John Arbash Meinel
If you have the path, use it rather than looking it up again
610
    if not supports_executable():
611
        def is_executable(self, file_id, path=None):
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
612
            file_id = osutils.safe_file_id(file_id)
1398 by Robert Collins
integrate in Gustavos x-bit patch
613
            return self._inventory[file_id].executable
1732.1.19 by John Arbash Meinel
If you have the path, use it rather than looking it up again
614
    else:
615
        def is_executable(self, file_id, path=None):
616
            if not path:
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
617
                file_id = osutils.safe_file_id(file_id)
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
618
                path = self.id2path(file_id)
1398 by Robert Collins
integrate in Gustavos x-bit patch
619
            mode = os.lstat(self.abspath(path)).st_mode
1733.1.4 by Robert Collins
Cosmetic niceties for debugging, extra comments etc.
620
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1398 by Robert Collins
integrate in Gustavos x-bit patch
621
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
622
    @needs_write_lock
1986.1.2 by Robert Collins
Various changes to allow non-workingtree specific tests to run entirely
623
    def _add(self, files, ids, kinds):
624
        """See MutableTree._add."""
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
625
        # TODO: Re-adding a file that is removed in the working copy
626
        # should probably put it back with the previous ID.
1986.1.2 by Robert Collins
Various changes to allow non-workingtree specific tests to run entirely
627
        # the read and write working inventory should not occur in this 
628
        # function - they should be part of lock_write and unlock.
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
629
        inv = self.read_working_inventory()
1986.1.2 by Robert Collins
Various changes to allow non-workingtree specific tests to run entirely
630
        for f, file_id, kind in zip(files, ids, kinds):
631
            assert kind is not None
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
632
            if file_id is None:
1713.1.6 by Robert Collins
Move file id random data selection out of the inner loop for 'bzr add'.
633
                inv.add_path(f, kind=kind)
634
            else:
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
635
                file_id = osutils.safe_file_id(file_id)
1713.1.6 by Robert Collins
Move file id random data selection out of the inner loop for 'bzr add'.
636
                inv.add_path(f, kind=kind, file_id=file_id)
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
637
        self._write_inventory(inv)
638
2100.3.8 by Aaron Bentley
Add add_reference
639
    def add_reference(self, sub_tree):
640
        """Add a TreeReference to the tree, pointing at sub_tree"""
2100.3.22 by Aaron Bentley
merge from bzr.dev
641
        raise errors.UnsupportedOperation(self.add_reference, self)
2100.3.8 by Aaron Bentley
Add add_reference
642
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
643
    @needs_tree_write_lock
1986.1.2 by Robert Collins
Various changes to allow non-workingtree specific tests to run entirely
644
    def _gather_kinds(self, files, kinds):
645
        """See MutableTree._gather_kinds."""
646
        for pos, f in enumerate(files):
647
            if kinds[pos] is None:
648
                fullpath = normpath(self.abspath(f))
649
                try:
650
                    kinds[pos] = file_kind(fullpath)
651
                except OSError, e:
652
                    if e.errno == errno.ENOENT:
2206.1.7 by Marius Kruger
* errors
653
                        raise errors.NoSuchFile(fullpath)
1986.1.2 by Robert Collins
Various changes to allow non-workingtree specific tests to run entirely
654
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
655
    @needs_write_lock
1908.5.9 by Robert Collins
Add a guard against setting the tree last-revision value to a ghost in the new tree parent management api.
656
    def add_parent_tree_id(self, revision_id, allow_leftmost_as_ghost=False):
1908.5.4 by Robert Collins
Add add_parent_tree_id WorkingTree helper api.
657
        """Add revision_id as a parent.
658
659
        This is equivalent to retrieving the current list of parent ids
660
        and setting the list to its value plus revision_id.
661
662
        :param revision_id: The revision id to add to the parent list. It may
1908.5.12 by Robert Collins
Apply review feedback - paired with Martin.
663
        be a ghost revision as long as its not the first parent to be added,
664
        or the allow_leftmost_as_ghost parameter is set True.
665
        :param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
1908.5.4 by Robert Collins
Add add_parent_tree_id WorkingTree helper api.
666
        """
1908.5.13 by Robert Collins
Adding a parent when the first is a ghost already should not require forcing it.
667
        parents = self.get_parent_ids() + [revision_id]
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
668
        self.set_parent_ids(parents, allow_leftmost_as_ghost=len(parents) > 1
2206.1.7 by Marius Kruger
* errors
669
            or allow_leftmost_as_ghost)
1908.5.4 by Robert Collins
Add add_parent_tree_id WorkingTree helper api.
670
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
671
    @needs_tree_write_lock
1908.5.9 by Robert Collins
Add a guard against setting the tree last-revision value to a ghost in the new tree parent management api.
672
    def add_parent_tree(self, parent_tuple, allow_leftmost_as_ghost=False):
1908.5.6 by Robert Collins
Add add_parent_tree to WorkingTree.
673
        """Add revision_id, tree tuple as a parent.
674
675
        This is equivalent to retrieving the current list of parent trees
676
        and setting the list to its value plus parent_tuple. See also
677
        add_parent_tree_id - if you only have a parent id available it will be
678
        simpler to use that api. If you have the parent already available, using
679
        this api is preferred.
680
1908.5.12 by Robert Collins
Apply review feedback - paired with Martin.
681
        :param parent_tuple: The (revision id, tree) to add to the parent list.
682
            If the revision_id is a ghost, pass None for the tree.
683
        :param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
1908.5.6 by Robert Collins
Add add_parent_tree to WorkingTree.
684
        """
1979.2.1 by Robert Collins
(robertc) adds a convenience method "merge_from_branch" to WorkingTree.
685
        parent_ids = self.get_parent_ids() + [parent_tuple[0]]
686
        if len(parent_ids) > 1:
687
            # the leftmost may have already been a ghost, preserve that if it
688
            # was.
689
            allow_leftmost_as_ghost = True
690
        self.set_parent_ids(parent_ids,
1908.5.9 by Robert Collins
Add a guard against setting the tree last-revision value to a ghost in the new tree parent management api.
691
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
1908.5.6 by Robert Collins
Add add_parent_tree to WorkingTree.
692
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
693
    @needs_tree_write_lock
1457.1.15 by Robert Collins
Move add_pending_merge to WorkingTree.
694
    def add_pending_merge(self, *revision_ids):
695
        # TODO: Perhaps should check at this point that the
696
        # history of the revision is actually present?
1908.6.7 by Robert Collins
Remove all users of set_pending_merges and add_pending_merge except tests that they work correctly.
697
        parents = self.get_parent_ids()
1457.1.15 by Robert Collins
Move add_pending_merge to WorkingTree.
698
        updated = False
699
        for rev_id in revision_ids:
1908.6.7 by Robert Collins
Remove all users of set_pending_merges and add_pending_merge except tests that they work correctly.
700
            if rev_id in parents:
701
                continue
702
            parents.append(rev_id)
1457.1.15 by Robert Collins
Move add_pending_merge to WorkingTree.
703
            updated = True
704
        if updated:
1908.6.7 by Robert Collins
Remove all users of set_pending_merges and add_pending_merge except tests that they work correctly.
705
            self.set_parent_ids(parents, allow_leftmost_as_ghost=True)
1457.1.15 by Robert Collins
Move add_pending_merge to WorkingTree.
706
1908.7.7 by Robert Collins
Deprecated WorkingTree.pending_merges.
707
    @deprecated_method(zero_eleven)
1185.69.2 by John Arbash Meinel
Changed LockableFiles to take the root directory directly. Moved mode information into LockableFiles instead of Branch
708
    @needs_read_lock
1457.1.14 by Robert Collins
Move pending_merges() to WorkingTree.
709
    def pending_merges(self):
710
        """Return a list of pending merges.
711
712
        These are revisions that have been merged into the working
713
        directory but not yet committed.
1908.7.9 by Robert Collins
WorkingTree.last_revision and WorkingTree.pending_merges are deprecated.
714
715
        As of 0.11 this is deprecated. Please see WorkingTree.get_parent_ids()
716
        instead - which is available on all tree objects.
1457.1.14 by Robert Collins
Move pending_merges() to WorkingTree.
717
        """
1908.6.10 by Robert Collins
forward to get_parent_ids in pending_merges.
718
        return self.get_parent_ids()[1:]
1457.1.14 by Robert Collins
Move pending_merges() to WorkingTree.
719
2041.1.2 by John Arbash Meinel
Update WorkingTree.set_parent_trees() to directly cache inv.
720
    def _check_parents_for_ghosts(self, revision_ids, allow_leftmost_as_ghost):
721
        """Common ghost checking functionality from set_parent_*.
722
723
        This checks that the left hand-parent exists if there are any
724
        revisions present.
725
        """
726
        if len(revision_ids) > 0:
727
            leftmost_id = revision_ids[0]
728
            if (not allow_leftmost_as_ghost and not
729
                self.branch.repository.has_revision(leftmost_id)):
730
                raise errors.GhostRevisionUnusableHere(leftmost_id)
731
732
    def _set_merges_from_parent_ids(self, parent_ids):
733
        merges = parent_ids[1:]
2294.1.2 by John Arbash Meinel
Track down and add tests that all tree.commit() can handle
734
        self._control_files.put_bytes('pending-merges', '\n'.join(merges))
2041.1.2 by John Arbash Meinel
Update WorkingTree.set_parent_trees() to directly cache inv.
735
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
736
    @needs_tree_write_lock
1908.5.9 by Robert Collins
Add a guard against setting the tree last-revision value to a ghost in the new tree parent management api.
737
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
1908.5.5 by Robert Collins
Add WorkingTree.set_parent_ids.
738
        """Set the parent ids to revision_ids.
739
        
740
        See also set_parent_trees. This api will try to retrieve the tree data
741
        for each element of revision_ids from the trees repository. If you have
742
        tree data already available, it is more efficient to use
743
        set_parent_trees rather than set_parent_ids. set_parent_ids is however
744
        an easier API to use.
745
746
        :param revision_ids: The revision_ids to set as the parent ids of this
747
            working tree. Any of these may be ghosts.
748
        """
2249.5.9 by John Arbash Meinel
Update WorkingTree to use safe_revision_id when appropriate
749
        revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
2041.1.2 by John Arbash Meinel
Update WorkingTree.set_parent_trees() to directly cache inv.
750
        self._check_parents_for_ghosts(revision_ids,
751
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
752
1908.6.7 by Robert Collins
Remove all users of set_pending_merges and add_pending_merge except tests that they work correctly.
753
        if len(revision_ids) > 0:
2041.1.2 by John Arbash Meinel
Update WorkingTree.set_parent_trees() to directly cache inv.
754
            self.set_last_revision(revision_ids[0])
1908.6.7 by Robert Collins
Remove all users of set_pending_merges and add_pending_merge except tests that they work correctly.
755
        else:
756
            self.set_last_revision(None)
2041.1.2 by John Arbash Meinel
Update WorkingTree.set_parent_trees() to directly cache inv.
757
758
        self._set_merges_from_parent_ids(revision_ids)
1908.5.5 by Robert Collins
Add WorkingTree.set_parent_ids.
759
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
760
    @needs_tree_write_lock
1908.5.9 by Robert Collins
Add a guard against setting the tree last-revision value to a ghost in the new tree parent management api.
761
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
1986.1.2 by Robert Collins
Various changes to allow non-workingtree specific tests to run entirely
762
        """See MutableTree.set_parent_trees."""
2249.5.9 by John Arbash Meinel
Update WorkingTree to use safe_revision_id when appropriate
763
        parent_ids = [osutils.safe_revision_id(rev) for (rev, tree) in parents_list]
2041.1.2 by John Arbash Meinel
Update WorkingTree.set_parent_trees() to directly cache inv.
764
765
        self._check_parents_for_ghosts(parent_ids,
1908.6.7 by Robert Collins
Remove all users of set_pending_merges and add_pending_merge except tests that they work correctly.
766
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
1908.5.2 by Robert Collins
Create and test set_parent_trees.
767
2041.1.2 by John Arbash Meinel
Update WorkingTree.set_parent_trees() to directly cache inv.
768
        if len(parent_ids) == 0:
2041.1.3 by John Arbash Meinel
Call _cache_basis_inventory directly rather than set_last_revision
769
            leftmost_parent_id = None
770
            leftmost_parent_tree = None
2041.1.2 by John Arbash Meinel
Update WorkingTree.set_parent_trees() to directly cache inv.
771
        else:
772
            leftmost_parent_id, leftmost_parent_tree = parents_list[0]
773
2041.1.3 by John Arbash Meinel
Call _cache_basis_inventory directly rather than set_last_revision
774
        if self._change_last_revision(leftmost_parent_id):
775
            if leftmost_parent_tree is None:
2041.1.4 by John Arbash Meinel
NEWS and documentation
776
                # If we don't have a tree, fall back to reading the
777
                # parent tree from the repository.
2041.1.3 by John Arbash Meinel
Call _cache_basis_inventory directly rather than set_last_revision
778
                self._cache_basis_inventory(leftmost_parent_id)
779
            else:
2041.1.2 by John Arbash Meinel
Update WorkingTree.set_parent_trees() to directly cache inv.
780
                inv = leftmost_parent_tree.inventory
781
                xml = self._create_basis_xml_from_inventory(
782
                                        leftmost_parent_id, inv)
783
                self._write_basis_inventory(xml)
784
        self._set_merges_from_parent_ids(parent_ids)
785
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
786
    @needs_tree_write_lock
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
787
    def set_pending_merges(self, rev_list):
1908.6.7 by Robert Collins
Remove all users of set_pending_merges and add_pending_merge except tests that they work correctly.
788
        parents = self.get_parent_ids()
789
        leftmost = parents[:1]
790
        new_parents = leftmost + rev_list
791
        self.set_parent_ids(new_parents)
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
792
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
793
    @needs_tree_write_lock
1534.7.192 by Aaron Bentley
Record hashes produced by merges
794
    def set_merge_modified(self, modified_hashes):
1534.10.3 by Aaron Bentley
Simplify set_merge_modified with rio_file
795
        def iter_stanzas():
796
            for file_id, hash in modified_hashes.iteritems():
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
797
                yield Stanza(file_id=file_id.decode('utf8'), hash=hash)
1534.10.3 by Aaron Bentley
Simplify set_merge_modified with rio_file
798
        self._put_rio('merge-hashes', iter_stanzas(), MERGE_MODIFIED_HEADER_1)
799
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
800
    @needs_tree_write_lock
1534.10.3 by Aaron Bentley
Simplify set_merge_modified with rio_file
801
    def _put_rio(self, filename, stanzas, header):
802
        my_file = rio_file(stanzas, header)
803
        self._control_files.put(filename, my_file)
1534.7.192 by Aaron Bentley
Record hashes produced by merges
804
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
805
    @needs_write_lock # because merge pulls data into the branch.
1979.2.1 by Robert Collins
(robertc) adds a convenience method "merge_from_branch" to WorkingTree.
806
    def merge_from_branch(self, branch, to_revision=None):
807
        """Merge from a branch into this working tree.
808
809
        :param branch: The branch to merge from.
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
810
        :param to_revision: If non-None, the merge will merge to to_revision,
811
            but not beyond it. to_revision does not need to be in the history
2206.1.7 by Marius Kruger
* errors
812
            of the branch when it is supplied. If None, to_revision defaults to
1979.2.1 by Robert Collins
(robertc) adds a convenience method "merge_from_branch" to WorkingTree.
813
            branch.last_revision().
814
        """
815
        from bzrlib.merge import Merger, Merge3Merger
816
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
817
        try:
818
            merger = Merger(self.branch, this_tree=self, pb=pb)
819
            merger.pp = ProgressPhase("Merge phase", 5, pb)
820
            merger.pp.next_phase()
821
            # check that there are no
822
            # local alterations
823
            merger.check_basis(check_clean=True, require_commits=False)
824
            if to_revision is None:
825
                to_revision = branch.last_revision()
2249.5.9 by John Arbash Meinel
Update WorkingTree to use safe_revision_id when appropriate
826
            else:
827
                to_revision = osutils.safe_revision_id(to_revision)
1979.2.1 by Robert Collins
(robertc) adds a convenience method "merge_from_branch" to WorkingTree.
828
            merger.other_rev_id = to_revision
829
            if merger.other_rev_id is None:
830
                raise error.NoCommits(branch)
831
            self.branch.fetch(branch, last_revision=merger.other_rev_id)
832
            merger.other_basis = merger.other_rev_id
833
            merger.other_tree = self.branch.repository.revision_tree(
834
                merger.other_rev_id)
2100.3.29 by Aaron Bentley
Get merge working initially
835
            merger.other_branch = branch
1979.2.1 by Robert Collins
(robertc) adds a convenience method "merge_from_branch" to WorkingTree.
836
            merger.pp.next_phase()
837
            merger.find_base()
838
            if merger.base_rev_id == merger.other_rev_id:
839
                raise errors.PointlessMerge
840
            merger.backup_files = False
841
            merger.merge_type = Merge3Merger
842
            merger.set_interesting_files(None)
843
            merger.show_base = False
844
            merger.reprocess = False
845
            conflicts = merger.do_merge()
846
            merger.set_pending()
847
        finally:
848
            pb.finished()
849
        return conflicts
850
1731.2.1 by Aaron Bentley
Initial subsume implementation
851
    @needs_write_lock
852
    def subsume(self, other_tree):
1731.2.4 by Aaron Bentley
Ensure subsume works with Knit2 repos
853
        def add_children(inventory, entry):
854
            for child_entry in entry.children.values():
855
                inventory._byid[child_entry.file_id] = child_entry
856
                if child_entry.kind == 'directory':
857
                    add_children(inventory, child_entry)
1731.2.2 by Aaron Bentley
Test subsume failure modes
858
        if other_tree.get_root_id() == self.get_root_id():
1731.2.5 by Aaron Bentley
Ensure versionedfile will be produced for subsumed tree root
859
            raise errors.BadSubsumeSource(self, other_tree, 
1731.2.2 by Aaron Bentley
Test subsume failure modes
860
                                          'Trees have the same root')
861
        try:
862
            other_tree_path = self.relpath(other_tree.basedir)
863
        except errors.PathNotChild:
1731.2.5 by Aaron Bentley
Ensure versionedfile will be produced for subsumed tree root
864
            raise errors.BadSubsumeSource(self, other_tree, 
1731.2.2 by Aaron Bentley
Test subsume failure modes
865
                'Tree is not contained by the other')
1731.2.4 by Aaron Bentley
Ensure subsume works with Knit2 repos
866
        new_root_parent = self.path2id(osutils.dirname(other_tree_path))
867
        if new_root_parent is None:
1731.2.5 by Aaron Bentley
Ensure versionedfile will be produced for subsumed tree root
868
            raise errors.BadSubsumeSource(self, other_tree, 
1731.2.3 by Aaron Bentley
Handle unversioned parents during subsume
869
                'Parent directory is not versioned.')
1731.2.5 by Aaron Bentley
Ensure versionedfile will be produced for subsumed tree root
870
        # We need to ensure that the result of a fetch will have a
871
        # versionedfile for the other_tree root, and only fetching into
872
        # RepositoryKnit2 guarantees that.
1731.2.10 by Aaron Bentley
Change test for rich root data
873
        if not self.branch.repository.supports_rich_root():
1731.2.5 by Aaron Bentley
Ensure versionedfile will be produced for subsumed tree root
874
            raise errors.SubsumeTargetNeedsUpgrade(other_tree)
1731.2.4 by Aaron Bentley
Ensure subsume works with Knit2 repos
875
        other_tree.lock_tree_write()
876
        try:
877
            for parent_id in other_tree.get_parent_ids():
878
                self.branch.fetch(other_tree.branch, parent_id)
879
                self.add_parent_tree_id(parent_id)
880
            other_root = other_tree.inventory.root
881
            other_root.parent_id = new_root_parent
882
            other_root.name = osutils.basename(other_tree_path)
883
            self.inventory.add(other_root)
884
            add_children(self.inventory, other_root)
885
            self._write_inventory(self.inventory)
886
        finally:
887
            other_tree.unlock()
1731.2.14 by Aaron Bentley
Update for API change
888
        other_tree.bzrdir.destroy_workingtree_metadata()
1731.2.1 by Aaron Bentley
Initial subsume implementation
889
1731.2.16 by Aaron Bentley
Get extract working for standalone trees
890
    @needs_tree_write_lock
1731.2.17 by Aaron Bentley
Support extracting with checkouts
891
    def extract(self, file_id, format=None):
1731.2.16 by Aaron Bentley
Get extract working for standalone trees
892
        """Extract a subtree from this tree.
893
        
894
        A new branch will be created, relative to the path for this tree.
895
        """
1731.2.17 by Aaron Bentley
Support extracting with checkouts
896
        def mkdirs(path):
897
            segments = osutils.splitpath(path)
898
            transport = self.branch.bzrdir.root_transport
899
            for name in segments:
900
                transport = transport.clone(name)
901
                try:
902
                    transport.mkdir('.')
903
                except errors.FileExists:
904
                    pass
905
            return transport
906
            
1731.2.16 by Aaron Bentley
Get extract working for standalone trees
907
        sub_path = self.id2path(file_id)
1731.2.17 by Aaron Bentley
Support extracting with checkouts
908
        branch_transport = mkdirs(sub_path)
909
        if format is None:
2100.3.17 by Aaron Bentley
Remove get_format_*, make FormatRegistry.register_metadir vary working tree
910
            format = bzrdir.format_registry.make_bzrdir('experimental-knit2')
1731.2.17 by Aaron Bentley
Support extracting with checkouts
911
        try:
912
            branch_transport.mkdir('.')
913
        except errors.FileExists:
914
            pass
1731.2.16 by Aaron Bentley
Get extract working for standalone trees
915
        branch_bzrdir = format.initialize_on_transport(branch_transport)
916
        try:
917
            repo = branch_bzrdir.find_repository()
918
        except errors.NoRepositoryPresent:
919
            repo = branch_bzrdir.create_repository()
920
            assert repo.supports_rich_root()
921
        else:
922
            if not repo.supports_rich_root():
1731.2.18 by Aaron Bentley
Get extract in repository under test
923
                raise errors.RootNotRich()
1731.2.16 by Aaron Bentley
Get extract working for standalone trees
924
        new_branch = branch_bzrdir.create_branch()
1731.2.21 by Aaron Bentley
Ensure extracting a subtree dupes the branch
925
        new_branch.pull(self.branch)
1731.2.16 by Aaron Bentley
Get extract working for standalone trees
926
        for parent_id in self.get_parent_ids():
927
            new_branch.fetch(self.branch, parent_id)
928
        tree_transport = self.bzrdir.root_transport.clone(sub_path)
929
        if tree_transport.base != branch_transport.base:
930
            tree_bzrdir = format.initialize_on_transport(tree_transport)
1731.2.17 by Aaron Bentley
Support extracting with checkouts
931
            branch.BranchReferenceFormat().initialize(tree_bzrdir, new_branch)
1731.2.16 by Aaron Bentley
Get extract working for standalone trees
932
        else:
933
            tree_bzrdir = branch_bzrdir
1731.2.18 by Aaron Bentley
Get extract in repository under test
934
        wt = tree_bzrdir.create_workingtree(NULL_REVISION)
1731.2.16 by Aaron Bentley
Get extract working for standalone trees
935
        wt.set_parent_ids(self.get_parent_ids())
936
        my_inv = self.inventory
937
        child_inv = Inventory(root_id=None)
938
        new_root = my_inv[file_id]
939
        my_inv.remove_recursive_id(file_id)
940
        new_root.parent_id = None
941
        child_inv.add(new_root)
942
        self._write_inventory(my_inv)
943
        wt._write_inventory(child_inv)
944
        return wt
945
1534.7.192 by Aaron Bentley
Record hashes produced by merges
946
    @needs_read_lock
947
    def merge_modified(self):
948
        try:
949
            hashfile = self._control_files.get('merge-hashes')
2206.1.7 by Marius Kruger
* errors
950
        except errors.NoSuchFile:
1534.7.192 by Aaron Bentley
Record hashes produced by merges
951
            return {}
1534.7.196 by Aaron Bentley
Switched to Rio format for merge-modified list
952
        merge_hashes = {}
953
        try:
954
            if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
2206.1.7 by Marius Kruger
* errors
955
                raise errors.MergeModifiedFormatError()
1534.7.196 by Aaron Bentley
Switched to Rio format for merge-modified list
956
        except StopIteration:
2206.1.7 by Marius Kruger
* errors
957
            raise errors.MergeModifiedFormatError()
1534.7.196 by Aaron Bentley
Switched to Rio format for merge-modified list
958
        for s in RioReader(hashfile):
1534.7.198 by Aaron Bentley
Removed spurious encode/decode
959
            file_id = s.get("file_id")
1558.12.10 by Aaron Bentley
Be robust when merge_hash file_id not in inventory
960
            if file_id not in self.inventory:
961
                continue
1534.7.196 by Aaron Bentley
Switched to Rio format for merge-modified list
962
            hash = s.get("hash")
963
            if hash == self.get_file_sha1(file_id):
964
                merge_hashes[file_id] = hash
965
        return merge_hashes
1534.7.192 by Aaron Bentley
Record hashes produced by merges
966
1986.1.2 by Robert Collins
Various changes to allow non-workingtree specific tests to run entirely
967
    @needs_write_lock
968
    def mkdir(self, path, file_id=None):
969
        """See MutableTree.mkdir()."""
970
        if file_id is None:
2116.4.1 by John Arbash Meinel
Update file and revision id generators.
971
            file_id = generate_ids.gen_file_id(os.path.basename(path))
1986.1.2 by Robert Collins
Various changes to allow non-workingtree specific tests to run entirely
972
        os.mkdir(self.abspath(path))
973
        self.add(path, file_id, 'directory')
974
        return file_id
975
1092.2.6 by Robert Collins
symlink support updated to work
976
    def get_symlink_target(self, file_id):
1185.15.10 by Scott James Remnant
Fix WorkingTree.get_symlink_target() to read the absolute path of the
977
        return os.readlink(self.id2abspath(file_id))
453 by Martin Pool
- Split WorkingTree into its own file
978
979
    def file_class(self, filename):
980
        if self.path2id(filename):
981
            return 'V'
982
        elif self.is_ignored(filename):
983
            return 'I'
984
        else:
985
            return '?'
986
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
987
    def flush(self):
988
        """Write the in memory inventory to disk."""
989
        # TODO: Maybe this should only write on dirty ?
990
        if self._control_files._lock_mode != 'w':
991
            raise errors.NotWriteLocked(self)
992
        sio = StringIO()
2100.3.10 by Aaron Bentley
Ensure added references are serialized properly, beef up Workingtreee3
993
        self._serialize(self._inventory, sio)
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
994
        sio.seek(0)
995
        self._control_files.put('inventory', sio)
996
        self._inventory_is_modified = False
997
2100.3.10 by Aaron Bentley
Ensure added references are serialized properly, beef up Workingtreee3
998
    def _serialize(self, inventory, out_file):
999
        xml5.serializer_v5.write_inventory(self._inventory, out_file)
1000
1001
    def _deserialize(selt, in_file):
1002
        return xml5.serializer_v5.read_inventory(in_file)
1003
1731.1.33 by Aaron Bentley
Revert no-special-root changes
1004
    def list_files(self, include_root=False):
1732.1.6 by John Arbash Meinel
Fix documentation bug in workingtree.list_files
1005
        """Recursively list all files as (path, class, kind, id, entry).
453 by Martin Pool
- Split WorkingTree into its own file
1006
1007
        Lists, but does not descend into unversioned directories.
1008
1009
        This does not include files that have been deleted in this
1010
        tree.
1011
1012
        Skips the control directory.
1013
        """
2255.2.60 by John Arbash Meinel
Add an explicit exception since tree.list_files() requires a lock (at least for dirstate
1014
        # list_files is an iterator, so @needs_read_lock doesn't work properly
1015
        # with it. So callers should be careful to always read_lock the tree.
1016
        if not self.is_locked():
1017
            raise errors.ObjectNotLocked(self)
1018
2255.2.52 by Robert Collins
Dirstate - fix workingtree.list_files to use the public interface to access the trees inventory.
1019
        inv = self.inventory
1910.2.56 by Aaron Bentley
More work on bundles
1020
        if include_root is True:
1021
            yield ('', 'V', 'directory', inv.root.file_id, inv.root)
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
1022
        # Convert these into local objects to save lookup times
1836.1.22 by John Arbash Meinel
[merge] bzr.dev 1861
1023
        pathjoin = osutils.pathjoin
1024
        file_kind = osutils.file_kind
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
1025
1026
        # transport.base ends in a slash, we want the piece
1027
        # between the last two slashes
1028
        transport_base_dir = self.bzrdir.transport.base.rsplit('/', 2)[1]
1029
1732.1.11 by John Arbash Meinel
Trying multiple things to get WorkingTree.list_files time down
1030
        fk_entries = {'directory':TreeDirectory, 'file':TreeFile, 'symlink':TreeLink}
1031
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
1032
        # directory file_id, relative path, absolute path, reverse sorted children
1033
        children = os.listdir(self.basedir)
1034
        children.sort()
1732.1.14 by John Arbash Meinel
Some speedups by not calling pathjoin()
1035
        # jam 20060527 The kernel sized tree seems equivalent whether we 
1036
        # use a deque and popleft to keep them sorted, or if we use a plain
1037
        # list and just reverse() them.
1732.1.13 by John Arbash Meinel
A large improvement from not popping the parent off until we have done all children.
1038
        children = collections.deque(children)
1732.1.21 by John Arbash Meinel
We don't need to strip off 2 characters, just do one, minor memory improvement
1039
        stack = [(inv.root.file_id, u'', self.basedir, children)]
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
1040
        while stack:
1732.1.13 by John Arbash Meinel
A large improvement from not popping the parent off until we have done all children.
1041
            from_dir_id, from_dir_relpath, from_dir_abspath, children = stack[-1]
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
1042
1043
            while children:
1732.1.13 by John Arbash Meinel
A large improvement from not popping the parent off until we have done all children.
1044
                f = children.popleft()
453 by Martin Pool
- Split WorkingTree into its own file
1045
                ## TODO: If we find a subdirectory with its own .bzr
1046
                ## directory, then that is a separate tree and we
1047
                ## should exclude it.
1534.5.5 by Robert Collins
Move is_control_file into WorkingTree.is_control_filename and test.
1048
1049
                # the bzrdir for this tree
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
1050
                if transport_base_dir == f:
453 by Martin Pool
- Split WorkingTree into its own file
1051
                    continue
1052
1732.1.14 by John Arbash Meinel
Some speedups by not calling pathjoin()
1053
                # we know that from_dir_relpath and from_dir_abspath never end in a slash
1054
                # and 'f' doesn't begin with one, we can do a string op, rather
1732.1.21 by John Arbash Meinel
We don't need to strip off 2 characters, just do one, minor memory improvement
1055
                # than the checks of pathjoin(), all relative paths will have an extra slash
1056
                # at the beginning
1732.1.14 by John Arbash Meinel
Some speedups by not calling pathjoin()
1057
                fp = from_dir_relpath + '/' + f
453 by Martin Pool
- Split WorkingTree into its own file
1058
1059
                # absolute path
1732.1.14 by John Arbash Meinel
Some speedups by not calling pathjoin()
1060
                fap = from_dir_abspath + '/' + f
453 by Martin Pool
- Split WorkingTree into its own file
1061
                
1062
                f_ie = inv.get_child(from_dir_id, f)
1063
                if f_ie:
1064
                    c = 'V'
1551.6.36 by Aaron Bentley
Revert --debris/--detritus changes
1065
                elif self.is_ignored(fp[1:]):
1066
                    c = 'I'
453 by Martin Pool
- Split WorkingTree into its own file
1067
                else:
1830.3.3 by John Arbash Meinel
inside workingtree check for normalized filename access
1068
                    # we may not have found this file, because of a unicode issue
1069
                    f_norm, can_access = osutils.normalized_filename(f)
1070
                    if f == f_norm or not can_access:
1071
                        # No change, so treat this file normally
1072
                        c = '?'
1073
                    else:
1074
                        # this file can be accessed by a normalized path
1075
                        # check again if it is versioned
1076
                        # these lines are repeated here for performance
1077
                        f = f_norm
1078
                        fp = from_dir_relpath + '/' + f
1079
                        fap = from_dir_abspath + '/' + f
1080
                        f_ie = inv.get_child(from_dir_id, f)
1081
                        if f_ie:
1082
                            c = 'V'
1083
                        elif self.is_ignored(fp[1:]):
1084
                            c = 'I'
1085
                        else:
1086
                            c = '?'
453 by Martin Pool
- Split WorkingTree into its own file
1087
1088
                fk = file_kind(fap)
1089
1090
                if f_ie:
1091
                    if f_ie.kind != fk:
2206.1.7 by Marius Kruger
* errors
1092
                        raise errors.BzrCheckError(
1093
                            "file %r entered as kind %r id %r, now of kind %r"
1094
                            % (fap, f_ie.kind, f_ie.file_id, fk))
453 by Martin Pool
- Split WorkingTree into its own file
1095
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
1096
                # make a last minute entry
1097
                if f_ie:
1732.1.21 by John Arbash Meinel
We don't need to strip off 2 characters, just do one, minor memory improvement
1098
                    yield fp[1:], c, fk, f_ie.file_id, f_ie
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
1099
                else:
1732.1.11 by John Arbash Meinel
Trying multiple things to get WorkingTree.list_files time down
1100
                    try:
1732.1.21 by John Arbash Meinel
We don't need to strip off 2 characters, just do one, minor memory improvement
1101
                        yield fp[1:], c, fk, None, fk_entries[fk]()
1732.1.11 by John Arbash Meinel
Trying multiple things to get WorkingTree.list_files time down
1102
                    except KeyError:
1732.1.21 by John Arbash Meinel
We don't need to strip off 2 characters, just do one, minor memory improvement
1103
                        yield fp[1:], c, fk, None, TreeEntry()
1732.1.13 by John Arbash Meinel
A large improvement from not popping the parent off until we have done all children.
1104
                    continue
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
1105
                
453 by Martin Pool
- Split WorkingTree into its own file
1106
                if fk != 'directory':
1107
                    continue
1108
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
1109
                # But do this child first
1732.1.13 by John Arbash Meinel
A large improvement from not popping the parent off until we have done all children.
1110
                new_children = os.listdir(fap)
1111
                new_children.sort()
1112
                new_children = collections.deque(new_children)
1113
                stack.append((f_ie.file_id, fp, fap, new_children))
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
1114
                # Break out of inner loop,
2206.1.7 by Marius Kruger
* errors
1115
                # so that we start outer loop with child
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
1116
                break
1732.1.22 by John Arbash Meinel
Bug in list_files if the last entry in a directory is another directory
1117
            else:
1118
                # if we finished all children, pop it off the stack
1732.1.25 by John Arbash Meinel
Fix list_files test, we don't need to check if children are empty if we fall off the loop.
1119
                stack.pop()
1732.1.13 by John Arbash Meinel
A large improvement from not popping the parent off until we have done all children.
1120
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
1121
    @needs_tree_write_lock
2123.3.8 by Steffen Eichenberg
new parameter to_dir must be a named parameter
1122
    def move(self, from_paths, to_dir=None, after=False, **kwargs):
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
1123
        """Rename files.
1124
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1125
        to_dir must exist in the inventory.
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
1126
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1127
        If to_dir exists and is a directory, the files are moved into
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
1128
        it, keeping their old names.  
1129
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1130
        Note that to_dir is only the last component of the new name;
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
1131
        this doesn't change the directory.
1132
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
1133
        For each entry in from_paths the move mode will be determined
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1134
        independently.
1135
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
1136
        The first mode moves the file in the filesystem and updates the
1137
        inventory. The second mode only updates the inventory without
1138
        touching the file on the filesystem. This is the new mode introduced
2220.1.6 by Marius Kruger
* change error message telling user about --after option sightly
1139
        in version 0.15.
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
1140
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1141
        move uses the second mode if 'after == True' and the target is not
1142
        versioned but present in the working tree.
1143
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
1144
        move uses the second mode if 'after == False' and the source is
1145
        versioned but no longer in the working tree, and the target is not
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1146
        versioned but present in the working tree.
1147
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
1148
        move uses the first mode if 'after == False' and the source is
1149
        versioned and present in the working tree, and the target is not
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1150
        versioned and not present in the working tree.
1151
1152
        Everything else results in an error.
1153
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
1154
        This returns a list of (from_path, to_path) pairs for each
2220.1.6 by Marius Kruger
* change error message telling user about --after option sightly
1155
        entry that is moved.
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
1156
        """
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1157
        rename_entries = []
1158
        rename_tuples = []
1159
1160
        # check for deprecated use of signature
1161
        if to_dir is None:
1162
            to_dir = kwargs.get('to_name', None)
1163
            if to_dir is None:
1164
                raise TypeError('You must supply a target directory')
1165
            else:
1166
                symbol_versioning.warn('The parameter to_name was deprecated'
1167
                                       ' in version 0.13. Use to_dir instead',
1168
                                       DeprecationWarning)
1169
1170
        # check destination directory
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
1171
        assert not isinstance(from_paths, basestring)
1172
        inv = self.inventory
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1173
        to_abs = self.abspath(to_dir)
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
1174
        if not isdir(to_abs):
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
1175
            raise errors.BzrMoveFailedError('',to_dir,
2206.1.9 by Marius Kruger
* Change move/rename errors yet again
1176
                errors.NotADirectory(to_abs))
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1177
        if not self.has_filename(to_dir):
2206.1.9 by Marius Kruger
* Change move/rename errors yet again
1178
            raise errors.BzrMoveFailedError('',to_dir,
1179
                errors.NotInWorkingDirectory(to_dir))
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1180
        to_dir_id = inv.path2id(to_dir)
2123.3.6 by Steffen Eichenberg
unified error messages
1181
        if to_dir_id is None:
2206.1.9 by Marius Kruger
* Change move/rename errors yet again
1182
            raise errors.BzrMoveFailedError('',to_dir,
1183
                errors.NotVersionedError(path=str(to_dir)))
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
1184
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
1185
        to_dir_ie = inv[to_dir_id]
1731.1.2 by Aaron Bentley
Removed all remaining uses of root_directory
1186
        if to_dir_ie.kind != 'directory':
2206.1.9 by Marius Kruger
* Change move/rename errors yet again
1187
            raise errors.BzrMoveFailedError('',to_dir,
1188
                errors.NotADirectory(to_abs))
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
1189
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1190
        # create rename entries and tuples
1191
        for from_rel in from_paths:
1192
            from_tail = splitpath(from_rel)[-1]
1193
            from_id = inv.path2id(from_rel)
1194
            if from_id is None:
2206.1.9 by Marius Kruger
* Change move/rename errors yet again
1195
                raise errors.BzrMoveFailedError(from_rel,to_dir,
1196
                    errors.NotVersionedError(path=str(from_rel)))
2206.1.4 by Marius Kruger
Improved WorkingTree.move excptions. (as requested)
1197
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1198
            from_entry = inv[from_id]
1199
            from_parent_id = from_entry.parent_id
1200
            to_rel = pathjoin(to_dir, from_tail)
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
1201
            rename_entry = WorkingTree._RenameEntry(from_rel=from_rel,
2123.3.2 by Steffen Eichenberg
fixed the most obvious bugs
1202
                                         from_id=from_id,
1203
                                         from_tail=from_tail,
1204
                                         from_parent_id=from_parent_id,
1205
                                         to_rel=to_rel, to_tail=from_tail,
1206
                                         to_parent_id=to_dir_id)
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1207
            rename_entries.append(rename_entry)
1208
            rename_tuples.append((from_rel, to_rel))
1209
1210
        # determine which move mode to use. checks also for movability
1211
        rename_entries = self._determine_mv_mode(rename_entries, after)
1212
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
1213
        original_modified = self._inventory_is_modified
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
1214
        try:
2220.1.6 by Marius Kruger
* change error message telling user about --after option sightly
1215
            if len(from_paths):
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
1216
                self._inventory_is_modified = True
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1217
            self._move(rename_entries)
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
1218
        except:
1219
            # restore the inventory on error
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1220
            self._inventory_is_modified = original_modified
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
1221
            raise
1222
        self._write_inventory(inv)
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1223
        return rename_tuples
1224
1225
    def _determine_mv_mode(self, rename_entries, after=False):
1226
        """Determines for each from-to pair if both inventory and working tree
1227
        or only the inventory has to be changed.
1228
1229
        Also does basic plausability tests.
1230
        """
1231
        inv = self.inventory
1232
1233
        for rename_entry in rename_entries:
1234
            # store to local variables for easier reference
1235
            from_rel = rename_entry.from_rel
1236
            from_id = rename_entry.from_id
1237
            to_rel = rename_entry.to_rel
1238
            to_id = inv.path2id(to_rel)
1239
            only_change_inv = False
1240
1241
            # check the inventory for source and destination
1242
            if from_id is None:
2206.1.9 by Marius Kruger
* Change move/rename errors yet again
1243
                raise errors.BzrMoveFailedError(from_rel,to_rel,
1244
                    errors.NotVersionedError(path=str(from_rel)))
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1245
            if to_id is not None:
2206.1.9 by Marius Kruger
* Change move/rename errors yet again
1246
                raise errors.BzrMoveFailedError(from_rel,to_rel,
1247
                    errors.AlreadyVersionedError(path=str(to_rel)))
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1248
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
1249
            # try to determine the mode for rename (only change inv or change
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1250
            # inv and file system)
1251
            if after:
1252
                if not self.has_filename(to_rel):
2206.1.9 by Marius Kruger
* Change move/rename errors yet again
1253
                    raise errors.BzrMoveFailedError(from_id,to_rel,
1254
                        errors.NoSuchFile(path=str(to_rel),
1255
                        extra="New file has not been created yet"))
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1256
                only_change_inv = True
1257
            elif not self.has_filename(from_rel) and self.has_filename(to_rel):
1258
                only_change_inv = True
1259
            elif self.has_filename(from_rel) and not self.has_filename(to_rel):
1260
                only_change_inv = False
1261
            else:
1262
                # something is wrong, so lets determine what exactly
1263
                if not self.has_filename(from_rel) and \
1264
                   not self.has_filename(to_rel):
2206.1.9 by Marius Kruger
* Change move/rename errors yet again
1265
                    raise errors.BzrRenameFailedError(from_rel,to_rel,
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
1266
                        errors.PathsDoNotExist(paths=(str(from_rel),
2206.1.9 by Marius Kruger
* Change move/rename errors yet again
1267
                        str(to_rel))))
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1268
                else:
2220.1.11 by Marius Kruger
* bzrlib/errors.py
1269
                    raise errors.RenameFailedFilesExist(from_rel, to_rel,
1270
                        extra="(Use --after to update the Bazaar id)")
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
1271
            rename_entry.only_change_inv = only_change_inv
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1272
        return rename_entries
1273
1274
    def _move(self, rename_entries):
1275
        """Moves a list of files.
1276
1277
        Depending on the value of the flag 'only_change_inv', the
1278
        file will be moved on the file system or not.
1279
        """
1280
        inv = self.inventory
1281
        moved = []
1282
1283
        for entry in rename_entries:
1284
            try:
1285
                self._move_entry(entry)
2220.1.12 by Marius Kruger
* Fix errors.py import order
1286
            except:
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1287
                self._rollback_move(moved)
1288
                raise
1289
            moved.append(entry)
1290
1291
    def _rollback_move(self, moved):
2220.1.12 by Marius Kruger
* Fix errors.py import order
1292
        """Try to rollback a previous move in case of an filesystem error."""
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1293
        inv = self.inventory
1294
        for entry in moved:
1295
            try:
2220.1.12 by Marius Kruger
* Fix errors.py import order
1296
                self._move_entry(_RenameEntry(entry.to_rel, entry.from_id,
1297
                    entry.to_tail, entry.to_parent_id, entry.from_rel,
1298
                    entry.from_tail, entry.from_parent_id,
1299
                    entry.only_change_inv))
2220.1.14 by Aaron Bentley
Cleanup formatting and error handling
1300
            except errors.BzrMoveFailedError, e:
2220.1.12 by Marius Kruger
* Fix errors.py import order
1301
                raise errors.BzrMoveFailedError( '', '', "Rollback failed."
2206.1.9 by Marius Kruger
* Change move/rename errors yet again
1302
                        " The working tree is in an inconsistent state."
1303
                        " Please consider doing a 'bzr revert'."
2220.1.14 by Aaron Bentley
Cleanup formatting and error handling
1304
                        " Error message is: %s" % e)
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1305
2220.1.12 by Marius Kruger
* Fix errors.py import order
1306
    def _move_entry(self, entry):
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1307
        inv = self.inventory
1308
        from_rel_abs = self.abspath(entry.from_rel)
1309
        to_rel_abs = self.abspath(entry.to_rel)
1310
        if from_rel_abs == to_rel_abs:
2220.1.12 by Marius Kruger
* Fix errors.py import order
1311
            raise errors.BzrMoveFailedError(entry.from_rel, entry.to_rel,
2206.1.9 by Marius Kruger
* Change move/rename errors yet again
1312
                "Source and target are identical.")
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
1313
2220.1.12 by Marius Kruger
* Fix errors.py import order
1314
        if not entry.only_change_inv:
1315
            try:
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1316
                osutils.rename(from_rel_abs, to_rel_abs)
2220.1.12 by Marius Kruger
* Fix errors.py import order
1317
            except OSError, e:
1318
                raise errors.BzrMoveFailedError(entry.from_rel,
1319
                    entry.to_rel, e[1])
1320
        inv.rename(entry.from_id, entry.to_parent_id, entry.to_tail)
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
1321
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
1322
    @needs_tree_write_lock
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1323
    def rename_one(self, from_rel, to_rel, after=False):
1508.1.7 by Robert Collins
Move rename_one from Branch to WorkingTree. (Robert Collins).
1324
        """Rename one file.
1325
1326
        This can change the directory or the filename or both.
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1327
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
1328
        rename_one has several 'modes' to work. First, it can rename a physical
1329
        file and change the file_id. That is the normal mode. Second, it can
1330
        only change the file_id without touching any physical file. This is
1331
        the new mode introduced in version 0.15.
1332
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1333
        rename_one uses the second mode if 'after == True' and 'to_rel' is not
1334
        versioned but present in the working tree.
1335
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
1336
        rename_one uses the second mode if 'after == False' and 'from_rel' is
1337
        versioned but no longer in the working tree, and 'to_rel' is not
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1338
        versioned but present in the working tree.
1339
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
1340
        rename_one uses the first mode if 'after == False' and 'from_rel' is
1341
        versioned and present in the working tree, and 'to_rel' is not
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1342
        versioned and not present in the working tree.
1343
1344
        Everything else results in an error.
1508.1.7 by Robert Collins
Move rename_one from Branch to WorkingTree. (Robert Collins).
1345
        """
1346
        inv = self.inventory
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1347
        rename_entries = []
1348
1349
        # create rename entries and tuples
1350
        from_tail = splitpath(from_rel)[-1]
1351
        from_id = inv.path2id(from_rel)
1352
        if from_id is None:
2206.1.9 by Marius Kruger
* Change move/rename errors yet again
1353
            raise errors.BzrRenameFailedError(from_rel,to_rel,
1354
                errors.NotVersionedError(path=str(from_rel)))
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1355
        from_entry = inv[from_id]
1356
        from_parent_id = from_entry.parent_id
1508.1.7 by Robert Collins
Move rename_one from Branch to WorkingTree. (Robert Collins).
1357
        to_dir, to_tail = os.path.split(to_rel)
1358
        to_dir_id = inv.path2id(to_dir)
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
1359
        rename_entry = WorkingTree._RenameEntry(from_rel=from_rel,
2123.3.2 by Steffen Eichenberg
fixed the most obvious bugs
1360
                                     from_id=from_id,
1361
                                     from_tail=from_tail,
1362
                                     from_parent_id=from_parent_id,
1363
                                     to_rel=to_rel, to_tail=to_tail,
1364
                                     to_parent_id=to_dir_id)
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1365
        rename_entries.append(rename_entry)
1366
1367
        # determine which move mode to use. checks also for movability
1368
        rename_entries = self._determine_mv_mode(rename_entries, after)
1369
1370
        # check if the target changed directory and if the target directory is
1371
        # versioned
2123.3.6 by Steffen Eichenberg
unified error messages
1372
        if to_dir_id is None:
2206.1.9 by Marius Kruger
* Change move/rename errors yet again
1373
            raise errors.BzrMoveFailedError(from_rel,to_rel,
1374
                errors.NotVersionedError(path=str(to_dir)))
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
1375
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1376
        # all checks done. now we can continue with our actual work
1377
        mutter('rename_one:\n'
1378
               '  from_id   {%s}\n'
1379
               '  from_rel: %r\n'
1380
               '  to_rel:   %r\n'
1381
               '  to_dir    %r\n'
1382
               '  to_dir_id {%s}\n',
1383
               from_id, from_rel, to_rel, to_dir, to_dir_id)
1384
1385
        self._move(rename_entries)
1508.1.7 by Robert Collins
Move rename_one from Branch to WorkingTree. (Robert Collins).
1386
        self._write_inventory(inv)
1387
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1388
    class _RenameEntry(object):
2123.3.2 by Steffen Eichenberg
fixed the most obvious bugs
1389
        def __init__(self, from_rel, from_id, from_tail, from_parent_id,
2220.1.12 by Marius Kruger
* Fix errors.py import order
1390
                     to_rel, to_tail, to_parent_id, only_change_inv=False):
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1391
            self.from_rel = from_rel
1392
            self.from_id = from_id
1393
            self.from_tail = from_tail
1394
            self.from_parent_id = from_parent_id
1395
            self.to_rel = to_rel
1396
            self.to_tail = to_tail
1397
            self.to_parent_id = to_parent_id
2220.1.12 by Marius Kruger
* Fix errors.py import order
1398
            self.only_change_inv = only_change_inv
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
1399
1508.1.7 by Robert Collins
Move rename_one from Branch to WorkingTree. (Robert Collins).
1400
    @needs_read_lock
453 by Martin Pool
- Split WorkingTree into its own file
1401
    def unknowns(self):
1508.1.6 by Robert Collins
Move Branch.unknowns() to WorkingTree.
1402
        """Return all unknown files.
1403
1404
        These are files in the working directory that are not versioned or
1405
        control files or ignored.
1406
        """
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
1407
        # force the extras method to be fully executed before returning, to 
1408
        # prevent race conditions with the lock
1409
        return iter(
1410
            [subp for subp in self.extras() if not self.is_ignored(subp)])
1988.2.1 by Robert Collins
WorkingTree has a new api ``unversion`` which allow the unversioning of
1411
    
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
1412
    @needs_tree_write_lock
1988.2.1 by Robert Collins
WorkingTree has a new api ``unversion`` which allow the unversioning of
1413
    def unversion(self, file_ids):
1414
        """Remove the file ids in file_ids from the current versioned set.
1415
1416
        When a file_id is unversioned, all of its children are automatically
1417
        unversioned.
1418
1419
        :param file_ids: The file ids to stop versioning.
1420
        :raises: NoSuchId if any fileid is not currently versioned.
1421
        """
1422
        for file_id in file_ids:
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
1423
            file_id = osutils.safe_file_id(file_id)
1988.2.1 by Robert Collins
WorkingTree has a new api ``unversion`` which allow the unversioning of
1424
            if self._inventory.has_id(file_id):
1988.2.6 by Robert Collins
Review feedback.
1425
                self._inventory.remove_recursive_id(file_id)
1988.2.1 by Robert Collins
WorkingTree has a new api ``unversion`` which allow the unversioning of
1426
            else:
1427
                raise errors.NoSuchId(self, file_id)
1428
        if len(file_ids):
1429
            # in the future this should just set a dirty bit to wait for the 
1430
            # final unlock. However, until all methods of workingtree start
1431
            # with the current in -memory inventory rather than triggering 
1432
            # a read, it is more complex - we need to teach read_inventory
1433
            # to know when to read, and when to not read first... and possibly
1434
            # to save first when the in memory one may be corrupted.
1435
            # so for now, we just only write it if it is indeed dirty.
1436
            # - RBC 20060907
1437
            self._write_inventory(self._inventory)
1438
    
1534.10.16 by Aaron Bentley
Small tweaks
1439
    @deprecated_method(zero_eight)
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
1440
    def iter_conflicts(self):
1534.10.16 by Aaron Bentley
Small tweaks
1441
        """List all files in the tree that have text or content conflicts.
1534.10.22 by Aaron Bentley
Got ConflictList implemented
1442
        DEPRECATED.  Use conflicts instead."""
1534.10.10 by Aaron Bentley
Resolve uses the new stuff.
1443
        return self._iter_conflicts()
1444
1534.10.9 by Aaron Bentley
Switched display functions to conflict_lines
1445
    def _iter_conflicts(self):
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
1446
        conflicted = set()
1732.1.11 by John Arbash Meinel
Trying multiple things to get WorkingTree.list_files time down
1447
        for info in self.list_files():
1448
            path = info[0]
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
1449
            stem = get_conflicted_stem(path)
1450
            if stem is None:
1451
                continue
1452
            if stem not in conflicted:
1453
                conflicted.add(stem)
1454
                yield stem
453 by Martin Pool
- Split WorkingTree into its own file
1455
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
1456
    @needs_write_lock
1551.11.10 by Aaron Bentley
Add change reporting to pull
1457
    def pull(self, source, overwrite=False, stop_revision=None,
1458
             change_reporter=None):
1551.2.36 by Aaron Bentley
Make pull update the progress bar more nicely
1459
        top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
1460
        source.lock_read()
1461
        try:
1551.2.36 by Aaron Bentley
Make pull update the progress bar more nicely
1462
            pp = ProgressPhase("Pull phase", 2, top_pb)
1463
            pp.next_phase()
2249.4.2 by Wouter van Heyst
Convert callers of Branch.revision_history() to Branch.last_revision_info() where sensible.
1464
            old_revision_info = self.branch.last_revision_info()
1563.1.4 by Robert Collins
Fix 'bzr pull' on metadir trees.
1465
            basis_tree = self.basis_tree()
1534.4.54 by Robert Collins
Merge from integration.
1466
            count = self.branch.pull(source, overwrite, stop_revision)
2249.4.2 by Wouter van Heyst
Convert callers of Branch.revision_history() to Branch.last_revision_info() where sensible.
1467
            new_revision_info = self.branch.last_revision_info()
1468
            if new_revision_info != old_revision_info:
1551.2.36 by Aaron Bentley
Make pull update the progress bar more nicely
1469
                pp.next_phase()
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
1470
                repository = self.branch.repository
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
1471
                pb = bzrlib.ui.ui_factory.nested_progress_bar()
2255.2.38 by Robert Collins
Fix WorkingTree4.pull to work.
1472
                basis_tree.lock_read()
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
1473
                try:
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
1474
                    new_basis_tree = self.branch.basis_tree()
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
1475
                    merge.merge_inner(
1476
                                self.branch,
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
1477
                                new_basis_tree,
1478
                                basis_tree,
1479
                                this_tree=self,
1551.11.10 by Aaron Bentley
Add change reporting to pull
1480
                                pb=pb,
1481
                                change_reporter=change_reporter)
1731.1.33 by Aaron Bentley
Revert no-special-root changes
1482
                    if (basis_tree.inventory.root is None and
1731.1.47 by Aaron Bentley
Merge bzr.dev
1483
                        new_basis_tree.inventory.root is not None):
1484
                        self.set_root_id(new_basis_tree.inventory.root.file_id)
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
1485
                finally:
1486
                    pb.finished()
2255.2.38 by Robert Collins
Fix WorkingTree4.pull to work.
1487
                    basis_tree.unlock()
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
1488
                # TODO - dedup parents list with things merged by pull ?
1908.6.3 by Robert Collins
Tidy up the last_revision_id and add_pending_merge conversion to use cleaner apis.
1489
                # reuse the revisiontree we merged against to set the new
1490
                # tree data.
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
1491
                parent_trees = [(self.branch.last_revision(), new_basis_tree)]
1908.6.3 by Robert Collins
Tidy up the last_revision_id and add_pending_merge conversion to use cleaner apis.
1492
                # we have to pull the merge trees out again, because 
1493
                # merge_inner has set the ids. - this corner is not yet 
1494
                # layered well enough to prevent double handling.
2255.2.38 by Robert Collins
Fix WorkingTree4.pull to work.
1495
                # XXX TODO: Fix the double handling: telling the tree about
1496
                # the already known parent data is wasteful.
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
1497
                merges = self.get_parent_ids()[1:]
1498
                parent_trees.extend([
1499
                    (parent, repository.revision_tree(parent)) for
1500
                     parent in merges])
1501
                self.set_parent_trees(parent_trees)
1185.33.44 by Martin Pool
[patch] show number of revisions pushed/pulled/merged (Robey Pointer)
1502
            return count
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
1503
        finally:
1504
            source.unlock()
1551.2.36 by Aaron Bentley
Make pull update the progress bar more nicely
1505
            top_pb.finished()
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
1506
1986.1.2 by Robert Collins
Various changes to allow non-workingtree specific tests to run entirely
1507
    @needs_write_lock
1508
    def put_file_bytes_non_atomic(self, file_id, bytes):
1509
        """See MutableTree.put_file_bytes_non_atomic."""
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
1510
        file_id = osutils.safe_file_id(file_id)
1986.1.2 by Robert Collins
Various changes to allow non-workingtree specific tests to run entirely
1511
        stream = file(self.id2abspath(file_id), 'wb')
1512
        try:
1513
            stream.write(bytes)
1514
        finally:
1515
            stream.close()
1516
        # TODO: update the hashcache here ?
1517
453 by Martin Pool
- Split WorkingTree into its own file
1518
    def extras(self):
1519
        """Yield all unknown files in this WorkingTree.
1520
1521
        If there are any unknown directories then only the directory is
1522
        returned, not all its children.  But if there are unknown files
1523
        under a versioned subdirectory, they are returned.
1524
1525
        Currently returned depth-first, sorted by name within directories.
1526
        """
1527
        ## TODO: Work from given directory downwards
1528
        for path, dir_entry in self.inventory.directories():
1711.2.101 by John Arbash Meinel
Clean up some unnecessary mutter() calls
1529
            # mutter("search for unknowns in %r", path)
453 by Martin Pool
- Split WorkingTree into its own file
1530
            dirabs = self.abspath(path)
1531
            if not isdir(dirabs):
1532
                # e.g. directory deleted
1533
                continue
1534
1535
            fl = []
1536
            for subf in os.listdir(dirabs):
1830.3.3 by John Arbash Meinel
inside workingtree check for normalized filename access
1537
                if subf == '.bzr':
1538
                    continue
1539
                if subf not in dir_entry.children:
1540
                    subf_norm, can_access = osutils.normalized_filename(subf)
1541
                    if subf_norm != subf and can_access:
1542
                        if subf_norm not in dir_entry.children:
1543
                            fl.append(subf_norm)
1544
                    else:
1545
                        fl.append(subf)
453 by Martin Pool
- Split WorkingTree into its own file
1546
            
1547
            fl.sort()
1548
            for subf in fl:
1732.1.1 by John Arbash Meinel
deprecating appendpath, it does exactly what pathjoin does
1549
                subp = pathjoin(path, subf)
453 by Martin Pool
- Split WorkingTree into its own file
1550
                yield subp
1551
1552
    def ignored_files(self):
1553
        """Yield list of PATH, IGNORE_PATTERN"""
1554
        for subp in self.extras():
1555
            pat = self.is_ignored(subp)
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
1556
            if pat is not None:
453 by Martin Pool
- Split WorkingTree into its own file
1557
                yield subp, pat
1558
1559
    def get_ignore_list(self):
1560
        """Return list of ignore patterns.
1561
1562
        Cached in the Tree object after the first call.
1563
        """
1836.1.30 by John Arbash Meinel
Change ignore functions to use sets instead of lists.
1564
        ignoreset = getattr(self, '_ignoreset', None)
1565
        if ignoreset is not None:
1566
            return ignoreset
1567
1568
        ignore_globs = set(bzrlib.DEFAULT_IGNORE)
1569
        ignore_globs.update(ignores.get_runtime_ignores())
1570
        ignore_globs.update(ignores.get_user_ignores())
453 by Martin Pool
- Split WorkingTree into its own file
1571
        if self.has_filename(bzrlib.IGNORE_FILENAME):
1572
            f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
1836.1.4 by John Arbash Meinel
Cleanup is_ignored to handle comment lines, and a global ignore pattern
1573
            try:
1836.1.30 by John Arbash Meinel
Change ignore functions to use sets instead of lists.
1574
                ignore_globs.update(ignores.parse_ignore_file(f))
1836.1.4 by John Arbash Meinel
Cleanup is_ignored to handle comment lines, and a global ignore pattern
1575
            finally:
1576
                f.close()
1836.1.30 by John Arbash Meinel
Change ignore functions to use sets instead of lists.
1577
        self._ignoreset = ignore_globs
1836.1.4 by John Arbash Meinel
Cleanup is_ignored to handle comment lines, and a global ignore pattern
1578
        return ignore_globs
453 by Martin Pool
- Split WorkingTree into its own file
1579
2135.2.7 by Kent Gibson
Implement JAM's review suggestions.
1580
    def _flush_ignore_list_cache(self):
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
1581
        """Resets the cached ignore list to force a cache rebuild."""
1582
        self._ignoreset = None
1583
        self._ignoreglobster = None
1713.2.3 by Robert Collins
Combine ignore rules into a single regex preventing pathological behaviour during add.
1584
453 by Martin Pool
- Split WorkingTree into its own file
1585
    def is_ignored(self, filename):
1586
        r"""Check whether the filename matches an ignore pattern.
1587
1588
        Patterns containing '/' or '\' need to match the whole path;
1589
        others match against only the last component.
1590
1591
        If the file is ignored, returns the pattern which caused it to
1592
        be ignored, otherwise None.  So this can simply be used as a
1593
        boolean if desired."""
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
1594
        if getattr(self, '_ignoreglobster', None) is None:
2135.2.7 by Kent Gibson
Implement JAM's review suggestions.
1595
            self._ignoreglobster = globbing.Globster(self.get_ignore_list())
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
1596
        return self._ignoreglobster.match(filename)
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
1597
1185.12.28 by Aaron Bentley
Removed use of readonly path for executability test
1598
    def kind(self, file_id):
1599
        return file_kind(self.id2abspath(file_id))
1600
2012.1.7 by Aaron Bentley
Get tree._iter_changed down to ~ 1 stat per file
1601
    def _comparison_data(self, entry, path):
1602
        abspath = self.abspath(path)
1603
        try:
1604
            stat_value = os.lstat(abspath)
1605
        except OSError, e:
1606
            if getattr(e, 'errno', None) == errno.ENOENT:
1607
                stat_value = None
1608
                kind = None
1609
                executable = False
1610
            else:
1611
                raise
1612
        else:
1613
            mode = stat_value.st_mode
1614
            kind = osutils.file_kind_from_stat_mode(mode)
1615
            if not supports_executable():
1616
                executable = entry.executable
1617
            else:
1618
                executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1619
        return kind, executable, stat_value
1620
1621
    def _file_size(self, entry, stat_value):
1622
        return stat_value.st_size
1623
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1624
    def last_revision(self):
1986.1.6 by Robert Collins
Add MemoryTree.last_revision.
1625
        """Return the last revision of the branch for this tree.
1626
1627
        This format tree does not support a separate marker for last-revision
1628
        compared to the branch.
1629
1630
        See MutableTree.last_revision
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1631
        """
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
1632
        return self._last_revision()
1633
1634
    @needs_read_lock
1635
    def _last_revision(self):
1636
        """helper for get_parent_ids."""
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1637
        return self.branch.last_revision()
1638
1694.2.6 by Martin Pool
[merge] bzr.dev
1639
    def is_locked(self):
1640
        return self._control_files.is_locked()
1641
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1642
    def lock_read(self):
1643
        """See Branch.lock_read, and WorkingTree.unlock."""
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1644
        self.branch.lock_read()
1645
        try:
1646
            return self._control_files.lock_read()
1647
        except:
1648
            self.branch.unlock()
1649
            raise
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1650
1997.1.1 by Robert Collins
Add WorkingTree.lock_tree_write.
1651
    def lock_tree_write(self):
1986.1.8 by Robert Collins
Update to bzr.dev, which involves adding lock_tree_write to MutableTree and MemoryTree.
1652
        """See MutableTree.lock_tree_write, and WorkingTree.unlock."""
1997.1.1 by Robert Collins
Add WorkingTree.lock_tree_write.
1653
        self.branch.lock_read()
1654
        try:
1655
            return self._control_files.lock_write()
1656
        except:
1657
            self.branch.unlock()
1658
            raise
1659
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1660
    def lock_write(self):
1986.1.2 by Robert Collins
Various changes to allow non-workingtree specific tests to run entirely
1661
        """See MutableTree.lock_write, and WorkingTree.unlock."""
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1662
        self.branch.lock_write()
1663
        try:
1664
            return self._control_files.lock_write()
1665
        except:
1666
            self.branch.unlock()
1667
            raise
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1668
1694.2.6 by Martin Pool
[merge] bzr.dev
1669
    def get_physical_lock_status(self):
1670
        return self._control_files.get_physical_lock_status()
1671
1638.1.2 by Robert Collins
Change the basis-inventory file to not have the revision-id in the file name.
1672
    def _basis_inventory_name(self):
1910.2.31 by Aaron Bentley
Fix bugs in basis inventory handling, change filename
1673
        return 'basis-inventory-cache'
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
1674
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
1675
    @needs_tree_write_lock
1638.1.2 by Robert Collins
Change the basis-inventory file to not have the revision-id in the file name.
1676
    def set_last_revision(self, new_revision):
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1677
        """Change the last revision in the working tree."""
2249.5.9 by John Arbash Meinel
Update WorkingTree to use safe_revision_id when appropriate
1678
        new_revision = osutils.safe_revision_id(new_revision)
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1679
        if self._change_last_revision(new_revision):
1680
            self._cache_basis_inventory(new_revision)
1681
1682
    def _change_last_revision(self, new_revision):
1638.1.2 by Robert Collins
Change the basis-inventory file to not have the revision-id in the file name.
1683
        """Template method part of set_last_revision to perform the change.
1684
        
1685
        This is used to allow WorkingTree3 instances to not affect branch
1686
        when their last revision is set.
1687
        """
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1688
        if new_revision is None:
1689
            self.branch.set_revision_history([])
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1690
            return False
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1691
        try:
1908.1.1 by Robert Collins
Relax WorkingTree.set_last-revision to allow any revision to be set.
1692
            self.branch.generate_revision_history(new_revision)
1693
        except errors.NoSuchRevision:
1694
            # not present in the repo - dont try to set it deeper than the tip
1695
            self.branch.set_revision_history([new_revision])
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1696
        return True
1697
2041.1.2 by John Arbash Meinel
Update WorkingTree.set_parent_trees() to directly cache inv.
1698
    def _write_basis_inventory(self, xml):
1699
        """Write the basis inventory XML to the basis-inventory file"""
1700
        assert isinstance(xml, str), 'serialised xml must be bytestring.'
1701
        path = self._basis_inventory_name()
1702
        sio = StringIO(xml)
1703
        self._control_files.put(path, sio)
1704
1705
    def _create_basis_xml_from_inventory(self, revision_id, inventory):
1706
        """Create the text that will be saved in basis-inventory"""
2249.5.9 by John Arbash Meinel
Update WorkingTree to use safe_revision_id when appropriate
1707
        # TODO: jam 20070209 This should be redundant, as the revision_id
1708
        #       as all callers should have already converted the revision_id to
1709
        #       utf8
1710
        inventory.revision_id = osutils.safe_revision_id(revision_id)
2100.3.14 by Aaron Bentley
Test workingtree4 format, prevent use with old repos
1711
        return xml7.serializer_v7.write_inventory_to_string(inventory)
2041.1.2 by John Arbash Meinel
Update WorkingTree.set_parent_trees() to directly cache inv.
1712
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1713
    def _cache_basis_inventory(self, new_revision):
1714
        """Cache new_revision as the basis inventory."""
1740.2.3 by Aaron Bentley
Only reserialize the working tree basis inventory when needed.
1715
        # TODO: this should allow the ready-to-use inventory to be passed in,
1716
        # as commit already has that ready-to-use [while the format is the
1717
        # same, that is].
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
1718
        try:
1638.1.2 by Robert Collins
Change the basis-inventory file to not have the revision-id in the file name.
1719
            # this double handles the inventory - unpack and repack - 
1720
            # but is easier to understand. We can/should put a conditional
1721
            # in here based on whether the inventory is in the latest format
1722
            # - perhaps we should repack all inventories on a repository
1723
            # upgrade ?
1740.2.3 by Aaron Bentley
Only reserialize the working tree basis inventory when needed.
1724
            # the fast path is to copy the raw xml from the repository. If the
1725
            # xml contains 'revision_id="', then we assume the right 
1726
            # revision_id is set. We must check for this full string, because a
1727
            # root node id can legitimately look like 'revision_id' but cannot
1728
            # contain a '"'.
1729
            xml = self.branch.repository.get_inventory_xml(new_revision)
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
1730
            firstline = xml.split('\n', 1)[0]
1731
            if (not 'revision_id="' in firstline or 
2100.3.14 by Aaron Bentley
Test workingtree4 format, prevent use with old repos
1732
                'format="7"' not in firstline):
1740.2.3 by Aaron Bentley
Only reserialize the working tree basis inventory when needed.
1733
                inv = self.branch.repository.deserialise_inventory(
1734
                    new_revision, xml)
2041.1.2 by John Arbash Meinel
Update WorkingTree.set_parent_trees() to directly cache inv.
1735
                xml = self._create_basis_xml_from_inventory(new_revision, inv)
1736
            self._write_basis_inventory(xml)
1908.1.1 by Robert Collins
Relax WorkingTree.set_last-revision to allow any revision to be set.
1737
        except (errors.NoSuchRevision, errors.RevisionNotPresent):
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
1738
            pass
1739
1638.1.2 by Robert Collins
Change the basis-inventory file to not have the revision-id in the file name.
1740
    def read_basis_inventory(self):
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
1741
        """Read the cached basis inventory."""
1638.1.2 by Robert Collins
Change the basis-inventory file to not have the revision-id in the file name.
1742
        path = self._basis_inventory_name()
1757.1.3 by Robert Collins
Dont treat the basis inventory xml as ascii - its utf8 and should be preserved as such.
1743
        return self._control_files.get(path).read()
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
1744
        
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1745
    @needs_read_lock
1746
    def read_working_inventory(self):
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
1747
        """Read the working inventory.
1748
        
1986.5.7 by Robert Collins
Merge reviews.
1749
        :raises errors.InventoryModified: read_working_inventory will fail
1750
            when the current in memory inventory has been modified.
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
1751
        """
1752
        # conceptually this should be an implementation detail of the tree. 
1753
        # XXX: Deprecate this.
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1754
        # ElementTree does its own conversion from UTF-8, so open in
1755
        # binary.
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
1756
        if self._inventory_is_modified:
1757
            raise errors.InventoryModified(self)
2100.3.10 by Aaron Bentley
Ensure added references are serialized properly, beef up Workingtreee3
1758
        result = self._deserialize(self._control_files.get('inventory'))
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
1759
        self._set_inventory(result, dirty=False)
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1760
        return result
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1761
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
1762
    @needs_tree_write_lock
1685.1.77 by Wouter van Heyst
WorkingTree.remove takes an optional output file
1763
    def remove(self, files, verbose=False, to_file=None):
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1764
        """Remove nominated files from the working inventory..
1765
1766
        This does not remove their text.  This does not run on XXX on what? RBC
1767
1768
        TODO: Refuse to remove modified files unless --force is given?
1769
1770
        TODO: Do something useful with directories.
1771
1772
        TODO: Should this remove the text or not?  Tough call; not
1773
        removing may be useful and the user can just use use rm, and
1774
        is the opposite of add.  Removing it is consistent with most
1775
        other tools.  Maybe an option.
1776
        """
1777
        ## TODO: Normalize names
1778
        ## TODO: Remove nested loops; better scalability
1779
        if isinstance(files, basestring):
1780
            files = [files]
1781
1782
        inv = self.inventory
1783
1784
        # do this before any modifications
1785
        for f in files:
1786
            fid = inv.path2id(f)
1787
            if not fid:
2245.5.1 by Marius Kruger
Let bzr rm rather give a warning than an error when trying to remove a non-versioned file.
1788
                note("%s is not versioned."%f)
1789
            else:
1790
                if verbose:
1791
                    # having remove it, it must be either ignored or unknown
1792
                    if self.is_ignored(f):
1793
                        new_status = 'I'
1794
                    else:
1795
                        new_status = '?'
1796
                    textui.show_status(new_status, inv[fid].kind, f,
1797
                                       to_file=to_file)
1798
                del inv[fid]
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1799
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1800
        self._write_inventory(inv)
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1801
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
1802
    @needs_tree_write_lock
1534.9.4 by Aaron Bentley
Added progress bars to revert.
1803
    def revert(self, filenames, old_tree=None, backups=True, 
2225.1.1 by Aaron Bentley
Added revert change display, with tests
1804
               pb=DummyProgress(), report_changes=False):
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
1805
        from bzrlib.conflicts import resolve
1501 by Robert Collins
Move revert from Branch to WorkingTree.
1806
        if old_tree is None:
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1807
            old_tree = self.basis_tree()
2225.1.1 by Aaron Bentley
Added revert change display, with tests
1808
        conflicts = transform.revert(self, old_tree, filenames, backups, pb,
1809
                                     report_changes)
1457.1.8 by Robert Collins
Replace the WorkingTree.revert method algorithm with a call to merge_inner.
1810
        if not len(filenames):
1908.6.7 by Robert Collins
Remove all users of set_pending_merges and add_pending_merge except tests that they work correctly.
1811
            self.set_parent_ids(self.get_parent_ids()[:1])
1534.10.14 by Aaron Bentley
Made revert clear conflicts
1812
            resolve(self)
1813
        else:
1534.10.15 by Aaron Bentley
Revert does resolve
1814
            resolve(self, filenames, ignore_misses=True)
1558.7.13 by Aaron Bentley
WorkingTree.revert returns conflicts
1815
        return conflicts
1501 by Robert Collins
Move revert from Branch to WorkingTree.
1816
1908.11.2 by Robert Collins
Implement WorkingTree interface conformance tests for
1817
    def revision_tree(self, revision_id):
1818
        """See Tree.revision_tree.
1819
1820
        WorkingTree can supply revision_trees for the basis revision only
1821
        because there is only one cached inventory in the bzr directory.
1822
        """
1823
        if revision_id == self.last_revision():
1824
            try:
1825
                xml = self.read_basis_inventory()
1852.16.5 by John Arbash Meinel
[merge] bzr.dev 2255, resolve conflicts, update copyrights
1826
            except errors.NoSuchFile:
1908.11.2 by Robert Collins
Implement WorkingTree interface conformance tests for
1827
                pass
1828
            else:
1908.11.3 by Robert Collins
Merge bzr.dev
1829
                try:
1908.11.6 by John Arbash Meinel
Fix an invalid access to bzrlib.xml6 in workingtree.py
1830
                    inv = xml6.serializer_v6.read_inventory_from_string(xml)
1908.11.3 by Robert Collins
Merge bzr.dev
1831
                    # dont use the repository revision_tree api because we want
1832
                    # to supply the inventory.
1833
                    if inv.revision_id == revision_id:
1908.11.5 by John Arbash Meinel
[merge] bzr.dev 2240
1834
                        return revisiontree.RevisionTree(self.branch.repository,
1908.11.3 by Robert Collins
Merge bzr.dev
1835
                            inv, revision_id)
1836
                except errors.BadInventoryFormat:
1837
                    pass
1908.11.2 by Robert Collins
Implement WorkingTree interface conformance tests for
1838
        # raise if there was no inventory, or if we read the wrong inventory.
1839
        raise errors.NoSuchRevisionInTree(self, revision_id)
1840
1658.1.3 by Martin Pool
Doc
1841
    # XXX: This method should be deprecated in favour of taking in a proper
1842
    # new Inventory object.
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
1843
    @needs_tree_write_lock
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1844
    def set_inventory(self, new_inventory_list):
1845
        from bzrlib.inventory import (Inventory,
1846
                                      InventoryDirectory,
1847
                                      InventoryEntry,
1848
                                      InventoryFile,
1849
                                      InventoryLink)
1850
        inv = Inventory(self.get_root_id())
1658.1.2 by Martin Pool
Revert changes to WorkingTree.set_inventory to unbreak bzrtools
1851
        for path, file_id, parent, kind in new_inventory_list:
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1852
            name = os.path.basename(path)
1853
            if name == "":
1854
                continue
1855
            # fixme, there should be a factory function inv,add_?? 
1856
            if kind == 'directory':
1857
                inv.add(InventoryDirectory(file_id, name, parent))
1858
            elif kind == 'file':
1658.1.2 by Martin Pool
Revert changes to WorkingTree.set_inventory to unbreak bzrtools
1859
                inv.add(InventoryFile(file_id, name, parent))
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1860
            elif kind == 'symlink':
1861
                inv.add(InventoryLink(file_id, name, parent))
1862
            else:
2206.1.7 by Marius Kruger
* errors
1863
                raise errors.BzrError("unknown kind %r" % kind)
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1864
        self._write_inventory(inv)
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1865
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
1866
    @needs_tree_write_lock
1457.1.10 by Robert Collins
Move set_root_id to WorkingTree.
1867
    def set_root_id(self, file_id):
1868
        """Set the root id for this tree."""
1986.5.2 by Robert Collins
``WorkingTree.set_root_id(None)`` is now deprecated. Please
1869
        # for compatability 
1870
        if file_id is None:
1871
            symbol_versioning.warn(symbol_versioning.zero_twelve
1872
                % 'WorkingTree.set_root_id with fileid=None',
1873
                DeprecationWarning,
1874
                stacklevel=3)
1875
            file_id = ROOT_ID
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
1876
        else:
1877
            file_id = osutils.safe_file_id(file_id)
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
1878
        self._set_root_id(file_id)
1879
1880
    def _set_root_id(self, file_id):
1881
        """Set the root id for this tree, in a format specific manner.
1882
1883
        :param file_id: The file id to assign to the root. It must not be 
1884
            present in the current inventory or an error will occur. It must
1885
            not be None, but rather a valid file id.
1886
        """
1986.5.2 by Robert Collins
``WorkingTree.set_root_id(None)`` is now deprecated. Please
1887
        inv = self._inventory
1457.1.10 by Robert Collins
Move set_root_id to WorkingTree.
1888
        orig_root_id = inv.root.file_id
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
1889
        # TODO: it might be nice to exit early if there was nothing
1890
        # to do, saving us from trigger a sync on unlock.
1891
        self._inventory_is_modified = True
1892
        # we preserve the root inventory entry object, but
1893
        # unlinkit from the byid index
1457.1.10 by Robert Collins
Move set_root_id to WorkingTree.
1894
        del inv._byid[inv.root.file_id]
1895
        inv.root.file_id = file_id
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
1896
        # and link it into the index with the new changed id.
1457.1.10 by Robert Collins
Move set_root_id to WorkingTree.
1897
        inv._byid[inv.root.file_id] = inv.root
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
1898
        # and finally update all children to reference the new id.
1899
        # XXX: this should be safe to just look at the root.children
1900
        # list, not the WHOLE INVENTORY.
1457.1.10 by Robert Collins
Move set_root_id to WorkingTree.
1901
        for fid in inv:
1902
            entry = inv[fid]
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1903
            if entry.parent_id == orig_root_id:
1457.1.10 by Robert Collins
Move set_root_id to WorkingTree.
1904
                entry.parent_id = inv.root.file_id
1905
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1906
    def unlock(self):
1907
        """See Branch.unlock.
1908
        
1909
        WorkingTree locking just uses the Branch locking facilities.
1910
        This is current because all working trees have an embedded branch
1911
        within them. IF in the future, we were to make branch data shareable
1912
        between multiple working trees, i.e. via shared storage, then we 
1913
        would probably want to lock both the local tree, and the branch.
1914
        """
1852.4.2 by Robert Collins
Refactor workingtree.unlock to be cleaner, adding a trivial test for unlock. Introduces an explicit Format2 tree type, making the base WorkingTree cleaner to derive from.
1915
        raise NotImplementedError(self.unlock)
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1916
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1917
    def update(self):
1587.1.11 by Robert Collins
Local commits appear to be working properly.
1918
        """Update a working tree along its branch.
1919
1731.1.33 by Aaron Bentley
Revert no-special-root changes
1920
        This will update the branch if its bound too, which means we have
1921
        multiple trees involved:
1922
1923
        - The new basis tree of the master.
1924
        - The old basis tree of the branch.
1925
        - The old basis tree of the working tree.
1926
        - The current working tree state.
1927
1928
        Pathologically, all three may be different, and non-ancestors of each
1929
        other.  Conceptually we want to:
1930
1931
        - Preserve the wt.basis->wt.state changes
1932
        - Transform the wt.basis to the new master basis.
1933
        - Apply a merge of the old branch basis to get any 'local' changes from
1934
          it into the tree.
1935
        - Restore the wt.basis->wt.state changes.
1587.1.11 by Robert Collins
Local commits appear to be working properly.
1936
1937
        There isn't a single operation at the moment to do that, so we:
1731.1.33 by Aaron Bentley
Revert no-special-root changes
1938
        - Merge current state -> basis tree of the master w.r.t. the old tree
1939
          basis.
1940
        - Do a 'normal' merge of the old branch basis if it is relevant.
1587.1.11 by Robert Collins
Local commits appear to be working properly.
1941
        """
2084.2.1 by Aaron Bentley
Support updating lightweight checkouts of readonly branches
1942
        if self.branch.get_master_branch() is not None:
1943
            self.lock_write()
1944
            update_branch = True
1945
        else:
1946
            self.lock_tree_write()
1947
            update_branch = False
1948
        try:
1949
            if update_branch:
1950
                old_tip = self.branch.update()
1951
            else:
1952
                old_tip = None
1953
            return self._update_tree(old_tip)
1954
        finally:
1955
            self.unlock()
1956
1957
    @needs_tree_write_lock
1958
    def _update_tree(self, old_tip=None):
1959
        """Update a tree to the master branch.
1960
1961
        :param old_tip: if supplied, the previous tip revision the branch,
1962
            before it was changed to the master branch's tip.
1963
        """
1927.2.3 by Robert Collins
review comment application - paired with Martin.
1964
        # here if old_tip is not None, it is the old tip of the branch before
1965
        # it was updated from the master branch. This should become a pending
1966
        # merge in the working tree to preserve the user existing work.  we
1967
        # cant set that until we update the working trees last revision to be
1968
        # one from the new branch, because it will just get absorbed by the
1969
        # parent de-duplication logic.
1970
        # 
1971
        # We MUST save it even if an error occurs, because otherwise the users
1972
        # local work is unreferenced and will appear to have been lost.
1973
        # 
1974
        result = 0
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
1975
        try:
1976
            last_rev = self.get_parent_ids()[0]
1977
        except IndexError:
1978
            last_rev = None
1979
        if last_rev != self.branch.last_revision():
1927.2.3 by Robert Collins
review comment application - paired with Martin.
1980
            # merge tree state up to new branch tip.
1981
            basis = self.basis_tree()
2255.2.44 by Robert Collins
Fix tree unlock on readonly Format4 trees with dirty hashcache.
1982
            basis.lock_read()
1983
            try:
1984
                to_tree = self.branch.basis_tree()
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
1985
                if basis.inventory.root is None and self.inventory.root is None:
2255.2.44 by Robert Collins
Fix tree unlock on readonly Format4 trees with dirty hashcache.
1986
                    self.set_root_id(to_tree.inventory.root.file_id)
1987
                result += merge.merge_inner(
1988
                                      self.branch,
1989
                                      to_tree,
1990
                                      basis,
1991
                                      this_tree=self)
1992
            finally:
1993
                basis.unlock()
1908.6.6 by Robert Collins
Merge updated set_parents api.
1994
            # TODO - dedup parents list with things merged by pull ?
1995
            # reuse the tree we've updated to to set the basis:
1996
            parent_trees = [(self.branch.last_revision(), to_tree)]
1997
            merges = self.get_parent_ids()[1:]
1998
            # Ideally we ask the tree for the trees here, that way the working
1999
            # tree can decide whether to give us teh entire tree or give us a
2000
            # lazy initialised tree. dirstate for instance will have the trees
2001
            # in ram already, whereas a last-revision + basis-inventory tree
2002
            # will not, but also does not need them when setting parents.
2003
            for parent in merges:
2004
                parent_trees.append(
2005
                    (parent, self.branch.repository.revision_tree(parent)))
2006
            if old_tip is not None:
2007
                parent_trees.append(
2008
                    (old_tip, self.branch.repository.revision_tree(old_tip)))
2009
            self.set_parent_trees(parent_trees)
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
2010
            last_rev = parent_trees[0][0]
1927.2.3 by Robert Collins
review comment application - paired with Martin.
2011
        else:
2012
            # the working tree had the same last-revision as the master
2013
            # branch did. We may still have pivot local work from the local
2014
            # branch into old_tip:
1927.2.1 by Robert Collins
Alter set_pending_merges to shove the left most merge into the trees last-revision if that is not set. Related bugfixes include basis_tree handling ghosts, de-duping the merges with the last-revision and update changing where and how it adds its pending merge.
2015
            if old_tip is not None:
1908.6.7 by Robert Collins
Remove all users of set_pending_merges and add_pending_merge except tests that they work correctly.
2016
                self.add_parent_tree_id(old_tip)
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
2017
        if old_tip and old_tip != last_rev:
1927.2.3 by Robert Collins
review comment application - paired with Martin.
2018
            # our last revision was not the prior branch last revision
2019
            # and we have converted that last revision to a pending merge.
2020
            # base is somewhere between the branch tip now
2021
            # and the now pending merge
2255.2.55 by John Arbash Meinel
add extra flush() call to make _update_tree work for dirstate.
2022
2023
            # Since we just modified the working tree and inventory, flush out
2024
            # the current state, before we modify it again.
2025
            # TODO: jam 20070214 WorkingTree3 doesn't require this, dirstate
2026
            #       requires it only because TreeTransform directly munges the
2027
            #       inventory and calls tree._write_inventory(). Ultimately we
2028
            #       should be able to remove this extra flush.
2029
            self.flush()
1927.2.3 by Robert Collins
review comment application - paired with Martin.
2030
            from bzrlib.revision import common_ancestor
2031
            try:
2032
                base_rev_id = common_ancestor(self.branch.last_revision(),
2033
                                              old_tip,
2034
                                              self.branch.repository)
2035
            except errors.NoCommonAncestor:
2036
                base_rev_id = None
2037
            base_tree = self.branch.repository.revision_tree(base_rev_id)
2038
            other_tree = self.branch.repository.revision_tree(old_tip)
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
2039
            result += merge.merge_inner(
2040
                                  self.branch,
1927.2.3 by Robert Collins
review comment application - paired with Martin.
2041
                                  other_tree,
2042
                                  base_tree,
2043
                                  this_tree=self)
2044
        return result
1508.1.24 by Robert Collins
Add update command for use with checkouts.
2045
2201.1.1 by John Arbash Meinel
Fix bug #76299 by ignoring write errors during readonly hashcache write.
2046
    def _write_hashcache_if_dirty(self):
2047
        """Write out the hashcache if it is dirty."""
2048
        if self._hashcache.needs_write:
2049
            try:
2050
                self._hashcache.write()
2051
            except OSError, e:
2052
                if e.errno not in (errno.EPERM, errno.EACCES):
2053
                    raise
2054
                # TODO: jam 20061219 Should this be a warning? A single line
2055
                #       warning might be sufficient to let the user know what
2056
                #       is going on.
2057
                mutter('Could not write hashcache for %s\nError: %s',
2058
                       self._hashcache.cache_file_name(), e)
2059
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
2060
    @needs_tree_write_lock
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
2061
    def _write_inventory(self, inv):
2062
        """Write inventory as the current inventory."""
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
2063
        self._set_inventory(inv, dirty=True)
2064
        self.flush()
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
2065
1534.10.22 by Aaron Bentley
Got ConflictList implemented
2066
    def set_conflicts(self, arg):
2206.1.7 by Marius Kruger
* errors
2067
        raise errors.UnsupportedOperation(self.set_conflicts, self)
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
2068
1551.7.11 by Aaron Bentley
Add WorkingTree.add_conflicts
2069
    def add_conflicts(self, arg):
2206.1.7 by Marius Kruger
* errors
2070
        raise errors.UnsupportedOperation(self.add_conflicts, self)
1551.7.11 by Aaron Bentley
Add WorkingTree.add_conflicts
2071
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
2072
    @needs_read_lock
1534.10.22 by Aaron Bentley
Got ConflictList implemented
2073
    def conflicts(self):
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
2074
        conflicts = _mod_conflicts.ConflictList()
1534.10.9 by Aaron Bentley
Switched display functions to conflict_lines
2075
        for conflicted in self._iter_conflicts():
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
2076
            text = True
2077
            try:
2078
                if file_kind(self.abspath(conflicted)) != "file":
2079
                    text = False
1757.2.4 by Robert Collins
Teach file_kind about NoSuchFile, reducing duplicate code, and add user files before entering the main loop in smart_add.
2080
            except errors.NoSuchFile:
2081
                text = False
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
2082
            if text is True:
2083
                for suffix in ('.THIS', '.OTHER'):
2084
                    try:
2085
                        kind = file_kind(self.abspath(conflicted+suffix))
1757.2.4 by Robert Collins
Teach file_kind about NoSuchFile, reducing duplicate code, and add user files before entering the main loop in smart_add.
2086
                        if kind != "file":
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
2087
                            text = False
1757.2.4 by Robert Collins
Teach file_kind about NoSuchFile, reducing duplicate code, and add user files before entering the main loop in smart_add.
2088
                    except errors.NoSuchFile:
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
2089
                        text = False
1757.2.4 by Robert Collins
Teach file_kind about NoSuchFile, reducing duplicate code, and add user files before entering the main loop in smart_add.
2090
                    if text == False:
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
2091
                        break
2092
            ctype = {True: 'text conflict', False: 'contents conflict'}[text]
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
2093
            conflicts.append(_mod_conflicts.Conflict.factory(ctype,
2094
                             path=conflicted,
1534.10.22 by Aaron Bentley
Got ConflictList implemented
2095
                             file_id=self.path2id(conflicted)))
2096
        return conflicts
2097
1852.15.3 by Robert Collins
Add a first-cut Tree.walkdirs method.
2098
    def walkdirs(self, prefix=""):
2255.2.18 by Robert Collins
Dirstate: all tree_implementation tests passing.
2099
        """Walk the directories of this tree.
2100
2101
        This API returns a generator, which is only valid during the current
2102
        tree transaction - within a single lock_read or lock_write duration.
2103
2104
        If the tree is not locked, it may cause an error to be raised, depending
2105
        on the tree implementation.
2106
        """
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
2107
        disk_top = self.abspath(prefix)
2108
        if disk_top.endswith('/'):
2109
            disk_top = disk_top[:-1]
2110
        top_strip_len = len(disk_top) + 1
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
2111
        inventory_iterator = self._walkdirs(prefix)
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
2112
        disk_iterator = osutils.walkdirs(disk_top, prefix)
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
2113
        try:
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
2114
            current_disk = disk_iterator.next()
2115
            disk_finished = False
2116
        except OSError, e:
2117
            if e.errno != errno.ENOENT:
2118
                raise
2119
            current_disk = None
2120
            disk_finished = True
2121
        try:
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
2122
            current_inv = inventory_iterator.next()
2123
            inv_finished = False
2124
        except StopIteration:
2125
            current_inv = None
2126
            inv_finished = True
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
2127
        while not inv_finished or not disk_finished:
2128
            if not disk_finished:
2129
                # strip out .bzr dirs
2130
                if current_disk[0][1][top_strip_len:] == '':
2131
                    # osutils.walkdirs can be made nicer - 
2132
                    # yield the path-from-prefix rather than the pathjoined
2133
                    # value.
2134
                    bzrdir_loc = bisect_left(current_disk[1], ('.bzr', '.bzr'))
2135
                    if current_disk[1][bzrdir_loc][0] == '.bzr':
2136
                        # we dont yield the contents of, or, .bzr itself.
2137
                        del current_disk[1][bzrdir_loc]
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
2138
            if inv_finished:
2139
                # everything is unknown
1852.15.12 by Robert Collins
WorkingTree.walkdirs handling of changing file kinds, and multi-directory with missing and unknown ordering bugfix.
2140
                direction = 1
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
2141
            elif disk_finished:
2142
                # everything is missing
1852.15.12 by Robert Collins
WorkingTree.walkdirs handling of changing file kinds, and multi-directory with missing and unknown ordering bugfix.
2143
                direction = -1
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
2144
            else:
2145
                direction = cmp(current_inv[0][0], current_disk[0][0])
1852.15.12 by Robert Collins
WorkingTree.walkdirs handling of changing file kinds, and multi-directory with missing and unknown ordering bugfix.
2146
            if direction > 0:
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
2147
                # disk is before inventory - unknown
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
2148
                dirblock = [(relpath, basename, kind, stat, None, None) for
2149
                    relpath, basename, kind, stat, top_path in current_disk[1]]
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
2150
                yield (current_disk[0][0], None), dirblock
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
2151
                try:
2152
                    current_disk = disk_iterator.next()
2153
                except StopIteration:
2154
                    disk_finished = True
1852.15.12 by Robert Collins
WorkingTree.walkdirs handling of changing file kinds, and multi-directory with missing and unknown ordering bugfix.
2155
            elif direction < 0:
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
2156
                # inventory is before disk - missing.
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
2157
                dirblock = [(relpath, basename, 'unknown', None, fileid, kind)
2158
                    for relpath, basename, dkind, stat, fileid, kind in 
2159
                    current_inv[1]]
2160
                yield (current_inv[0][0], current_inv[0][1]), dirblock
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
2161
                try:
2162
                    current_inv = inventory_iterator.next()
2163
                except StopIteration:
2164
                    inv_finished = True
2165
            else:
2166
                # versioned present directory
2167
                # merge the inventory and disk data together
2168
                dirblock = []
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
2169
                for relpath, subiterator in itertools.groupby(sorted(
1852.15.12 by Robert Collins
WorkingTree.walkdirs handling of changing file kinds, and multi-directory with missing and unknown ordering bugfix.
2170
                    current_inv[1] + current_disk[1], key=operator.itemgetter(0)), operator.itemgetter(1)):
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
2171
                    path_elements = list(subiterator)
2172
                    if len(path_elements) == 2:
1852.15.12 by Robert Collins
WorkingTree.walkdirs handling of changing file kinds, and multi-directory with missing and unknown ordering bugfix.
2173
                        inv_row, disk_row = path_elements
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
2174
                        # versioned, present file
1852.15.12 by Robert Collins
WorkingTree.walkdirs handling of changing file kinds, and multi-directory with missing and unknown ordering bugfix.
2175
                        dirblock.append((inv_row[0],
2176
                            inv_row[1], disk_row[2],
2177
                            disk_row[3], inv_row[4],
2178
                            inv_row[5]))
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
2179
                    elif len(path_elements[0]) == 5:
2180
                        # unknown disk file
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
2181
                        dirblock.append((path_elements[0][0],
2182
                            path_elements[0][1], path_elements[0][2],
2183
                            path_elements[0][3], None, None))
2184
                    elif len(path_elements[0]) == 6:
2185
                        # versioned, absent file.
2186
                        dirblock.append((path_elements[0][0],
2187
                            path_elements[0][1], 'unknown', None,
2188
                            path_elements[0][4], path_elements[0][5]))
2189
                    else:
2190
                        raise NotImplementedError('unreachable code')
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
2191
                yield current_inv[0], dirblock
2192
                try:
2193
                    current_inv = inventory_iterator.next()
2194
                except StopIteration:
2195
                    inv_finished = True
2196
                try:
2197
                    current_disk = disk_iterator.next()
2198
                except StopIteration:
2199
                    disk_finished = True
2200
2201
    def _walkdirs(self, prefix=""):
1852.15.3 by Robert Collins
Add a first-cut Tree.walkdirs method.
2202
        _directory = 'directory'
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
2203
        # get the root in the inventory
1852.15.3 by Robert Collins
Add a first-cut Tree.walkdirs method.
2204
        inv = self.inventory
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
2205
        top_id = inv.path2id(prefix)
2206
        if top_id is None:
2207
            pending = []
2208
        else:
2209
            pending = [(prefix, '', _directory, None, top_id, None)]
1852.15.3 by Robert Collins
Add a first-cut Tree.walkdirs method.
2210
        while pending:
2211
            dirblock = []
2212
            currentdir = pending.pop()
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
2213
            # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-id, 5-kind
2214
            top_id = currentdir[4]
1852.15.3 by Robert Collins
Add a first-cut Tree.walkdirs method.
2215
            if currentdir[0]:
2216
                relroot = currentdir[0] + '/'
2217
            else:
2218
                relroot = ""
2219
            # FIXME: stash the node in pending
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
2220
            entry = inv[top_id]
1852.15.3 by Robert Collins
Add a first-cut Tree.walkdirs method.
2221
            for name, child in entry.sorted_children():
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
2222
                dirblock.append((relroot + name, name, child.kind, None,
1852.15.3 by Robert Collins
Add a first-cut Tree.walkdirs method.
2223
                    child.file_id, child.kind
2224
                    ))
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
2225
            yield (currentdir[0], entry.file_id), dirblock
1852.15.3 by Robert Collins
Add a first-cut Tree.walkdirs method.
2226
            # push the user specified dirs from dirblock
2227
            for dir in reversed(dirblock):
2228
                if dir[2] == _directory:
2229
                    pending.append(dir)
2230
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
2231
1852.4.2 by Robert Collins
Refactor workingtree.unlock to be cleaner, adding a trivial test for unlock. Introduces an explicit Format2 tree type, making the base WorkingTree cleaner to derive from.
2232
class WorkingTree2(WorkingTree):
2233
    """This is the Format 2 working tree.
2234
2235
    This was the first weave based working tree. 
2236
     - uses os locks for locking.
2237
     - uses the branch last-revision.
2238
    """
2239
1997.1.1 by Robert Collins
Add WorkingTree.lock_tree_write.
2240
    def lock_tree_write(self):
2241
        """See WorkingTree.lock_tree_write().
2242
2243
        In Format2 WorkingTrees we have a single lock for the branch and tree
2244
        so lock_tree_write() degrades to lock_write().
2245
        """
2246
        self.branch.lock_write()
2247
        try:
2248
            return self._control_files.lock_write()
2249
        except:
2250
            self.branch.unlock()
2251
            raise
2252
1852.4.2 by Robert Collins
Refactor workingtree.unlock to be cleaner, adding a trivial test for unlock. Introduces an explicit Format2 tree type, making the base WorkingTree cleaner to derive from.
2253
    def unlock(self):
2254
        # we share control files:
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
2255
        if self._control_files._lock_count == 3:
2256
            # _inventory_is_modified is always False during a read lock.
2257
            if self._inventory_is_modified:
2258
                self.flush()
2201.1.1 by John Arbash Meinel
Fix bug #76299 by ignoring write errors during readonly hashcache write.
2259
            self._write_hashcache_if_dirty()
2260
                    
1852.4.2 by Robert Collins
Refactor workingtree.unlock to be cleaner, adding a trivial test for unlock. Introduces an explicit Format2 tree type, making the base WorkingTree cleaner to derive from.
2261
        # reverse order of locking.
2262
        try:
2263
            return self._control_files.unlock()
2264
        finally:
2265
            self.branch.unlock()
2266
2267
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
2268
class WorkingTree3(WorkingTree):
2269
    """This is the Format 3 working tree.
2270
2271
    This differs from the base WorkingTree by:
2272
     - having its own file lock
2273
     - having its own last-revision property.
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
2274
2275
    This is new in bzr 0.8
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
2276
    """
2277
2278
    @needs_read_lock
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
2279
    def _last_revision(self):
1986.1.6 by Robert Collins
Add MemoryTree.last_revision.
2280
        """See Mutable.last_revision."""
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
2281
        try:
2249.5.9 by John Arbash Meinel
Update WorkingTree to use safe_revision_id when appropriate
2282
            return osutils.safe_revision_id(
2283
                        self._control_files.get('last-revision').read())
2206.1.7 by Marius Kruger
* errors
2284
        except errors.NoSuchFile:
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
2285
            return None
2286
2287
    def _change_last_revision(self, revision_id):
2288
        """See WorkingTree._change_last_revision."""
2289
        if revision_id is None or revision_id == NULL_REVISION:
2290
            try:
2291
                self._control_files._transport.delete('last-revision')
2292
            except errors.NoSuchFile:
2293
                pass
2294
            return False
2295
        else:
2294.1.1 by John Arbash Meinel
Track down some non-ascii deficiencies in commit logic.
2296
            self._control_files.put_bytes('last-revision', revision_id)
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
2297
            return True
2298
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
2299
    @needs_tree_write_lock
1534.10.22 by Aaron Bentley
Got ConflictList implemented
2300
    def set_conflicts(self, conflicts):
2301
        self._put_rio('conflicts', conflicts.to_stanzas(), 
1534.10.21 by Aaron Bentley
Moved and renamed conflict functions
2302
                      CONFLICT_HEADER_1)
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
2303
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
2304
    @needs_tree_write_lock
1551.7.11 by Aaron Bentley
Add WorkingTree.add_conflicts
2305
    def add_conflicts(self, new_conflicts):
2306
        conflict_set = set(self.conflicts())
2307
        conflict_set.update(set(list(new_conflicts)))
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
2308
        self.set_conflicts(_mod_conflicts.ConflictList(sorted(conflict_set,
2309
                                       key=_mod_conflicts.Conflict.sort_key)))
1551.7.11 by Aaron Bentley
Add WorkingTree.add_conflicts
2310
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
2311
    @needs_read_lock
1534.10.22 by Aaron Bentley
Got ConflictList implemented
2312
    def conflicts(self):
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
2313
        try:
2314
            confile = self._control_files.get('conflicts')
2206.1.7 by Marius Kruger
* errors
2315
        except errors.NoSuchFile:
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
2316
            return _mod_conflicts.ConflictList()
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
2317
        try:
2318
            if confile.next() != CONFLICT_HEADER_1 + '\n':
2206.1.7 by Marius Kruger
* errors
2319
                raise errors.ConflictFormatError()
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
2320
        except StopIteration:
2206.1.7 by Marius Kruger
* errors
2321
            raise errors.ConflictFormatError()
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
2322
        return _mod_conflicts.ConflictList.from_stanzas(RioReader(confile))
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
2323
1852.4.2 by Robert Collins
Refactor workingtree.unlock to be cleaner, adding a trivial test for unlock. Introduces an explicit Format2 tree type, making the base WorkingTree cleaner to derive from.
2324
    def unlock(self):
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
2325
        if self._control_files._lock_count == 1:
2326
            # _inventory_is_modified is always False during a read lock.
2327
            if self._inventory_is_modified:
2328
                self.flush()
2201.1.1 by John Arbash Meinel
Fix bug #76299 by ignoring write errors during readonly hashcache write.
2329
            self._write_hashcache_if_dirty()
1852.4.2 by Robert Collins
Refactor workingtree.unlock to be cleaner, adding a trivial test for unlock. Introduces an explicit Format2 tree type, making the base WorkingTree cleaner to derive from.
2330
        # reverse order of locking.
2331
        try:
2332
            return self._control_files.unlock()
2333
        finally:
2334
            self.branch.unlock()
2335
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
2336
2100.3.37 by Aaron Bentley
rename working tree format 4 to AB1 everywhere
2337
class WorkingTreeAB1(WorkingTree3):
2100.3.8 by Aaron Bentley
Add add_reference
2338
2100.3.20 by Aaron Bentley
Implement tree comparison for tree references
2339
    def _serialize(self, inventory, out_file):
2340
        xml7.serializer_v7.write_inventory(self._inventory, out_file)
2341
2342
    def _deserialize(selt, in_file):
2343
        return xml7.serializer_v7.read_inventory(in_file)
2344
2345
    def _comparison_data(self, entry, path):
2346
        kind, executable, stat_value = \
2347
            WorkingTree3._comparison_data(self, entry, path)
2348
        if kind == 'directory' and entry.kind == 'tree-reference':
2349
            kind = 'tree-reference'
2350
        return kind, executable, stat_value
2351
2100.3.31 by Aaron Bentley
Merged bzr.dev (17 tests failing)
2352
    def kind(self, file_id):
2353
        kind = WorkingTree3.kind(self, file_id)
2354
        if kind == 'directory':
2355
            entry = self.inventory[file_id]
2356
            if entry.kind == 'tree-reference':
2357
                kind = 'tree-reference'
2358
        return kind
2359
2100.3.8 by Aaron Bentley
Add add_reference
2360
    def add_reference(self, sub_tree):
2361
        try:
2362
            sub_tree_path = self.relpath(sub_tree.basedir)
2363
        except errors.PathNotChild:
2364
            raise errors.BadReferenceTarget(self, sub_tree, 
2365
                                            'Target not inside tree.')
2366
        parent_id = self.path2id(osutils.dirname(sub_tree_path))
2367
        name = osutils.basename(sub_tree_path)
2368
        sub_tree_id = sub_tree.get_root_id()
2369
        if sub_tree_id == self.get_root_id():
2370
            raise errors.BadReferenceTarget(self, sub_tree, 
2371
                                     'Trees have the same root id.')
2372
        if sub_tree_id in self.inventory:
2373
            raise errors.BadReferenceTarget(self, sub_tree, 
2374
                                            'Root id already present in tree')
2375
        entry = TreeReference(sub_tree_id, name, parent_id, None, 
2376
                              None)
2377
        self.inventory.add(entry)
2100.3.10 by Aaron Bentley
Ensure added references are serialized properly, beef up Workingtreee3
2378
        self._write_inventory(self.inventory)
2379
2100.3.27 by Aaron Bentley
Enable nested commits
2380
    def get_nested_tree(self, entry, path=None):
2381
        if path is None:
2382
            path = self.id2path(entry.file_id)
2383
        return WorkingTree.open(self.abspath(path))
2384
2100.3.20 by Aaron Bentley
Implement tree comparison for tree references
2385
    def get_reference_revision(self, entry, path=None):
2100.3.27 by Aaron Bentley
Enable nested commits
2386
        return self.get_nested_tree(entry, path).last_revision()
2100.3.3 by Aaron Bentley
Start of work on format 4 trees
2387
2388
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
2389
def get_conflicted_stem(path):
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
2390
    for suffix in _mod_conflicts.CONFLICT_SUFFIXES:
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
2391
        if path.endswith(suffix):
2392
            return path[:-len(suffix)]
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
2393
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
2394
1534.5.5 by Robert Collins
Move is_control_file into WorkingTree.is_control_filename and test.
2395
@deprecated_function(zero_eight)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
2396
def is_control_file(filename):
1534.5.5 by Robert Collins
Move is_control_file into WorkingTree.is_control_filename and test.
2397
    """See WorkingTree.is_control_filename(filename)."""
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
2398
    ## FIXME: better check
2399
    filename = normpath(filename)
2400
    while filename != '':
2401
        head, tail = os.path.split(filename)
2402
        ## mutter('check %r for control file' % ((head, tail),))
1534.5.5 by Robert Collins
Move is_control_file into WorkingTree.is_control_filename and test.
2403
        if tail == '.bzr':
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
2404
            return True
2405
        if filename == head:
2406
            break
2407
        filename = head
2408
    return False
2409
2410
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
2411
class WorkingTreeFormat(object):
2412
    """An encapsulation of the initialization and open routines for a format.
2413
2414
    Formats provide three things:
2415
     * An initialization routine,
2416
     * a format string,
2417
     * an open routine.
2418
2419
    Formats are placed in an dict by their format string for reference 
2420
    during workingtree opening. Its not required that these be instances, they
2421
    can be classes themselves with class methods - it simply depends on 
2422
    whether state is needed for a given format or not.
2423
2424
    Once a format is deprecated, just deprecate the initialize and open
2425
    methods on the format class. Do not deprecate the object, as the 
2426
    object will be created every time regardless.
2427
    """
2428
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2429
    _default_format = None
2430
    """The default format used for new trees."""
2431
2432
    _formats = {}
2433
    """The known formats."""
2434
2100.3.14 by Aaron Bentley
Test workingtree4 format, prevent use with old repos
2435
    requires_rich_root = False
2436
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2437
    @classmethod
2438
    def find_format(klass, a_bzrdir):
2439
        """Return the format for the working tree object in a_bzrdir."""
2440
        try:
2441
            transport = a_bzrdir.get_workingtree_transport(None)
2442
            format_string = transport.get("format").read()
2443
            return klass._formats[format_string]
2206.1.7 by Marius Kruger
* errors
2444
        except errors.NoSuchFile:
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
2445
            raise errors.NoWorkingTree(base=transport.base)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2446
        except KeyError:
1740.5.6 by Martin Pool
Clean up many exception classes.
2447
            raise errors.UnknownFormatError(format=format_string)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2448
2100.3.35 by Aaron Bentley
equality operations on bzrdir
2449
    def __eq__(self, other):
2450
        return self.__class__ is other.__class__
2451
2452
    def __ne__(self, other):
2453
        return not (self == other)
2454
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2455
    @classmethod
2456
    def get_default_format(klass):
2457
        """Return the current default format."""
2458
        return klass._default_format
2459
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
2460
    def get_format_string(self):
2461
        """Return the ASCII format string that identifies this format."""
2462
        raise NotImplementedError(self.get_format_string)
2463
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
2464
    def get_format_description(self):
2465
        """Return the short description for this format."""
2466
        raise NotImplementedError(self.get_format_description)
2467
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2468
    def is_supported(self):
2469
        """Is this format supported?
2470
2471
        Supported formats can be initialized and opened.
2472
        Unsupported formats may not support initialization or committing or 
2473
        some other features depending on the reason for not being supported.
2474
        """
2475
        return True
2476
2477
    @classmethod
2478
    def register_format(klass, format):
2479
        klass._formats[format.get_format_string()] = format
2480
2481
    @classmethod
2482
    def set_default_format(klass, format):
2483
        klass._default_format = format
2484
2485
    @classmethod
2486
    def unregister_format(klass, format):
2487
        assert klass._formats[format.get_format_string()] is format
2488
        del klass._formats[format.get_format_string()]
2489
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
2490
2491
2492
class WorkingTreeFormat2(WorkingTreeFormat):
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
2493
    """The second working tree format. 
2494
2495
    This format modified the hash cache from the format 1 hash cache.
2496
    """
2497
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
2498
    def get_format_description(self):
2499
        """See WorkingTreeFormat.get_format_description()."""
2500
        return "Working tree format 2"
2501
1692.7.9 by Martin Pool
Don't create broken standalone branches over sftp (Malone #43064)
2502
    def stub_initialize_remote(self, control_files):
2503
        """As a special workaround create critical control files for a remote working tree
2504
        
2505
        This ensures that it can later be updated and dealt with locally,
2506
        since BzrDirFormat6 and BzrDirFormat5 cannot represent dirs with 
2507
        no working tree.  (See bug #43064).
2508
        """
2509
        sio = StringIO()
2510
        inv = Inventory()
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
2511
        xml5.serializer_v5.write_inventory(inv, sio)
1692.7.9 by Martin Pool
Don't create broken standalone branches over sftp (Malone #43064)
2512
        sio.seek(0)
2513
        control_files.put('inventory', sio)
2514
2294.1.2 by John Arbash Meinel
Track down and add tests that all tree.commit() can handle
2515
        control_files.put_bytes('pending-merges', '')
1692.7.9 by Martin Pool
Don't create broken standalone branches over sftp (Malone #43064)
2516
        
2517
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
2518
    def initialize(self, a_bzrdir, revision_id=None):
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
2519
        """See WorkingTreeFormat.initialize()."""
2520
        if not isinstance(a_bzrdir.transport, LocalTransport):
2521
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
2522
        branch = a_bzrdir.open_branch()
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
2523
        if revision_id is not None:
2249.5.9 by John Arbash Meinel
Update WorkingTree to use safe_revision_id when appropriate
2524
            revision_id = osutils.safe_revision_id(revision_id)
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
2525
            branch.lock_write()
2526
            try:
2527
                revision_history = branch.revision_history()
2528
                try:
2529
                    position = revision_history.index(revision_id)
2530
                except ValueError:
2531
                    raise errors.NoSuchRevision(branch, revision_id)
2532
                branch.set_revision_history(revision_history[:position + 1])
2533
            finally:
2534
                branch.unlock()
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
2535
        revision = branch.last_revision()
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
2536
        inv = Inventory()
1852.4.2 by Robert Collins
Refactor workingtree.unlock to be cleaner, adding a trivial test for unlock. Introduces an explicit Format2 tree type, making the base WorkingTree cleaner to derive from.
2537
        wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
2538
                         branch,
2539
                         inv,
2540
                         _internal=True,
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
2541
                         _format=self,
2542
                         _bzrdir=a_bzrdir)
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
2543
        basis_tree = branch.repository.revision_tree(revision)
1731.1.33 by Aaron Bentley
Revert no-special-root changes
2544
        if basis_tree.inventory.root is not None:
1986.5.8 by Robert Collins
Merge bzr.dev.
2545
            wt.set_root_id(basis_tree.inventory.root.file_id)
2546
        # set the parent list and cache the basis tree.
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
2547
        wt.set_parent_trees([(revision, basis_tree)])
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
2548
        transform.build_tree(basis_tree, wt)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2549
        return wt
2550
2551
    def __init__(self):
2552
        super(WorkingTreeFormat2, self).__init__()
2553
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
2554
2555
    def open(self, a_bzrdir, _found=False):
2556
        """Return the WorkingTree object for a_bzrdir
2557
2558
        _found is a private parameter, do not use it. It is used to indicate
2559
               if format probing has already been done.
2560
        """
2561
        if not _found:
2562
            # we are being called directly and must probe.
2563
            raise NotImplementedError
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2564
        if not isinstance(a_bzrdir.transport, LocalTransport):
2565
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
1852.4.2 by Robert Collins
Refactor workingtree.unlock to be cleaner, adding a trivial test for unlock. Introduces an explicit Format2 tree type, making the base WorkingTree cleaner to derive from.
2566
        return WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
2567
                           _internal=True,
2568
                           _format=self,
2569
                           _bzrdir=a_bzrdir)
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
2570
2571
2572
class WorkingTreeFormat3(WorkingTreeFormat):
2573
    """The second working tree format updated to record a format marker.
2574
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
2575
    This format:
2576
        - exists within a metadir controlling .bzr
2577
        - includes an explicit version marker for the workingtree control
2578
          files, separate from the BzrDir format
2579
        - modifies the hash cache format
2580
        - is new in bzr 0.8
1852.3.1 by Robert Collins
Trivial cleanups to workingtree.py
2581
        - uses a LockDir to guard access for writes.
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
2582
    """
2583
2584
    def get_format_string(self):
2585
        """See WorkingTreeFormat.get_format_string()."""
1553.5.81 by Martin Pool
Revert change to WorkingTreeFormat3 format string; too many things want it the old way
2586
        return "Bazaar-NG Working Tree format 3"
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
2587
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
2588
    def get_format_description(self):
2589
        """See WorkingTreeFormat.get_format_description()."""
2590
        return "Working tree format 3"
2591
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
2592
    _lock_file_name = 'lock'
2593
    _lock_class = LockDir
2100.3.3 by Aaron Bentley
Start of work on format 4 trees
2594
    _tree_class = WorkingTree3
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
2595
2100.3.15 by Aaron Bentley
get test suite passing
2596
    def __get_matchingbzrdir(self):
2597
        return bzrdir.BzrDirMetaFormat1()
2598
2599
    _matchingbzrdir = property(__get_matchingbzrdir)
2600
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
2601
    def _open_control_files(self, a_bzrdir):
2602
        transport = a_bzrdir.get_workingtree_transport(None)
2603
        return LockableFiles(transport, self._lock_file_name, 
2604
                             self._lock_class)
2605
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
2606
    def initialize(self, a_bzrdir, revision_id=None):
2607
        """See WorkingTreeFormat.initialize().
2608
        
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
2609
        revision_id allows creating a working tree at a different
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
2610
        revision than the branch is at.
2611
        """
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
2612
        if not isinstance(a_bzrdir.transport, LocalTransport):
2613
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2614
        transport = a_bzrdir.get_workingtree_transport(self)
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
2615
        control_files = self._open_control_files(a_bzrdir)
2616
        control_files.create_lock()
1607.1.14 by Robert Collins
Reduce lock thrashing somewhat - drops bound branch tests lock count from 6554 to 4456 locks.
2617
        control_files.lock_write()
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2618
        control_files.put_utf8('format', self.get_format_string())
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
2619
        branch = a_bzrdir.open_branch()
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
2620
        if revision_id is None:
2621
            revision_id = branch.last_revision()
2249.5.9 by John Arbash Meinel
Update WorkingTree to use safe_revision_id when appropriate
2622
        else:
2623
            revision_id = osutils.safe_revision_id(revision_id)
2084.1.1 by John Arbash Meinel
Don't create new working trees with unique roots, because it breaks older versions of bzr
2624
        # WorkingTree3 can handle an inventory which has a unique root id.
2625
        # as of bzr 0.12. However, bzr 0.11 and earlier fail to handle
2626
        # those trees. And because there isn't a format bump inbetween, we
2627
        # are maintaining compatibility with older clients.
2628
        # inv = Inventory(root_id=gen_root_id())
2100.3.12 by Aaron Bentley
Stop generating unique roots for WorkingTree3
2629
        inv = self._initial_inventory()
2100.3.8 by Aaron Bentley
Add add_reference
2630
        wt = self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
2631
                         branch,
2632
                         inv,
2633
                         _internal=True,
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
2634
                         _format=self,
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
2635
                         _bzrdir=a_bzrdir,
2636
                         _control_files=control_files)
1997.1.4 by Robert Collins
``bzr checkout --lightweight`` now operates on readonly branches as well
2637
        wt.lock_tree_write()
1607.1.14 by Robert Collins
Reduce lock thrashing somewhat - drops bound branch tests lock count from 6554 to 4456 locks.
2638
        try:
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
2639
            basis_tree = branch.repository.revision_tree(revision_id)
1986.5.8 by Robert Collins
Merge bzr.dev.
2640
            # only set an explicit root id if there is one to set.
2641
            if basis_tree.inventory.root is not None:
2642
                wt.set_root_id(basis_tree.inventory.root.file_id)
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
2643
            if revision_id == NULL_REVISION:
1551.8.20 by Aaron Bentley
Fix BzrDir.create_workingtree for NULL_REVISION
2644
                wt.set_parent_trees([])
2645
            else:
2646
                wt.set_parent_trees([(revision_id, basis_tree)])
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
2647
            transform.build_tree(basis_tree, wt)
1607.1.14 by Robert Collins
Reduce lock thrashing somewhat - drops bound branch tests lock count from 6554 to 4456 locks.
2648
        finally:
1986.5.7 by Robert Collins
Merge reviews.
2649
            # Unlock in this order so that the unlock-triggers-flush in
1986.5.4 by Robert Collins
Update comments and unlock in a better order in tree initialization (Robert Collins, John Meinel)
2650
            # WorkingTree is given a chance to fire.
2651
            control_files.unlock()
1607.1.14 by Robert Collins
Reduce lock thrashing somewhat - drops bound branch tests lock count from 6554 to 4456 locks.
2652
            wt.unlock()
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2653
        return wt
2654
2100.3.12 by Aaron Bentley
Stop generating unique roots for WorkingTree3
2655
    def _initial_inventory(self):
2656
        return Inventory()
2657
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2658
    def __init__(self):
2659
        super(WorkingTreeFormat3, self).__init__()
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
2660
2661
    def open(self, a_bzrdir, _found=False):
2662
        """Return the WorkingTree object for a_bzrdir
2663
2664
        _found is a private parameter, do not use it. It is used to indicate
2665
               if format probing has already been done.
2666
        """
2667
        if not _found:
2668
            # we are being called directly and must probe.
2669
            raise NotImplementedError
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2670
        if not isinstance(a_bzrdir.transport, LocalTransport):
2671
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
1852.3.1 by Robert Collins
Trivial cleanups to workingtree.py
2672
        return self._open(a_bzrdir, self._open_control_files(a_bzrdir))
2673
2674
    def _open(self, a_bzrdir, control_files):
2675
        """Open the tree itself.
2676
        
2677
        :param a_bzrdir: the dir for the tree.
2678
        :param control_files: the control files for the tree.
2679
        """
2100.3.3 by Aaron Bentley
Start of work on format 4 trees
2680
        return self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
2681
                                _internal=True,
2682
                                _format=self,
2683
                                _bzrdir=a_bzrdir,
2684
                                _control_files=control_files)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2685
1534.5.1 by Robert Collins
Give info some reasonable output and tests.
2686
    def __str__(self):
2687
        return self.get_format_string()
2688
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2689
2100.3.37 by Aaron Bentley
rename working tree format 4 to AB1 everywhere
2690
class WorkingTreeFormatAB1(WorkingTreeFormat3):
2100.3.3 by Aaron Bentley
Start of work on format 4 trees
2691
    
2692
    """Working tree format that supports unique roots and nested trees"""
2693
2100.3.37 by Aaron Bentley
rename working tree format 4 to AB1 everywhere
2694
    _tree_class = WorkingTreeAB1
2100.3.3 by Aaron Bentley
Start of work on format 4 trees
2695
2100.3.14 by Aaron Bentley
Test workingtree4 format, prevent use with old repos
2696
    requires_rich_root = True
2697
2100.3.20 by Aaron Bentley
Implement tree comparison for tree references
2698
    supports_tree_reference = True
2699
2100.3.15 by Aaron Bentley
get test suite passing
2700
    def __init__(self):
2701
        WorkingTreeFormat3.__init__(self)
2702
        
2703
    def __get_matchingbzrdir(self):
2100.3.17 by Aaron Bentley
Remove get_format_*, make FormatRegistry.register_metadir vary working tree
2704
        return bzrdir.format_registry.make_bzrdir('experimental-knit3')
2100.3.15 by Aaron Bentley
get test suite passing
2705
2706
    _matchingbzrdir = property(__get_matchingbzrdir)
2707
2100.3.3 by Aaron Bentley
Start of work on format 4 trees
2708
    def get_format_string(self):
2709
        """See WorkingTreeFormat.get_format_string()."""
2100.3.37 by Aaron Bentley
rename working tree format 4 to AB1 everywhere
2710
        return "Bazaar-NG Working Tree format AB1"
2100.3.3 by Aaron Bentley
Start of work on format 4 trees
2711
2712
    def get_format_description(self):
2713
        """See WorkingTreeFormat.get_format_description()."""
2714
        return "Working tree format 4"
2715
2100.3.12 by Aaron Bentley
Stop generating unique roots for WorkingTree3
2716
    def _initial_inventory(self):
2717
        return Inventory(root_id=generate_ids.gen_root_id())
2100.3.3 by Aaron Bentley
Start of work on format 4 trees
2718
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2719
# formats which have no format string are not discoverable
2720
# and not independently creatable, so are not registered.
2721
__default_format = WorkingTreeFormat3()
2722
WorkingTreeFormat.register_format(__default_format)
1852.13.2 by Robert Collins
Introduce a WorkingTree Format 4, which is the new dirstate format.
2723
WorkingTreeFormat.register_format(WorkingTreeFormat4())
2100.3.37 by Aaron Bentley
rename working tree format 4 to AB1 everywhere
2724
WorkingTreeFormat.register_format(WorkingTreeFormatAB1())
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2725
WorkingTreeFormat.set_default_format(__default_format)
1852.13.2 by Robert Collins
Introduce a WorkingTree Format 4, which is the new dirstate format.
2726
# formats which have no format string are not discoverable
2727
# and not independently creatable, so are not registered.
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2728
_legacy_formats = [WorkingTreeFormat2(),
2729
                   ]
2730
2731
2732
class WorkingTreeTestProviderAdapter(object):
2733
    """A tool to generate a suite testing multiple workingtree formats at once.
2734
2735
    This is done by copying the test once for each transport and injecting
2736
    the transport_server, transport_readonly_server, and workingtree_format
2737
    classes into each copy. Each copy is also given a new id() to make it
2738
    easy to identify.
2739
    """
2740
2741
    def __init__(self, transport_server, transport_readonly_server, formats):
2742
        self._transport_server = transport_server
2743
        self._transport_readonly_server = transport_readonly_server
2744
        self._formats = formats
2745
    
1852.6.1 by Robert Collins
Start tree implementation tests.
2746
    def _clone_test(self, test, bzrdir_format, workingtree_format, variation):
2747
        """Clone test for adaption."""
2748
        new_test = deepcopy(test)
2749
        new_test.transport_server = self._transport_server
2750
        new_test.transport_readonly_server = self._transport_readonly_server
2751
        new_test.bzrdir_format = bzrdir_format
2752
        new_test.workingtree_format = workingtree_format
2753
        def make_new_test_id():
2754
            new_id = "%s(%s)" % (test.id(), variation)
2755
            return lambda: new_id
2756
        new_test.id = make_new_test_id()
2757
        return new_test
2758
    
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2759
    def adapt(self, test):
2760
        from bzrlib.tests import TestSuite
2761
        result = TestSuite()
2762
        for workingtree_format, bzrdir_format in self._formats:
1852.6.1 by Robert Collins
Start tree implementation tests.
2763
            new_test = self._clone_test(
2764
                test,
2765
                bzrdir_format,
2766
                workingtree_format, workingtree_format.__class__.__name__)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2767
            result.addTest(new_test)
2768
        return result