/brz/remove-bazaar

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